OSDN Git Service

/cp
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 enum template_base_result {
113   tbr_incomplete_type,
114   tbr_ambiguous_baseclass,
115   tbr_success
116 };
117
118 static void push_access_scope (tree);
119 static void pop_access_scope (tree);
120 static void push_deduction_access_scope (tree);
121 static void pop_deduction_access_scope (tree);
122 static bool resolve_overloaded_unification (tree, tree, tree, tree,
123                                             unification_kind_t, int,
124                                             bool);
125 static int try_one_overload (tree, tree, tree, tree, tree,
126                              unification_kind_t, int, bool, bool);
127 static int unify (tree, tree, tree, tree, int, bool);
128 static void add_pending_template (tree);
129 static tree reopen_tinst_level (struct tinst_level *);
130 static tree tsubst_initializer_list (tree, tree);
131 static tree get_class_bindings (tree, tree, tree);
132 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
133                                    bool, bool);
134 static void tsubst_enum (tree, tree, tree);
135 static tree add_to_template_args (tree, tree);
136 static tree add_outermost_template_args (tree, tree);
137 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
138 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
139                                              tree);
140 static int type_unification_real (tree, tree, tree, const tree *,
141                                   unsigned int, int, unification_kind_t, int,
142                                   bool);
143 static void note_template_header (int);
144 static tree convert_nontype_argument_function (tree, tree);
145 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
146 static tree convert_template_argument (tree, tree, tree,
147                                        tsubst_flags_t, int, tree);
148 static int for_each_template_parm (tree, tree_fn_t, void*,
149                                    struct pointer_set_t*, bool);
150 static tree expand_template_argument_pack (tree);
151 static tree build_template_parm_index (int, int, int, int, tree, tree);
152 static bool inline_needs_template_parms (tree);
153 static void push_inline_template_parms_recursive (tree, int);
154 static tree retrieve_local_specialization (tree);
155 static void register_local_specialization (tree, tree);
156 static hashval_t hash_specialization (const void *p);
157 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
158 static int mark_template_parm (tree, void *);
159 static int template_parm_this_level_p (tree, void *);
160 static tree tsubst_friend_function (tree, tree);
161 static tree tsubst_friend_class (tree, tree);
162 static int can_complete_type_without_circularity (tree);
163 static tree get_bindings (tree, tree, tree, bool);
164 static int template_decl_level (tree);
165 static int check_cv_quals_for_unify (int, tree, tree);
166 static void template_parm_level_and_index (tree, int*, int*);
167 static int unify_pack_expansion (tree, tree, tree,
168                                  tree, int, bool, bool, bool);
169 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
171 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
172 static void regenerate_decl_from_template (tree, tree);
173 static tree most_specialized_class (tree, tree, tsubst_flags_t);
174 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
175 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
177 static bool check_specialization_scope (void);
178 static tree process_partial_specialization (tree);
179 static void set_current_access_from_decl (tree);
180 static enum template_base_result get_template_base (tree, tree, tree, tree,
181                                                     bool , tree *);
182 static tree try_class_unification (tree, tree, tree, tree, bool);
183 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
184                                            tree, tree);
185 static bool template_template_parm_bindings_ok_p (tree, tree);
186 static int template_args_equal (tree, tree);
187 static void tsubst_default_arguments (tree);
188 static tree for_each_template_parm_r (tree *, int *, void *);
189 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
190 static void copy_default_args_to_explicit_spec (tree);
191 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
192 static int eq_local_specializations (const void *, const void *);
193 static bool dependent_template_arg_p (tree);
194 static bool any_template_arguments_need_structural_equality_p (tree);
195 static bool dependent_type_p_r (tree);
196 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
197 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
198 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
199 static tree tsubst_decl (tree, tree, tsubst_flags_t);
200 static void perform_typedefs_access_check (tree tmpl, tree targs);
201 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
202                                                         location_t);
203 static tree listify (tree);
204 static tree listify_autos (tree, tree);
205 static tree template_parm_to_arg (tree t);
206 static bool arg_from_parm_pack_p (tree, tree);
207 static tree current_template_args (void);
208 static tree fixup_template_type_parm_type (tree, int);
209 static tree fixup_template_parm_index (tree, tree, int);
210 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
211
212 /* Make the current scope suitable for access checking when we are
213    processing T.  T can be FUNCTION_DECL for instantiated function
214    template, or VAR_DECL for static member variable (need by
215    instantiate_decl).  */
216
217 static void
218 push_access_scope (tree t)
219 {
220   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
221               || TREE_CODE (t) == VAR_DECL);
222
223   if (DECL_FRIEND_CONTEXT (t))
224     push_nested_class (DECL_FRIEND_CONTEXT (t));
225   else if (DECL_CLASS_SCOPE_P (t))
226     push_nested_class (DECL_CONTEXT (t));
227   else
228     push_to_top_level ();
229
230   if (TREE_CODE (t) == FUNCTION_DECL)
231     {
232       saved_access_scope = tree_cons
233         (NULL_TREE, current_function_decl, saved_access_scope);
234       current_function_decl = t;
235     }
236 }
237
238 /* Restore the scope set up by push_access_scope.  T is the node we
239    are processing.  */
240
241 static void
242 pop_access_scope (tree t)
243 {
244   if (TREE_CODE (t) == FUNCTION_DECL)
245     {
246       current_function_decl = TREE_VALUE (saved_access_scope);
247       saved_access_scope = TREE_CHAIN (saved_access_scope);
248     }
249
250   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
251     pop_nested_class ();
252   else
253     pop_from_top_level ();
254 }
255
256 /* Do any processing required when DECL (a member template
257    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
258    to DECL, unless it is a specialization, in which case the DECL
259    itself is returned.  */
260
261 tree
262 finish_member_template_decl (tree decl)
263 {
264   if (decl == error_mark_node)
265     return error_mark_node;
266
267   gcc_assert (DECL_P (decl));
268
269   if (TREE_CODE (decl) == TYPE_DECL)
270     {
271       tree type;
272
273       type = TREE_TYPE (decl);
274       if (type == error_mark_node)
275         return error_mark_node;
276       if (MAYBE_CLASS_TYPE_P (type)
277           && CLASSTYPE_TEMPLATE_INFO (type)
278           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
279         {
280           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
281           check_member_template (tmpl);
282           return tmpl;
283         }
284       return NULL_TREE;
285     }
286   else if (TREE_CODE (decl) == FIELD_DECL)
287     error ("data member %qD cannot be a member template", decl);
288   else if (DECL_TEMPLATE_INFO (decl))
289     {
290       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
291         {
292           check_member_template (DECL_TI_TEMPLATE (decl));
293           return DECL_TI_TEMPLATE (decl);
294         }
295       else
296         return decl;
297     }
298   else
299     error ("invalid member template declaration %qD", decl);
300
301   return error_mark_node;
302 }
303
304 /* Create a template info node.  */
305
306 tree
307 build_template_info (tree template_decl, tree template_args)
308 {
309   tree result = make_node (TEMPLATE_INFO);
310   TI_TEMPLATE (result) = template_decl;
311   TI_ARGS (result) = template_args;
312   return result;
313 }
314
315 /* Return the template info node corresponding to T, whatever T is.  */
316
317 tree
318 get_template_info (const_tree t)
319 {
320   tree tinfo = NULL_TREE;
321
322   if (!t || t == error_mark_node)
323     return NULL;
324
325   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
326     tinfo = DECL_TEMPLATE_INFO (t);
327
328   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
329     t = TREE_TYPE (t);
330
331   if (TAGGED_TYPE_P (t))
332     tinfo = TYPE_TEMPLATE_INFO (t);
333   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
334     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
335
336   return tinfo;
337 }
338
339 /* Returns the template nesting level of the indicated class TYPE.
340
341    For example, in:
342      template <class T>
343      struct A
344      {
345        template <class U>
346        struct B {};
347      };
348
349    A<T>::B<U> has depth two, while A<T> has depth one.
350    Both A<T>::B<int> and A<int>::B<U> have depth one, if
351    they are instantiations, not specializations.
352
353    This function is guaranteed to return 0 if passed NULL_TREE so
354    that, for example, `template_class_depth (current_class_type)' is
355    always safe.  */
356
357 int
358 template_class_depth (tree type)
359 {
360   int depth;
361
362   for (depth = 0;
363        type && TREE_CODE (type) != NAMESPACE_DECL;
364        type = (TREE_CODE (type) == FUNCTION_DECL)
365          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
366     {
367       tree tinfo = get_template_info (type);
368
369       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
370           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
371         ++depth;
372     }
373
374   return depth;
375 }
376
377 /* Subroutine of maybe_begin_member_template_processing.
378    Returns true if processing DECL needs us to push template parms.  */
379
380 static bool
381 inline_needs_template_parms (tree decl)
382 {
383   if (! DECL_TEMPLATE_INFO (decl))
384     return false;
385
386   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
387           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
388 }
389
390 /* Subroutine of maybe_begin_member_template_processing.
391    Push the template parms in PARMS, starting from LEVELS steps into the
392    chain, and ending at the beginning, since template parms are listed
393    innermost first.  */
394
395 static void
396 push_inline_template_parms_recursive (tree parmlist, int levels)
397 {
398   tree parms = TREE_VALUE (parmlist);
399   int i;
400
401   if (levels > 1)
402     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
403
404   ++processing_template_decl;
405   current_template_parms
406     = tree_cons (size_int (processing_template_decl),
407                  parms, current_template_parms);
408   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
409
410   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
411                NULL);
412   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
413     {
414       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
415
416       if (parm == error_mark_node)
417         continue;
418
419       gcc_assert (DECL_P (parm));
420
421       switch (TREE_CODE (parm))
422         {
423         case TYPE_DECL:
424         case TEMPLATE_DECL:
425           pushdecl (parm);
426           break;
427
428         case PARM_DECL:
429           {
430             /* Make a CONST_DECL as is done in process_template_parm.
431                It is ugly that we recreate this here; the original
432                version built in process_template_parm is no longer
433                available.  */
434             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
435                                     CONST_DECL, DECL_NAME (parm),
436                                     TREE_TYPE (parm));
437             DECL_ARTIFICIAL (decl) = 1;
438             TREE_CONSTANT (decl) = 1;
439             TREE_READONLY (decl) = 1;
440             DECL_INITIAL (decl) = DECL_INITIAL (parm);
441             SET_DECL_TEMPLATE_PARM_P (decl);
442             pushdecl (decl);
443           }
444           break;
445
446         default:
447           gcc_unreachable ();
448         }
449     }
450 }
451
452 /* Restore the template parameter context for a member template or
453    a friend template defined in a class definition.  */
454
455 void
456 maybe_begin_member_template_processing (tree decl)
457 {
458   tree parms;
459   int levels = 0;
460
461   if (inline_needs_template_parms (decl))
462     {
463       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
464       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
465
466       if (DECL_TEMPLATE_SPECIALIZATION (decl))
467         {
468           --levels;
469           parms = TREE_CHAIN (parms);
470         }
471
472       push_inline_template_parms_recursive (parms, levels);
473     }
474
475   /* Remember how many levels of template parameters we pushed so that
476      we can pop them later.  */
477   VEC_safe_push (int, heap, inline_parm_levels, levels);
478 }
479
480 /* Undo the effects of maybe_begin_member_template_processing.  */
481
482 void
483 maybe_end_member_template_processing (void)
484 {
485   int i;
486   int last;
487
488   if (VEC_length (int, inline_parm_levels) == 0)
489     return;
490
491   last = VEC_pop (int, inline_parm_levels);
492   for (i = 0; i < last; ++i)
493     {
494       --processing_template_decl;
495       current_template_parms = TREE_CHAIN (current_template_parms);
496       poplevel (0, 0, 0);
497     }
498 }
499
500 /* Return a new template argument vector which contains all of ARGS,
501    but has as its innermost set of arguments the EXTRA_ARGS.  */
502
503 static tree
504 add_to_template_args (tree args, tree extra_args)
505 {
506   tree new_args;
507   int extra_depth;
508   int i;
509   int j;
510
511   if (args == NULL_TREE || extra_args == error_mark_node)
512     return extra_args;
513
514   extra_depth = TMPL_ARGS_DEPTH (extra_args);
515   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
516
517   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
518     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
519
520   for (j = 1; j <= extra_depth; ++j, ++i)
521     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
522
523   return new_args;
524 }
525
526 /* Like add_to_template_args, but only the outermost ARGS are added to
527    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
528    (EXTRA_ARGS) levels are added.  This function is used to combine
529    the template arguments from a partial instantiation with the
530    template arguments used to attain the full instantiation from the
531    partial instantiation.  */
532
533 static tree
534 add_outermost_template_args (tree args, tree extra_args)
535 {
536   tree new_args;
537
538   /* If there are more levels of EXTRA_ARGS than there are ARGS,
539      something very fishy is going on.  */
540   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
541
542   /* If *all* the new arguments will be the EXTRA_ARGS, just return
543      them.  */
544   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
545     return extra_args;
546
547   /* For the moment, we make ARGS look like it contains fewer levels.  */
548   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
549
550   new_args = add_to_template_args (args, extra_args);
551
552   /* Now, we restore ARGS to its full dimensions.  */
553   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
554
555   return new_args;
556 }
557
558 /* Return the N levels of innermost template arguments from the ARGS.  */
559
560 tree
561 get_innermost_template_args (tree args, int n)
562 {
563   tree new_args;
564   int extra_levels;
565   int i;
566
567   gcc_assert (n >= 0);
568
569   /* If N is 1, just return the innermost set of template arguments.  */
570   if (n == 1)
571     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
572
573   /* If we're not removing anything, just return the arguments we were
574      given.  */
575   extra_levels = TMPL_ARGS_DEPTH (args) - n;
576   gcc_assert (extra_levels >= 0);
577   if (extra_levels == 0)
578     return args;
579
580   /* Make a new set of arguments, not containing the outer arguments.  */
581   new_args = make_tree_vec (n);
582   for (i = 1; i <= n; ++i)
583     SET_TMPL_ARGS_LEVEL (new_args, i,
584                          TMPL_ARGS_LEVEL (args, i + extra_levels));
585
586   return new_args;
587 }
588
589 /* The inverse of get_innermost_template_args: Return all but the innermost
590    EXTRA_LEVELS levels of template arguments from the ARGS.  */
591
592 static tree
593 strip_innermost_template_args (tree args, int extra_levels)
594 {
595   tree new_args;
596   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
597   int i;
598
599   gcc_assert (n >= 0);
600
601   /* If N is 1, just return the outermost set of template arguments.  */
602   if (n == 1)
603     return TMPL_ARGS_LEVEL (args, 1);
604
605   /* If we're not removing anything, just return the arguments we were
606      given.  */
607   gcc_assert (extra_levels >= 0);
608   if (extra_levels == 0)
609     return args;
610
611   /* Make a new set of arguments, not containing the inner arguments.  */
612   new_args = make_tree_vec (n);
613   for (i = 1; i <= n; ++i)
614     SET_TMPL_ARGS_LEVEL (new_args, i,
615                          TMPL_ARGS_LEVEL (args, i));
616
617   return new_args;
618 }
619
620 /* We've got a template header coming up; push to a new level for storing
621    the parms.  */
622
623 void
624 begin_template_parm_list (void)
625 {
626   /* We use a non-tag-transparent scope here, which causes pushtag to
627      put tags in this scope, rather than in the enclosing class or
628      namespace scope.  This is the right thing, since we want
629      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
630      global template class, push_template_decl handles putting the
631      TEMPLATE_DECL into top-level scope.  For a nested template class,
632      e.g.:
633
634        template <class T> struct S1 {
635          template <class T> struct S2 {};
636        };
637
638      pushtag contains special code to call pushdecl_with_scope on the
639      TEMPLATE_DECL for S2.  */
640   begin_scope (sk_template_parms, NULL);
641   ++processing_template_decl;
642   ++processing_template_parmlist;
643   note_template_header (0);
644 }
645
646 /* This routine is called when a specialization is declared.  If it is
647    invalid to declare a specialization here, an error is reported and
648    false is returned, otherwise this routine will return true.  */
649
650 static bool
651 check_specialization_scope (void)
652 {
653   tree scope = current_scope ();
654
655   /* [temp.expl.spec]
656
657      An explicit specialization shall be declared in the namespace of
658      which the template is a member, or, for member templates, in the
659      namespace of which the enclosing class or enclosing class
660      template is a member.  An explicit specialization of a member
661      function, member class or static data member of a class template
662      shall be declared in the namespace of which the class template
663      is a member.  */
664   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
665     {
666       error ("explicit specialization in non-namespace scope %qD", scope);
667       return false;
668     }
669
670   /* [temp.expl.spec]
671
672      In an explicit specialization declaration for a member of a class
673      template or a member template that appears in namespace scope,
674      the member template and some of its enclosing class templates may
675      remain unspecialized, except that the declaration shall not
676      explicitly specialize a class member template if its enclosing
677      class templates are not explicitly specialized as well.  */
678   if (current_template_parms)
679     {
680       error ("enclosing class templates are not explicitly specialized");
681       return false;
682     }
683
684   return true;
685 }
686
687 /* We've just seen template <>.  */
688
689 bool
690 begin_specialization (void)
691 {
692   begin_scope (sk_template_spec, NULL);
693   note_template_header (1);
694   return check_specialization_scope ();
695 }
696
697 /* Called at then end of processing a declaration preceded by
698    template<>.  */
699
700 void
701 end_specialization (void)
702 {
703   finish_scope ();
704   reset_specialization ();
705 }
706
707 /* Any template <>'s that we have seen thus far are not referring to a
708    function specialization.  */
709
710 void
711 reset_specialization (void)
712 {
713   processing_specialization = 0;
714   template_header_count = 0;
715 }
716
717 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
718    it was of the form template <>.  */
719
720 static void
721 note_template_header (int specialization)
722 {
723   processing_specialization = specialization;
724   template_header_count++;
725 }
726
727 /* We're beginning an explicit instantiation.  */
728
729 void
730 begin_explicit_instantiation (void)
731 {
732   gcc_assert (!processing_explicit_instantiation);
733   processing_explicit_instantiation = true;
734 }
735
736
737 void
738 end_explicit_instantiation (void)
739 {
740   gcc_assert (processing_explicit_instantiation);
741   processing_explicit_instantiation = false;
742 }
743
744 /* An explicit specialization or partial specialization TMPL is being
745    declared.  Check that the namespace in which the specialization is
746    occurring is permissible.  Returns false iff it is invalid to
747    specialize TMPL in the current namespace.  */
748
749 static bool
750 check_specialization_namespace (tree tmpl)
751 {
752   tree tpl_ns = decl_namespace_context (tmpl);
753
754   /* [tmpl.expl.spec]
755
756      An explicit specialization shall be declared in the namespace of
757      which the template is a member, or, for member templates, in the
758      namespace of which the enclosing class or enclosing class
759      template is a member.  An explicit specialization of a member
760      function, member class or static data member of a class template
761      shall be declared in the namespace of which the class template is
762      a member.  */
763   if (current_scope() != DECL_CONTEXT (tmpl)
764       && !at_namespace_scope_p ())
765     {
766       error ("specialization of %qD must appear at namespace scope", tmpl);
767       return false;
768     }
769   if (is_associated_namespace (current_namespace, tpl_ns))
770     /* Same or super-using namespace.  */
771     return true;
772   else
773     {
774       permerror (input_location, "specialization of %qD in different namespace", tmpl);
775       permerror (input_location, "  from definition of %q+#D", tmpl);
776       return false;
777     }
778 }
779
780 /* SPEC is an explicit instantiation.  Check that it is valid to
781    perform this explicit instantiation in the current namespace.  */
782
783 static void
784 check_explicit_instantiation_namespace (tree spec)
785 {
786   tree ns;
787
788   /* DR 275: An explicit instantiation shall appear in an enclosing
789      namespace of its template.  */
790   ns = decl_namespace_context (spec);
791   if (!is_ancestor (current_namespace, ns))
792     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
793                "(which does not enclose namespace %qD)",
794                spec, current_namespace, ns);
795 }
796
797 /* The TYPE is being declared.  If it is a template type, that means it
798    is a partial specialization.  Do appropriate error-checking.  */
799
800 tree
801 maybe_process_partial_specialization (tree type)
802 {
803   tree context;
804
805   if (type == error_mark_node)
806     return error_mark_node;
807
808   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
809     {
810       error ("name of class shadows template template parameter %qD",
811              TYPE_NAME (type));
812       return error_mark_node;
813     }
814
815   context = TYPE_CONTEXT (type);
816
817   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
818     {
819       /* This is for ordinary explicit specialization and partial
820          specialization of a template class such as:
821
822            template <> class C<int>;
823
824          or:
825
826            template <class T> class C<T*>;
827
828          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
829
830       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
831           && !COMPLETE_TYPE_P (type))
832         {
833           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
834           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
835           if (processing_template_decl)
836             {
837               if (push_template_decl (TYPE_MAIN_DECL (type))
838                   == error_mark_node)
839                 return error_mark_node;
840             }
841         }
842       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
843         error ("specialization of %qT after instantiation", type);
844     }
845   else if (CLASS_TYPE_P (type)
846            && !CLASSTYPE_USE_TEMPLATE (type)
847            && CLASSTYPE_TEMPLATE_INFO (type)
848            && context && CLASS_TYPE_P (context)
849            && CLASSTYPE_TEMPLATE_INFO (context))
850     {
851       /* This is for an explicit specialization of member class
852          template according to [temp.expl.spec/18]:
853
854            template <> template <class U> class C<int>::D;
855
856          The context `C<int>' must be an implicit instantiation.
857          Otherwise this is just a member class template declared
858          earlier like:
859
860            template <> class C<int> { template <class U> class D; };
861            template <> template <class U> class C<int>::D;
862
863          In the first case, `C<int>::D' is a specialization of `C<T>::D'
864          while in the second case, `C<int>::D' is a primary template
865          and `C<T>::D' may not exist.  */
866
867       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
868           && !COMPLETE_TYPE_P (type))
869         {
870           tree t;
871           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
872
873           if (current_namespace
874               != decl_namespace_context (tmpl))
875             {
876               permerror (input_location, "specializing %q#T in different namespace", type);
877               permerror (input_location, "  from definition of %q+#D", tmpl);
878             }
879
880           /* Check for invalid specialization after instantiation:
881
882                template <> template <> class C<int>::D<int>;
883                template <> template <class U> class C<int>::D;  */
884
885           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
886                t; t = TREE_CHAIN (t))
887             {
888               tree inst = TREE_VALUE (t);
889               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
890                 {
891                   /* We already have a full specialization of this partial
892                      instantiation.  Reassign it to the new member
893                      specialization template.  */
894                   spec_entry elt;
895                   spec_entry **slot;
896
897                   elt.tmpl = most_general_template (tmpl);
898                   elt.args = CLASSTYPE_TI_ARGS (inst);
899                   elt.spec = inst;
900
901                   htab_remove_elt (type_specializations, &elt);
902
903                   elt.tmpl = tmpl;
904                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
905
906                   slot = (spec_entry **)
907                     htab_find_slot (type_specializations, &elt, INSERT);
908                   *slot = ggc_alloc_spec_entry ();
909                   **slot = elt;
910                 }
911               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
912                 /* But if we've had an implicit instantiation, that's a
913                    problem ([temp.expl.spec]/6).  */
914                 error ("specialization %qT after instantiation %qT",
915                        type, inst);
916             }
917
918           /* Mark TYPE as a specialization.  And as a result, we only
919              have one level of template argument for the innermost
920              class template.  */
921           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
922           CLASSTYPE_TI_ARGS (type)
923             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
924         }
925     }
926   else if (processing_specialization)
927     {
928        /* Someday C++0x may allow for enum template specialization.  */
929       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
930           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
931         pedwarn (input_location, OPT_pedantic, "template specialization "
932                  "of %qD not allowed by ISO C++", type);
933       else
934         {
935           error ("explicit specialization of non-template %qT", type);
936           return error_mark_node;
937         }
938     }
939
940   return type;
941 }
942
943 /* Returns nonzero if we can optimize the retrieval of specializations
944    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
945    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
946
947 static inline bool
948 optimize_specialization_lookup_p (tree tmpl)
949 {
950   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
951           && DECL_CLASS_SCOPE_P (tmpl)
952           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
953              parameter.  */
954           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
955           /* The optimized lookup depends on the fact that the
956              template arguments for the member function template apply
957              purely to the containing class, which is not true if the
958              containing class is an explicit or partial
959              specialization.  */
960           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
961           && !DECL_MEMBER_TEMPLATE_P (tmpl)
962           && !DECL_CONV_FN_P (tmpl)
963           /* It is possible to have a template that is not a member
964              template and is not a member of a template class:
965
966              template <typename T>
967              struct S { friend A::f(); };
968
969              Here, the friend function is a template, but the context does
970              not have template information.  The optimized lookup relies
971              on having ARGS be the template arguments for both the class
972              and the function template.  */
973           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
974 }
975
976 /* Retrieve the specialization (in the sense of [temp.spec] - a
977    specialization is either an instantiation or an explicit
978    specialization) of TMPL for the given template ARGS.  If there is
979    no such specialization, return NULL_TREE.  The ARGS are a vector of
980    arguments, or a vector of vectors of arguments, in the case of
981    templates with more than one level of parameters.
982
983    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
984    then we search for a partial specialization matching ARGS.  This
985    parameter is ignored if TMPL is not a class template.  */
986
987 static tree
988 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
989 {
990   if (args == error_mark_node)
991     return NULL_TREE;
992
993   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
994
995   /* There should be as many levels of arguments as there are
996      levels of parameters.  */
997   gcc_assert (TMPL_ARGS_DEPTH (args)
998               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
999
1000   if (optimize_specialization_lookup_p (tmpl))
1001     {
1002       tree class_template;
1003       tree class_specialization;
1004       VEC(tree,gc) *methods;
1005       tree fns;
1006       int idx;
1007
1008       /* The template arguments actually apply to the containing
1009          class.  Find the class specialization with those
1010          arguments.  */
1011       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1012       class_specialization
1013         = retrieve_specialization (class_template, args, 0);
1014       if (!class_specialization)
1015         return NULL_TREE;
1016       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1017          for the specialization.  */
1018       idx = class_method_index_for_fn (class_specialization, tmpl);
1019       if (idx == -1)
1020         return NULL_TREE;
1021       /* Iterate through the methods with the indicated name, looking
1022          for the one that has an instance of TMPL.  */
1023       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1024       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1025         {
1026           tree fn = OVL_CURRENT (fns);
1027           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1028               /* using-declarations can add base methods to the method vec,
1029                  and we don't want those here.  */
1030               && DECL_CONTEXT (fn) == class_specialization)
1031             return fn;
1032         }
1033       return NULL_TREE;
1034     }
1035   else
1036     {
1037       spec_entry *found;
1038       spec_entry elt;
1039       htab_t specializations;
1040
1041       elt.tmpl = tmpl;
1042       elt.args = args;
1043       elt.spec = NULL_TREE;
1044
1045       if (DECL_CLASS_TEMPLATE_P (tmpl))
1046         specializations = type_specializations;
1047       else
1048         specializations = decl_specializations;
1049
1050       if (hash == 0)
1051         hash = hash_specialization (&elt);
1052       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1053       if (found)
1054         return found->spec;
1055     }
1056
1057   return NULL_TREE;
1058 }
1059
1060 /* Like retrieve_specialization, but for local declarations.  */
1061
1062 static tree
1063 retrieve_local_specialization (tree tmpl)
1064 {
1065   tree spec;
1066
1067   if (local_specializations == NULL)
1068     return NULL_TREE;
1069
1070   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1071                                      htab_hash_pointer (tmpl));
1072   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1073 }
1074
1075 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1076
1077 int
1078 is_specialization_of (tree decl, tree tmpl)
1079 {
1080   tree t;
1081
1082   if (TREE_CODE (decl) == FUNCTION_DECL)
1083     {
1084       for (t = decl;
1085            t != NULL_TREE;
1086            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1087         if (t == tmpl)
1088           return 1;
1089     }
1090   else
1091     {
1092       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1093
1094       for (t = TREE_TYPE (decl);
1095            t != NULL_TREE;
1096            t = CLASSTYPE_USE_TEMPLATE (t)
1097              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1098         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1099           return 1;
1100     }
1101
1102   return 0;
1103 }
1104
1105 /* Returns nonzero iff DECL is a specialization of friend declaration
1106    FRIEND_DECL according to [temp.friend].  */
1107
1108 bool
1109 is_specialization_of_friend (tree decl, tree friend_decl)
1110 {
1111   bool need_template = true;
1112   int template_depth;
1113
1114   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1115               || TREE_CODE (decl) == TYPE_DECL);
1116
1117   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1118      of a template class, we want to check if DECL is a specialization
1119      if this.  */
1120   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1121       && DECL_TEMPLATE_INFO (friend_decl)
1122       && !DECL_USE_TEMPLATE (friend_decl))
1123     {
1124       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1125       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1126       need_template = false;
1127     }
1128   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1129            && !PRIMARY_TEMPLATE_P (friend_decl))
1130     need_template = false;
1131
1132   /* There is nothing to do if this is not a template friend.  */
1133   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1134     return false;
1135
1136   if (is_specialization_of (decl, friend_decl))
1137     return true;
1138
1139   /* [temp.friend/6]
1140      A member of a class template may be declared to be a friend of a
1141      non-template class.  In this case, the corresponding member of
1142      every specialization of the class template is a friend of the
1143      class granting friendship.
1144
1145      For example, given a template friend declaration
1146
1147        template <class T> friend void A<T>::f();
1148
1149      the member function below is considered a friend
1150
1151        template <> struct A<int> {
1152          void f();
1153        };
1154
1155      For this type of template friend, TEMPLATE_DEPTH below will be
1156      nonzero.  To determine if DECL is a friend of FRIEND, we first
1157      check if the enclosing class is a specialization of another.  */
1158
1159   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1160   if (template_depth
1161       && DECL_CLASS_SCOPE_P (decl)
1162       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1163                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1164     {
1165       /* Next, we check the members themselves.  In order to handle
1166          a few tricky cases, such as when FRIEND_DECL's are
1167
1168            template <class T> friend void A<T>::g(T t);
1169            template <class T> template <T t> friend void A<T>::h();
1170
1171          and DECL's are
1172
1173            void A<int>::g(int);
1174            template <int> void A<int>::h();
1175
1176          we need to figure out ARGS, the template arguments from
1177          the context of DECL.  This is required for template substitution
1178          of `T' in the function parameter of `g' and template parameter
1179          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1180
1181       tree context = DECL_CONTEXT (decl);
1182       tree args = NULL_TREE;
1183       int current_depth = 0;
1184
1185       while (current_depth < template_depth)
1186         {
1187           if (CLASSTYPE_TEMPLATE_INFO (context))
1188             {
1189               if (current_depth == 0)
1190                 args = TYPE_TI_ARGS (context);
1191               else
1192                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1193               current_depth++;
1194             }
1195           context = TYPE_CONTEXT (context);
1196         }
1197
1198       if (TREE_CODE (decl) == FUNCTION_DECL)
1199         {
1200           bool is_template;
1201           tree friend_type;
1202           tree decl_type;
1203           tree friend_args_type;
1204           tree decl_args_type;
1205
1206           /* Make sure that both DECL and FRIEND_DECL are templates or
1207              non-templates.  */
1208           is_template = DECL_TEMPLATE_INFO (decl)
1209                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1210           if (need_template ^ is_template)
1211             return false;
1212           else if (is_template)
1213             {
1214               /* If both are templates, check template parameter list.  */
1215               tree friend_parms
1216                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1217                                          args, tf_none);
1218               if (!comp_template_parms
1219                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1220                       friend_parms))
1221                 return false;
1222
1223               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1224             }
1225           else
1226             decl_type = TREE_TYPE (decl);
1227
1228           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1229                                               tf_none, NULL_TREE);
1230           if (friend_type == error_mark_node)
1231             return false;
1232
1233           /* Check if return types match.  */
1234           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1235             return false;
1236
1237           /* Check if function parameter types match, ignoring the
1238              `this' parameter.  */
1239           friend_args_type = TYPE_ARG_TYPES (friend_type);
1240           decl_args_type = TYPE_ARG_TYPES (decl_type);
1241           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1242             friend_args_type = TREE_CHAIN (friend_args_type);
1243           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1244             decl_args_type = TREE_CHAIN (decl_args_type);
1245
1246           return compparms (decl_args_type, friend_args_type);
1247         }
1248       else
1249         {
1250           /* DECL is a TYPE_DECL */
1251           bool is_template;
1252           tree decl_type = TREE_TYPE (decl);
1253
1254           /* Make sure that both DECL and FRIEND_DECL are templates or
1255              non-templates.  */
1256           is_template
1257             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1258               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1259
1260           if (need_template ^ is_template)
1261             return false;
1262           else if (is_template)
1263             {
1264               tree friend_parms;
1265               /* If both are templates, check the name of the two
1266                  TEMPLATE_DECL's first because is_friend didn't.  */
1267               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1268                   != DECL_NAME (friend_decl))
1269                 return false;
1270
1271               /* Now check template parameter list.  */
1272               friend_parms
1273                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1274                                          args, tf_none);
1275               return comp_template_parms
1276                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1277                  friend_parms);
1278             }
1279           else
1280             return (DECL_NAME (decl)
1281                     == DECL_NAME (friend_decl));
1282         }
1283     }
1284   return false;
1285 }
1286
1287 /* Register the specialization SPEC as a specialization of TMPL with
1288    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1289    is actually just a friend declaration.  Returns SPEC, or an
1290    equivalent prior declaration, if available.  */
1291
1292 static tree
1293 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1294                          hashval_t hash)
1295 {
1296   tree fn;
1297   spec_entry **slot = NULL;
1298   spec_entry elt;
1299
1300   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1301
1302   if (TREE_CODE (spec) == FUNCTION_DECL
1303       && uses_template_parms (DECL_TI_ARGS (spec)))
1304     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1305        register it; we want the corresponding TEMPLATE_DECL instead.
1306        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1307        the more obvious `uses_template_parms (spec)' to avoid problems
1308        with default function arguments.  In particular, given
1309        something like this:
1310
1311           template <class T> void f(T t1, T t = T())
1312
1313        the default argument expression is not substituted for in an
1314        instantiation unless and until it is actually needed.  */
1315     return spec;
1316
1317   if (optimize_specialization_lookup_p (tmpl))
1318     /* We don't put these specializations in the hash table, but we might
1319        want to give an error about a mismatch.  */
1320     fn = retrieve_specialization (tmpl, args, 0);
1321   else
1322     {
1323       elt.tmpl = tmpl;
1324       elt.args = args;
1325       elt.spec = spec;
1326
1327       if (hash == 0)
1328         hash = hash_specialization (&elt);
1329
1330       slot = (spec_entry **)
1331         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1332       if (*slot)
1333         fn = (*slot)->spec;
1334       else
1335         fn = NULL_TREE;
1336     }
1337
1338   /* We can sometimes try to re-register a specialization that we've
1339      already got.  In particular, regenerate_decl_from_template calls
1340      duplicate_decls which will update the specialization list.  But,
1341      we'll still get called again here anyhow.  It's more convenient
1342      to simply allow this than to try to prevent it.  */
1343   if (fn == spec)
1344     return spec;
1345   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1346     {
1347       if (DECL_TEMPLATE_INSTANTIATION (fn))
1348         {
1349           if (DECL_ODR_USED (fn)
1350               || DECL_EXPLICIT_INSTANTIATION (fn))
1351             {
1352               error ("specialization of %qD after instantiation",
1353                      fn);
1354               return error_mark_node;
1355             }
1356           else
1357             {
1358               tree clone;
1359               /* This situation should occur only if the first
1360                  specialization is an implicit instantiation, the
1361                  second is an explicit specialization, and the
1362                  implicit instantiation has not yet been used.  That
1363                  situation can occur if we have implicitly
1364                  instantiated a member function and then specialized
1365                  it later.
1366
1367                  We can also wind up here if a friend declaration that
1368                  looked like an instantiation turns out to be a
1369                  specialization:
1370
1371                    template <class T> void foo(T);
1372                    class S { friend void foo<>(int) };
1373                    template <> void foo(int);
1374
1375                  We transform the existing DECL in place so that any
1376                  pointers to it become pointers to the updated
1377                  declaration.
1378
1379                  If there was a definition for the template, but not
1380                  for the specialization, we want this to look as if
1381                  there were no definition, and vice versa.  */
1382               DECL_INITIAL (fn) = NULL_TREE;
1383               duplicate_decls (spec, fn, is_friend);
1384               /* The call to duplicate_decls will have applied
1385                  [temp.expl.spec]:
1386
1387                    An explicit specialization of a function template
1388                    is inline only if it is explicitly declared to be,
1389                    and independently of whether its function template
1390                    is.
1391
1392                 to the primary function; now copy the inline bits to
1393                 the various clones.  */
1394               FOR_EACH_CLONE (clone, fn)
1395                 {
1396                   DECL_DECLARED_INLINE_P (clone)
1397                     = DECL_DECLARED_INLINE_P (fn);
1398                   DECL_SOURCE_LOCATION (clone)
1399                     = DECL_SOURCE_LOCATION (fn);
1400                 }
1401               check_specialization_namespace (fn);
1402
1403               return fn;
1404             }
1405         }
1406       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1407         {
1408           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1409             /* Dup decl failed, but this is a new definition. Set the
1410                line number so any errors match this new
1411                definition.  */
1412             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1413
1414           return fn;
1415         }
1416     }
1417   else if (fn)
1418     return duplicate_decls (spec, fn, is_friend);
1419
1420   /* A specialization must be declared in the same namespace as the
1421      template it is specializing.  */
1422   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1423       && !check_specialization_namespace (tmpl))
1424     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1425
1426   if (!optimize_specialization_lookup_p (tmpl))
1427     {
1428       gcc_assert (tmpl && args && spec);
1429       *slot = ggc_alloc_spec_entry ();
1430       **slot = elt;
1431       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1432           && PRIMARY_TEMPLATE_P (tmpl)
1433           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1434         /* TMPL is a forward declaration of a template function; keep a list
1435            of all specializations in case we need to reassign them to a friend
1436            template later in tsubst_friend_function.  */
1437         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1438           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1439     }
1440
1441   return spec;
1442 }
1443
1444 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1445    TMPL and ARGS members, ignores SPEC.  */
1446
1447 static int
1448 eq_specializations (const void *p1, const void *p2)
1449 {
1450   const spec_entry *e1 = (const spec_entry *)p1;
1451   const spec_entry *e2 = (const spec_entry *)p2;
1452
1453   return (e1->tmpl == e2->tmpl
1454           && comp_template_args (e1->args, e2->args));
1455 }
1456
1457 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1458
1459 static hashval_t
1460 hash_tmpl_and_args (tree tmpl, tree args)
1461 {
1462   hashval_t val = DECL_UID (tmpl);
1463   return iterative_hash_template_arg (args, val);
1464 }
1465
1466 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1467    ignoring SPEC.  */
1468
1469 static hashval_t
1470 hash_specialization (const void *p)
1471 {
1472   const spec_entry *e = (const spec_entry *)p;
1473   return hash_tmpl_and_args (e->tmpl, e->args);
1474 }
1475
1476 /* Recursively calculate a hash value for a template argument ARG, for use
1477    in the hash tables of template specializations.  */
1478
1479 hashval_t
1480 iterative_hash_template_arg (tree arg, hashval_t val)
1481 {
1482   unsigned HOST_WIDE_INT i;
1483   enum tree_code code;
1484   char tclass;
1485
1486   if (arg == NULL_TREE)
1487     return iterative_hash_object (arg, val);
1488
1489   if (!TYPE_P (arg))
1490     STRIP_NOPS (arg);
1491
1492   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1493     /* We can get one of these when re-hashing a previous entry in the middle
1494        of substituting into a pack expansion.  Just look through it.  */
1495     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1496
1497   code = TREE_CODE (arg);
1498   tclass = TREE_CODE_CLASS (code);
1499
1500   val = iterative_hash_object (code, val);
1501
1502   switch (code)
1503     {
1504     case ERROR_MARK:
1505       return val;
1506
1507     case IDENTIFIER_NODE:
1508       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1509
1510     case TREE_VEC:
1511       {
1512         int i, len = TREE_VEC_LENGTH (arg);
1513         for (i = 0; i < len; ++i)
1514           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1515         return val;
1516       }
1517
1518     case TYPE_PACK_EXPANSION:
1519     case EXPR_PACK_EXPANSION:
1520       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1521
1522     case TYPE_ARGUMENT_PACK:
1523     case NONTYPE_ARGUMENT_PACK:
1524       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1525
1526     case TREE_LIST:
1527       for (; arg; arg = TREE_CHAIN (arg))
1528         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1529       return val;
1530
1531     case OVERLOAD:
1532       for (; arg; arg = OVL_NEXT (arg))
1533         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1534       return val;
1535
1536     case CONSTRUCTOR:
1537       {
1538         tree field, value;
1539         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1540           {
1541             val = iterative_hash_template_arg (field, val);
1542             val = iterative_hash_template_arg (value, val);
1543           }
1544         return val;
1545       }
1546
1547     case PARM_DECL:
1548       if (!DECL_ARTIFICIAL (arg))
1549         {
1550           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1551           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1552         }
1553       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1554
1555     case TARGET_EXPR:
1556       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1557
1558     case PTRMEM_CST:
1559       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1560       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1561
1562     case TEMPLATE_PARM_INDEX:
1563       val = iterative_hash_template_arg
1564         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1565       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1566       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1567
1568     case TRAIT_EXPR:
1569       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1570       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1571       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1572
1573     case BASELINK:
1574       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1575                                          val);
1576       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1577                                           val);
1578
1579     case MODOP_EXPR:
1580       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1581       code = TREE_CODE (TREE_OPERAND (arg, 1));
1582       val = iterative_hash_object (code, val);
1583       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1584
1585     case LAMBDA_EXPR:
1586       /* A lambda can't appear in a template arg, but don't crash on
1587          erroneous input.  */
1588       gcc_assert (seen_error ());
1589       return val;
1590
1591     case CAST_EXPR:
1592     case STATIC_CAST_EXPR:
1593     case REINTERPRET_CAST_EXPR:
1594     case CONST_CAST_EXPR:
1595     case DYNAMIC_CAST_EXPR:
1596     case NEW_EXPR:
1597       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1598       /* Now hash operands as usual.  */
1599       break;
1600
1601     default:
1602       break;
1603     }
1604
1605   switch (tclass)
1606     {
1607     case tcc_type:
1608       if (TYPE_CANONICAL (arg))
1609         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1610                                       val);
1611       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1612         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1613       /* Otherwise just compare the types during lookup.  */
1614       return val;
1615
1616     case tcc_declaration:
1617     case tcc_constant:
1618       return iterative_hash_expr (arg, val);
1619
1620     default:
1621       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1622       {
1623         unsigned n = cp_tree_operand_length (arg);
1624         for (i = 0; i < n; ++i)
1625           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1626         return val;
1627       }
1628     }
1629   gcc_unreachable ();
1630   return 0;
1631 }
1632
1633 /* Unregister the specialization SPEC as a specialization of TMPL.
1634    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1635    if the SPEC was listed as a specialization of TMPL.
1636
1637    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1638
1639 bool
1640 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1641 {
1642   spec_entry **slot;
1643   spec_entry elt;
1644
1645   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1646   elt.args = TI_ARGS (tinfo);
1647   elt.spec = NULL_TREE;
1648
1649   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1650   if (*slot)
1651     {
1652       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1653       gcc_assert (new_spec != NULL_TREE);
1654       (*slot)->spec = new_spec;
1655       return 1;
1656     }
1657
1658   return 0;
1659 }
1660
1661 /* Compare an entry in the local specializations hash table P1 (which
1662    is really a pointer to a TREE_LIST) with P2 (which is really a
1663    DECL).  */
1664
1665 static int
1666 eq_local_specializations (const void *p1, const void *p2)
1667 {
1668   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1669 }
1670
1671 /* Hash P1, an entry in the local specializations table.  */
1672
1673 static hashval_t
1674 hash_local_specialization (const void* p1)
1675 {
1676   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1677 }
1678
1679 /* Like register_specialization, but for local declarations.  We are
1680    registering SPEC, an instantiation of TMPL.  */
1681
1682 static void
1683 register_local_specialization (tree spec, tree tmpl)
1684 {
1685   void **slot;
1686
1687   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1688                                    htab_hash_pointer (tmpl), INSERT);
1689   *slot = build_tree_list (spec, tmpl);
1690 }
1691
1692 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1693    specialized class.  */
1694
1695 bool
1696 explicit_class_specialization_p (tree type)
1697 {
1698   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1699     return false;
1700   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1701 }
1702
1703 /* Print the list of functions at FNS, going through all the overloads
1704    for each element of the list.  Alternatively, FNS can not be a
1705    TREE_LIST, in which case it will be printed together with all the
1706    overloads.
1707
1708    MORE and *STR should respectively be FALSE and NULL when the function
1709    is called from the outside.  They are used internally on recursive
1710    calls.  print_candidates manages the two parameters and leaves NULL
1711    in *STR when it ends.  */
1712
1713 static void
1714 print_candidates_1 (tree fns, bool more, const char **str)
1715 {
1716   tree fn, fn2;
1717   char *spaces = NULL;
1718
1719   for (fn = fns; fn; fn = OVL_NEXT (fn))
1720     if (TREE_CODE (fn) == TREE_LIST)
1721       {
1722         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1723           print_candidates_1 (TREE_VALUE (fn2),
1724                               TREE_CHAIN (fn2) || more, str);
1725       }
1726     else
1727       {
1728         if (!*str)
1729           {
1730             /* Pick the prefix string.  */
1731             if (!more && !OVL_NEXT (fns))
1732               {
1733                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1734                 continue;
1735               }
1736
1737             *str = _("candidates are:");
1738             spaces = get_spaces (*str);
1739           }
1740         error ("%s %+#D", *str, OVL_CURRENT (fn));
1741         *str = spaces ? spaces : *str;
1742       }
1743
1744   if (!more)
1745     {
1746       free (spaces);
1747       *str = NULL;
1748     }
1749 }
1750
1751 /* Print the list of candidate FNS in an error message.  FNS can also
1752    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1753
1754 void
1755 print_candidates (tree fns)
1756 {
1757   const char *str = NULL;
1758   print_candidates_1 (fns, false, &str);
1759   gcc_assert (str == NULL);
1760 }
1761
1762 /* Returns the template (one of the functions given by TEMPLATE_ID)
1763    which can be specialized to match the indicated DECL with the
1764    explicit template args given in TEMPLATE_ID.  The DECL may be
1765    NULL_TREE if none is available.  In that case, the functions in
1766    TEMPLATE_ID are non-members.
1767
1768    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1769    specialization of a member template.
1770
1771    The TEMPLATE_COUNT is the number of references to qualifying
1772    template classes that appeared in the name of the function. See
1773    check_explicit_specialization for a more accurate description.
1774
1775    TSK indicates what kind of template declaration (if any) is being
1776    declared.  TSK_TEMPLATE indicates that the declaration given by
1777    DECL, though a FUNCTION_DECL, has template parameters, and is
1778    therefore a template function.
1779
1780    The template args (those explicitly specified and those deduced)
1781    are output in a newly created vector *TARGS_OUT.
1782
1783    If it is impossible to determine the result, an error message is
1784    issued.  The error_mark_node is returned to indicate failure.  */
1785
1786 static tree
1787 determine_specialization (tree template_id,
1788                           tree decl,
1789                           tree* targs_out,
1790                           int need_member_template,
1791                           int template_count,
1792                           tmpl_spec_kind tsk)
1793 {
1794   tree fns;
1795   tree targs;
1796   tree explicit_targs;
1797   tree candidates = NULL_TREE;
1798   /* A TREE_LIST of templates of which DECL may be a specialization.
1799      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1800      corresponding TREE_PURPOSE is the set of template arguments that,
1801      when used to instantiate the template, would produce a function
1802      with the signature of DECL.  */
1803   tree templates = NULL_TREE;
1804   int header_count;
1805   cp_binding_level *b;
1806
1807   *targs_out = NULL_TREE;
1808
1809   if (template_id == error_mark_node || decl == error_mark_node)
1810     return error_mark_node;
1811
1812   fns = TREE_OPERAND (template_id, 0);
1813   explicit_targs = TREE_OPERAND (template_id, 1);
1814
1815   if (fns == error_mark_node)
1816     return error_mark_node;
1817
1818   /* Check for baselinks.  */
1819   if (BASELINK_P (fns))
1820     fns = BASELINK_FUNCTIONS (fns);
1821
1822   if (!is_overloaded_fn (fns))
1823     {
1824       error ("%qD is not a function template", fns);
1825       return error_mark_node;
1826     }
1827
1828   /* Count the number of template headers specified for this
1829      specialization.  */
1830   header_count = 0;
1831   for (b = current_binding_level;
1832        b->kind == sk_template_parms;
1833        b = b->level_chain)
1834     ++header_count;
1835
1836   for (; fns; fns = OVL_NEXT (fns))
1837     {
1838       tree fn = OVL_CURRENT (fns);
1839
1840       if (TREE_CODE (fn) == TEMPLATE_DECL)
1841         {
1842           tree decl_arg_types;
1843           tree fn_arg_types;
1844
1845           /* In case of explicit specialization, we need to check if
1846              the number of template headers appearing in the specialization
1847              is correct. This is usually done in check_explicit_specialization,
1848              but the check done there cannot be exhaustive when specializing
1849              member functions. Consider the following code:
1850
1851              template <> void A<int>::f(int);
1852              template <> template <> void A<int>::f(int);
1853
1854              Assuming that A<int> is not itself an explicit specialization
1855              already, the first line specializes "f" which is a non-template
1856              member function, whilst the second line specializes "f" which
1857              is a template member function. So both lines are syntactically
1858              correct, and check_explicit_specialization does not reject
1859              them.
1860
1861              Here, we can do better, as we are matching the specialization
1862              against the declarations. We count the number of template
1863              headers, and we check if they match TEMPLATE_COUNT + 1
1864              (TEMPLATE_COUNT is the number of qualifying template classes,
1865              plus there must be another header for the member template
1866              itself).
1867
1868              Notice that if header_count is zero, this is not a
1869              specialization but rather a template instantiation, so there
1870              is no check we can perform here.  */
1871           if (header_count && header_count != template_count + 1)
1872             continue;
1873
1874           /* Check that the number of template arguments at the
1875              innermost level for DECL is the same as for FN.  */
1876           if (current_binding_level->kind == sk_template_parms
1877               && !current_binding_level->explicit_spec_p
1878               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1879                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1880                                       (current_template_parms))))
1881             continue;
1882
1883           /* DECL might be a specialization of FN.  */
1884           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1885           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1886
1887           /* For a non-static member function, we need to make sure
1888              that the const qualification is the same.  Since
1889              get_bindings does not try to merge the "this" parameter,
1890              we must do the comparison explicitly.  */
1891           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1892               && !same_type_p (TREE_VALUE (fn_arg_types),
1893                                TREE_VALUE (decl_arg_types)))
1894             continue;
1895
1896           /* Skip the "this" parameter and, for constructors of
1897              classes with virtual bases, the VTT parameter.  A
1898              full specialization of a constructor will have a VTT
1899              parameter, but a template never will.  */ 
1900           decl_arg_types 
1901             = skip_artificial_parms_for (decl, decl_arg_types);
1902           fn_arg_types 
1903             = skip_artificial_parms_for (fn, fn_arg_types);
1904
1905           /* Check that the number of function parameters matches.
1906              For example,
1907                template <class T> void f(int i = 0);
1908                template <> void f<int>();
1909              The specialization f<int> is invalid but is not caught
1910              by get_bindings below.  */
1911           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1912             continue;
1913
1914           /* Function templates cannot be specializations; there are
1915              no partial specializations of functions.  Therefore, if
1916              the type of DECL does not match FN, there is no
1917              match.  */
1918           if (tsk == tsk_template)
1919             {
1920               if (compparms (fn_arg_types, decl_arg_types))
1921                 candidates = tree_cons (NULL_TREE, fn, candidates);
1922               continue;
1923             }
1924
1925           /* See whether this function might be a specialization of this
1926              template.  */
1927           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1928
1929           if (!targs)
1930             /* We cannot deduce template arguments that when used to
1931                specialize TMPL will produce DECL.  */
1932             continue;
1933
1934           /* Save this template, and the arguments deduced.  */
1935           templates = tree_cons (targs, fn, templates);
1936         }
1937       else if (need_member_template)
1938         /* FN is an ordinary member function, and we need a
1939            specialization of a member template.  */
1940         ;
1941       else if (TREE_CODE (fn) != FUNCTION_DECL)
1942         /* We can get IDENTIFIER_NODEs here in certain erroneous
1943            cases.  */
1944         ;
1945       else if (!DECL_FUNCTION_MEMBER_P (fn))
1946         /* This is just an ordinary non-member function.  Nothing can
1947            be a specialization of that.  */
1948         ;
1949       else if (DECL_ARTIFICIAL (fn))
1950         /* Cannot specialize functions that are created implicitly.  */
1951         ;
1952       else
1953         {
1954           tree decl_arg_types;
1955
1956           /* This is an ordinary member function.  However, since
1957              we're here, we can assume it's enclosing class is a
1958              template class.  For example,
1959
1960                template <typename T> struct S { void f(); };
1961                template <> void S<int>::f() {}
1962
1963              Here, S<int>::f is a non-template, but S<int> is a
1964              template class.  If FN has the same type as DECL, we
1965              might be in business.  */
1966
1967           if (!DECL_TEMPLATE_INFO (fn))
1968             /* Its enclosing class is an explicit specialization
1969                of a template class.  This is not a candidate.  */
1970             continue;
1971
1972           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1973                             TREE_TYPE (TREE_TYPE (fn))))
1974             /* The return types differ.  */
1975             continue;
1976
1977           /* Adjust the type of DECL in case FN is a static member.  */
1978           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1979           if (DECL_STATIC_FUNCTION_P (fn)
1980               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1981             decl_arg_types = TREE_CHAIN (decl_arg_types);
1982
1983           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1984                          decl_arg_types))
1985             /* They match!  */
1986             candidates = tree_cons (NULL_TREE, fn, candidates);
1987         }
1988     }
1989
1990   if (templates && TREE_CHAIN (templates))
1991     {
1992       /* We have:
1993
1994            [temp.expl.spec]
1995
1996            It is possible for a specialization with a given function
1997            signature to be instantiated from more than one function
1998            template.  In such cases, explicit specification of the
1999            template arguments must be used to uniquely identify the
2000            function template specialization being specialized.
2001
2002          Note that here, there's no suggestion that we're supposed to
2003          determine which of the candidate templates is most
2004          specialized.  However, we, also have:
2005
2006            [temp.func.order]
2007
2008            Partial ordering of overloaded function template
2009            declarations is used in the following contexts to select
2010            the function template to which a function template
2011            specialization refers:
2012
2013            -- when an explicit specialization refers to a function
2014               template.
2015
2016          So, we do use the partial ordering rules, at least for now.
2017          This extension can only serve to make invalid programs valid,
2018          so it's safe.  And, there is strong anecdotal evidence that
2019          the committee intended the partial ordering rules to apply;
2020          the EDG front end has that behavior, and John Spicer claims
2021          that the committee simply forgot to delete the wording in
2022          [temp.expl.spec].  */
2023       tree tmpl = most_specialized_instantiation (templates);
2024       if (tmpl != error_mark_node)
2025         {
2026           templates = tmpl;
2027           TREE_CHAIN (templates) = NULL_TREE;
2028         }
2029     }
2030
2031   if (templates == NULL_TREE && candidates == NULL_TREE)
2032     {
2033       error ("template-id %qD for %q+D does not match any template "
2034              "declaration", template_id, decl);
2035       if (header_count && header_count != template_count + 1)
2036         inform (input_location, "saw %d %<template<>%>, need %d for "
2037                 "specializing a member function template",
2038                 header_count, template_count + 1);
2039       return error_mark_node;
2040     }
2041   else if ((templates && TREE_CHAIN (templates))
2042            || (candidates && TREE_CHAIN (candidates))
2043            || (templates && candidates))
2044     {
2045       error ("ambiguous template specialization %qD for %q+D",
2046              template_id, decl);
2047       candidates = chainon (candidates, templates);
2048       print_candidates (candidates);
2049       return error_mark_node;
2050     }
2051
2052   /* We have one, and exactly one, match.  */
2053   if (candidates)
2054     {
2055       tree fn = TREE_VALUE (candidates);
2056       *targs_out = copy_node (DECL_TI_ARGS (fn));
2057       /* DECL is a re-declaration or partial instantiation of a template
2058          function.  */
2059       if (TREE_CODE (fn) == TEMPLATE_DECL)
2060         return fn;
2061       /* It was a specialization of an ordinary member function in a
2062          template class.  */
2063       return DECL_TI_TEMPLATE (fn);
2064     }
2065
2066   /* It was a specialization of a template.  */
2067   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2068   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2069     {
2070       *targs_out = copy_node (targs);
2071       SET_TMPL_ARGS_LEVEL (*targs_out,
2072                            TMPL_ARGS_DEPTH (*targs_out),
2073                            TREE_PURPOSE (templates));
2074     }
2075   else
2076     *targs_out = TREE_PURPOSE (templates);
2077   return TREE_VALUE (templates);
2078 }
2079
2080 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2081    but with the default argument values filled in from those in the
2082    TMPL_TYPES.  */
2083
2084 static tree
2085 copy_default_args_to_explicit_spec_1 (tree spec_types,
2086                                       tree tmpl_types)
2087 {
2088   tree new_spec_types;
2089
2090   if (!spec_types)
2091     return NULL_TREE;
2092
2093   if (spec_types == void_list_node)
2094     return void_list_node;
2095
2096   /* Substitute into the rest of the list.  */
2097   new_spec_types =
2098     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2099                                           TREE_CHAIN (tmpl_types));
2100
2101   /* Add the default argument for this parameter.  */
2102   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2103                          TREE_VALUE (spec_types),
2104                          new_spec_types);
2105 }
2106
2107 /* DECL is an explicit specialization.  Replicate default arguments
2108    from the template it specializes.  (That way, code like:
2109
2110      template <class T> void f(T = 3);
2111      template <> void f(double);
2112      void g () { f (); }
2113
2114    works, as required.)  An alternative approach would be to look up
2115    the correct default arguments at the call-site, but this approach
2116    is consistent with how implicit instantiations are handled.  */
2117
2118 static void
2119 copy_default_args_to_explicit_spec (tree decl)
2120 {
2121   tree tmpl;
2122   tree spec_types;
2123   tree tmpl_types;
2124   tree new_spec_types;
2125   tree old_type;
2126   tree new_type;
2127   tree t;
2128   tree object_type = NULL_TREE;
2129   tree in_charge = NULL_TREE;
2130   tree vtt = NULL_TREE;
2131
2132   /* See if there's anything we need to do.  */
2133   tmpl = DECL_TI_TEMPLATE (decl);
2134   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2135   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2136     if (TREE_PURPOSE (t))
2137       break;
2138   if (!t)
2139     return;
2140
2141   old_type = TREE_TYPE (decl);
2142   spec_types = TYPE_ARG_TYPES (old_type);
2143
2144   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2145     {
2146       /* Remove the this pointer, but remember the object's type for
2147          CV quals.  */
2148       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2149       spec_types = TREE_CHAIN (spec_types);
2150       tmpl_types = TREE_CHAIN (tmpl_types);
2151
2152       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2153         {
2154           /* DECL may contain more parameters than TMPL due to the extra
2155              in-charge parameter in constructors and destructors.  */
2156           in_charge = spec_types;
2157           spec_types = TREE_CHAIN (spec_types);
2158         }
2159       if (DECL_HAS_VTT_PARM_P (decl))
2160         {
2161           vtt = spec_types;
2162           spec_types = TREE_CHAIN (spec_types);
2163         }
2164     }
2165
2166   /* Compute the merged default arguments.  */
2167   new_spec_types =
2168     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2169
2170   /* Compute the new FUNCTION_TYPE.  */
2171   if (object_type)
2172     {
2173       if (vtt)
2174         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2175                                          TREE_VALUE (vtt),
2176                                          new_spec_types);
2177
2178       if (in_charge)
2179         /* Put the in-charge parameter back.  */
2180         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2181                                          TREE_VALUE (in_charge),
2182                                          new_spec_types);
2183
2184       new_type = build_method_type_directly (object_type,
2185                                              TREE_TYPE (old_type),
2186                                              new_spec_types);
2187     }
2188   else
2189     new_type = build_function_type (TREE_TYPE (old_type),
2190                                     new_spec_types);
2191   new_type = cp_build_type_attribute_variant (new_type,
2192                                               TYPE_ATTRIBUTES (old_type));
2193   new_type = build_exception_variant (new_type,
2194                                       TYPE_RAISES_EXCEPTIONS (old_type));
2195   TREE_TYPE (decl) = new_type;
2196 }
2197
2198 /* Check to see if the function just declared, as indicated in
2199    DECLARATOR, and in DECL, is a specialization of a function
2200    template.  We may also discover that the declaration is an explicit
2201    instantiation at this point.
2202
2203    Returns DECL, or an equivalent declaration that should be used
2204    instead if all goes well.  Issues an error message if something is
2205    amiss.  Returns error_mark_node if the error is not easily
2206    recoverable.
2207
2208    FLAGS is a bitmask consisting of the following flags:
2209
2210    2: The function has a definition.
2211    4: The function is a friend.
2212
2213    The TEMPLATE_COUNT is the number of references to qualifying
2214    template classes that appeared in the name of the function.  For
2215    example, in
2216
2217      template <class T> struct S { void f(); };
2218      void S<int>::f();
2219
2220    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2221    classes are not counted in the TEMPLATE_COUNT, so that in
2222
2223      template <class T> struct S {};
2224      template <> struct S<int> { void f(); }
2225      template <> void S<int>::f();
2226
2227    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2228    invalid; there should be no template <>.)
2229
2230    If the function is a specialization, it is marked as such via
2231    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2232    is set up correctly, and it is added to the list of specializations
2233    for that template.  */
2234
2235 tree
2236 check_explicit_specialization (tree declarator,
2237                                tree decl,
2238                                int template_count,
2239                                int flags)
2240 {
2241   int have_def = flags & 2;
2242   int is_friend = flags & 4;
2243   int specialization = 0;
2244   int explicit_instantiation = 0;
2245   int member_specialization = 0;
2246   tree ctype = DECL_CLASS_CONTEXT (decl);
2247   tree dname = DECL_NAME (decl);
2248   tmpl_spec_kind tsk;
2249
2250   if (is_friend)
2251     {
2252       if (!processing_specialization)
2253         tsk = tsk_none;
2254       else
2255         tsk = tsk_excessive_parms;
2256     }
2257   else
2258     tsk = current_tmpl_spec_kind (template_count);
2259
2260   switch (tsk)
2261     {
2262     case tsk_none:
2263       if (processing_specialization)
2264         {
2265           specialization = 1;
2266           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2267         }
2268       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2269         {
2270           if (is_friend)
2271             /* This could be something like:
2272
2273                template <class T> void f(T);
2274                class S { friend void f<>(int); }  */
2275             specialization = 1;
2276           else
2277             {
2278               /* This case handles bogus declarations like template <>
2279                  template <class T> void f<int>(); */
2280
2281               error ("template-id %qD in declaration of primary template",
2282                      declarator);
2283               return decl;
2284             }
2285         }
2286       break;
2287
2288     case tsk_invalid_member_spec:
2289       /* The error has already been reported in
2290          check_specialization_scope.  */
2291       return error_mark_node;
2292
2293     case tsk_invalid_expl_inst:
2294       error ("template parameter list used in explicit instantiation");
2295
2296       /* Fall through.  */
2297
2298     case tsk_expl_inst:
2299       if (have_def)
2300         error ("definition provided for explicit instantiation");
2301
2302       explicit_instantiation = 1;
2303       break;
2304
2305     case tsk_excessive_parms:
2306     case tsk_insufficient_parms:
2307       if (tsk == tsk_excessive_parms)
2308         error ("too many template parameter lists in declaration of %qD",
2309                decl);
2310       else if (template_header_count)
2311         error("too few template parameter lists in declaration of %qD", decl);
2312       else
2313         error("explicit specialization of %qD must be introduced by "
2314               "%<template <>%>", decl);
2315
2316       /* Fall through.  */
2317     case tsk_expl_spec:
2318       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2319       if (ctype)
2320         member_specialization = 1;
2321       else
2322         specialization = 1;
2323       break;
2324
2325     case tsk_template:
2326       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2327         {
2328           /* This case handles bogus declarations like template <>
2329              template <class T> void f<int>(); */
2330
2331           if (uses_template_parms (declarator))
2332             error ("function template partial specialization %qD "
2333                    "is not allowed", declarator);
2334           else
2335             error ("template-id %qD in declaration of primary template",
2336                    declarator);
2337           return decl;
2338         }
2339
2340       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2341         /* This is a specialization of a member template, without
2342            specialization the containing class.  Something like:
2343
2344              template <class T> struct S {
2345                template <class U> void f (U);
2346              };
2347              template <> template <class U> void S<int>::f(U) {}
2348
2349            That's a specialization -- but of the entire template.  */
2350         specialization = 1;
2351       break;
2352
2353     default:
2354       gcc_unreachable ();
2355     }
2356
2357   if (specialization || member_specialization)
2358     {
2359       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2360       for (; t; t = TREE_CHAIN (t))
2361         if (TREE_PURPOSE (t))
2362           {
2363             permerror (input_location, 
2364                        "default argument specified in explicit specialization");
2365             break;
2366           }
2367     }
2368
2369   if (specialization || member_specialization || explicit_instantiation)
2370     {
2371       tree tmpl = NULL_TREE;
2372       tree targs = NULL_TREE;
2373
2374       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2375       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2376         {
2377           tree fns;
2378
2379           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2380           if (ctype)
2381             fns = dname;
2382           else
2383             {
2384               /* If there is no class context, the explicit instantiation
2385                  must be at namespace scope.  */
2386               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2387
2388               /* Find the namespace binding, using the declaration
2389                  context.  */
2390               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2391                                            false, true);
2392               if (fns == error_mark_node || !is_overloaded_fn (fns))
2393                 {
2394                   error ("%qD is not a template function", dname);
2395                   fns = error_mark_node;
2396                 }
2397               else
2398                 {
2399                   tree fn = OVL_CURRENT (fns);
2400                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2401                                                 CP_DECL_CONTEXT (fn)))
2402                     error ("%qD is not declared in %qD",
2403                            decl, current_namespace);
2404                 }
2405             }
2406
2407           declarator = lookup_template_function (fns, NULL_TREE);
2408         }
2409
2410       if (declarator == error_mark_node)
2411         return error_mark_node;
2412
2413       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2414         {
2415           if (!explicit_instantiation)
2416             /* A specialization in class scope.  This is invalid,
2417                but the error will already have been flagged by
2418                check_specialization_scope.  */
2419             return error_mark_node;
2420           else
2421             {
2422               /* It's not valid to write an explicit instantiation in
2423                  class scope, e.g.:
2424
2425                    class C { template void f(); }
2426
2427                    This case is caught by the parser.  However, on
2428                    something like:
2429
2430                    template class C { void f(); };
2431
2432                    (which is invalid) we can get here.  The error will be
2433                    issued later.  */
2434               ;
2435             }
2436
2437           return decl;
2438         }
2439       else if (ctype != NULL_TREE
2440                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2441                    IDENTIFIER_NODE))
2442         {
2443           /* Find the list of functions in ctype that have the same
2444              name as the declared function.  */
2445           tree name = TREE_OPERAND (declarator, 0);
2446           tree fns = NULL_TREE;
2447           int idx;
2448
2449           if (constructor_name_p (name, ctype))
2450             {
2451               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2452
2453               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2454                   : !CLASSTYPE_DESTRUCTORS (ctype))
2455                 {
2456                   /* From [temp.expl.spec]:
2457
2458                      If such an explicit specialization for the member
2459                      of a class template names an implicitly-declared
2460                      special member function (clause _special_), the
2461                      program is ill-formed.
2462
2463                      Similar language is found in [temp.explicit].  */
2464                   error ("specialization of implicitly-declared special member function");
2465                   return error_mark_node;
2466                 }
2467
2468               name = is_constructor ? ctor_identifier : dtor_identifier;
2469             }
2470
2471           if (!DECL_CONV_FN_P (decl))
2472             {
2473               idx = lookup_fnfields_1 (ctype, name);
2474               if (idx >= 0)
2475                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2476             }
2477           else
2478             {
2479               VEC(tree,gc) *methods;
2480               tree ovl;
2481
2482               /* For a type-conversion operator, we cannot do a
2483                  name-based lookup.  We might be looking for `operator
2484                  int' which will be a specialization of `operator T'.
2485                  So, we find *all* the conversion operators, and then
2486                  select from them.  */
2487               fns = NULL_TREE;
2488
2489               methods = CLASSTYPE_METHOD_VEC (ctype);
2490               if (methods)
2491                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2492                      VEC_iterate (tree, methods, idx, ovl);
2493                      ++idx)
2494                   {
2495                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2496                       /* There are no more conversion functions.  */
2497                       break;
2498
2499                     /* Glue all these conversion functions together
2500                        with those we already have.  */
2501                     for (; ovl; ovl = OVL_NEXT (ovl))
2502                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2503                   }
2504             }
2505
2506           if (fns == NULL_TREE)
2507             {
2508               error ("no member function %qD declared in %qT", name, ctype);
2509               return error_mark_node;
2510             }
2511           else
2512             TREE_OPERAND (declarator, 0) = fns;
2513         }
2514
2515       /* Figure out what exactly is being specialized at this point.
2516          Note that for an explicit instantiation, even one for a
2517          member function, we cannot tell apriori whether the
2518          instantiation is for a member template, or just a member
2519          function of a template class.  Even if a member template is
2520          being instantiated, the member template arguments may be
2521          elided if they can be deduced from the rest of the
2522          declaration.  */
2523       tmpl = determine_specialization (declarator, decl,
2524                                        &targs,
2525                                        member_specialization,
2526                                        template_count,
2527                                        tsk);
2528
2529       if (!tmpl || tmpl == error_mark_node)
2530         /* We couldn't figure out what this declaration was
2531            specializing.  */
2532         return error_mark_node;
2533       else
2534         {
2535           tree gen_tmpl = most_general_template (tmpl);
2536
2537           if (explicit_instantiation)
2538             {
2539               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2540                  is done by do_decl_instantiation later.  */
2541
2542               int arg_depth = TMPL_ARGS_DEPTH (targs);
2543               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2544
2545               if (arg_depth > parm_depth)
2546                 {
2547                   /* If TMPL is not the most general template (for
2548                      example, if TMPL is a friend template that is
2549                      injected into namespace scope), then there will
2550                      be too many levels of TARGS.  Remove some of them
2551                      here.  */
2552                   int i;
2553                   tree new_targs;
2554
2555                   new_targs = make_tree_vec (parm_depth);
2556                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2557                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2558                       = TREE_VEC_ELT (targs, i);
2559                   targs = new_targs;
2560                 }
2561
2562               return instantiate_template (tmpl, targs, tf_error);
2563             }
2564
2565           /* If we thought that the DECL was a member function, but it
2566              turns out to be specializing a static member function,
2567              make DECL a static member function as well.  */
2568           if (DECL_STATIC_FUNCTION_P (tmpl)
2569               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2570             revert_static_member_fn (decl);
2571
2572           /* If this is a specialization of a member template of a
2573              template class, we want to return the TEMPLATE_DECL, not
2574              the specialization of it.  */
2575           if (tsk == tsk_template)
2576             {
2577               tree result = DECL_TEMPLATE_RESULT (tmpl);
2578               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2579               DECL_INITIAL (result) = NULL_TREE;
2580               if (have_def)
2581                 {
2582                   tree parm;
2583                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2584                   DECL_SOURCE_LOCATION (result)
2585                     = DECL_SOURCE_LOCATION (decl);
2586                   /* We want to use the argument list specified in the
2587                      definition, not in the original declaration.  */
2588                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2589                   for (parm = DECL_ARGUMENTS (result); parm;
2590                        parm = DECL_CHAIN (parm))
2591                     DECL_CONTEXT (parm) = result;
2592                 }
2593               return register_specialization (tmpl, gen_tmpl, targs,
2594                                               is_friend, 0);
2595             }
2596
2597           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2598           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2599
2600           /* Inherit default function arguments from the template
2601              DECL is specializing.  */
2602           copy_default_args_to_explicit_spec (decl);
2603
2604           /* This specialization has the same protection as the
2605              template it specializes.  */
2606           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2607           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2608
2609           /* 7.1.1-1 [dcl.stc]
2610
2611              A storage-class-specifier shall not be specified in an
2612              explicit specialization...
2613
2614              The parser rejects these, so unless action is taken here,
2615              explicit function specializations will always appear with
2616              global linkage.
2617
2618              The action recommended by the C++ CWG in response to C++
2619              defect report 605 is to make the storage class and linkage
2620              of the explicit specialization match the templated function:
2621
2622              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2623            */
2624           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2625             {
2626               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2627               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2628
2629               /* This specialization has the same linkage and visibility as
2630                  the function template it specializes.  */
2631               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2632               if (! TREE_PUBLIC (decl))
2633                 {
2634                   DECL_INTERFACE_KNOWN (decl) = 1;
2635                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2636                 }
2637               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2638               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2639                 {
2640                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2641                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2642                 }
2643             }
2644
2645           /* If DECL is a friend declaration, declared using an
2646              unqualified name, the namespace associated with DECL may
2647              have been set incorrectly.  For example, in:
2648
2649                template <typename T> void f(T);
2650                namespace N {
2651                  struct S { friend void f<int>(int); }
2652                }
2653
2654              we will have set the DECL_CONTEXT for the friend
2655              declaration to N, rather than to the global namespace.  */
2656           if (DECL_NAMESPACE_SCOPE_P (decl))
2657             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2658
2659           if (is_friend && !have_def)
2660             /* This is not really a declaration of a specialization.
2661                It's just the name of an instantiation.  But, it's not
2662                a request for an instantiation, either.  */
2663             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2664           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2665             /* This is indeed a specialization.  In case of constructors
2666                and destructors, we need in-charge and not-in-charge
2667                versions in V3 ABI.  */
2668             clone_function_decl (decl, /*update_method_vec_p=*/0);
2669
2670           /* Register this specialization so that we can find it
2671              again.  */
2672           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2673         }
2674     }
2675
2676   return decl;
2677 }
2678
2679 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2680    parameters.  These are represented in the same format used for
2681    DECL_TEMPLATE_PARMS.  */
2682
2683 int
2684 comp_template_parms (const_tree parms1, const_tree parms2)
2685 {
2686   const_tree p1;
2687   const_tree p2;
2688
2689   if (parms1 == parms2)
2690     return 1;
2691
2692   for (p1 = parms1, p2 = parms2;
2693        p1 != NULL_TREE && p2 != NULL_TREE;
2694        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2695     {
2696       tree t1 = TREE_VALUE (p1);
2697       tree t2 = TREE_VALUE (p2);
2698       int i;
2699
2700       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2701       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2702
2703       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2704         return 0;
2705
2706       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2707         {
2708           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2709           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2710
2711           /* If either of the template parameters are invalid, assume
2712              they match for the sake of error recovery. */
2713           if (parm1 == error_mark_node || parm2 == error_mark_node)
2714             return 1;
2715
2716           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2717             return 0;
2718
2719           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2720               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2721                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2722             continue;
2723           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2724             return 0;
2725         }
2726     }
2727
2728   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2729     /* One set of parameters has more parameters lists than the
2730        other.  */
2731     return 0;
2732
2733   return 1;
2734 }
2735
2736 /* Determine whether PARM is a parameter pack.  */
2737
2738 bool 
2739 template_parameter_pack_p (const_tree parm)
2740 {
2741   /* Determine if we have a non-type template parameter pack.  */
2742   if (TREE_CODE (parm) == PARM_DECL)
2743     return (DECL_TEMPLATE_PARM_P (parm) 
2744             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2745   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2746     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2747
2748   /* If this is a list of template parameters, we could get a
2749      TYPE_DECL or a TEMPLATE_DECL.  */ 
2750   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2751     parm = TREE_TYPE (parm);
2752
2753   /* Otherwise it must be a type template parameter.  */
2754   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2755            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2756           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2757 }
2758
2759 /* Determine if T is a function parameter pack.  */
2760
2761 bool
2762 function_parameter_pack_p (const_tree t)
2763 {
2764   if (t && TREE_CODE (t) == PARM_DECL)
2765     return FUNCTION_PARAMETER_PACK_P (t);
2766   return false;
2767 }
2768
2769 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2770    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2771
2772 tree
2773 get_function_template_decl (const_tree primary_func_tmpl_inst)
2774 {
2775   if (! primary_func_tmpl_inst
2776       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2777       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2778     return NULL;
2779
2780   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2781 }
2782
2783 /* Return true iff the function parameter PARAM_DECL was expanded
2784    from the function parameter pack PACK.  */
2785
2786 bool
2787 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2788 {
2789   if (DECL_ARTIFICIAL (param_decl)
2790       || !function_parameter_pack_p (pack))
2791     return false;
2792
2793   /* The parameter pack and its pack arguments have the same
2794      DECL_PARM_INDEX.  */
2795   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2796 }
2797
2798 /* Determine whether ARGS describes a variadic template args list,
2799    i.e., one that is terminated by a template argument pack.  */
2800
2801 static bool 
2802 template_args_variadic_p (tree args)
2803 {
2804   int nargs;
2805   tree last_parm;
2806
2807   if (args == NULL_TREE)
2808     return false;
2809
2810   args = INNERMOST_TEMPLATE_ARGS (args);
2811   nargs = TREE_VEC_LENGTH (args);
2812
2813   if (nargs == 0)
2814     return false;
2815
2816   last_parm = TREE_VEC_ELT (args, nargs - 1);
2817
2818   return ARGUMENT_PACK_P (last_parm);
2819 }
2820
2821 /* Generate a new name for the parameter pack name NAME (an
2822    IDENTIFIER_NODE) that incorporates its */
2823
2824 static tree
2825 make_ith_pack_parameter_name (tree name, int i)
2826 {
2827   /* Munge the name to include the parameter index.  */
2828 #define NUMBUF_LEN 128
2829   char numbuf[NUMBUF_LEN];
2830   char* newname;
2831   int newname_len;
2832
2833   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2834   newname_len = IDENTIFIER_LENGTH (name)
2835                 + strlen (numbuf) + 2;
2836   newname = (char*)alloca (newname_len);
2837   snprintf (newname, newname_len,
2838             "%s#%i", IDENTIFIER_POINTER (name), i);
2839   return get_identifier (newname);
2840 }
2841
2842 /* Return true if T is a primary function
2843    or class template instantiation.  */
2844
2845 bool
2846 primary_template_instantiation_p (const_tree t)
2847 {
2848   if (!t)
2849     return false;
2850
2851   if (TREE_CODE (t) == FUNCTION_DECL)
2852     return DECL_LANG_SPECIFIC (t)
2853            && DECL_TEMPLATE_INSTANTIATION (t)
2854            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2855   else if (CLASS_TYPE_P (t))
2856     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2857            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2858   return false;
2859 }
2860
2861 /* Return true if PARM is a template template parameter.  */
2862
2863 bool
2864 template_template_parameter_p (const_tree parm)
2865 {
2866   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2867 }
2868
2869 /* Return the template parameters of T if T is a
2870    primary template instantiation, NULL otherwise.  */
2871
2872 tree
2873 get_primary_template_innermost_parameters (const_tree t)
2874 {
2875   tree parms = NULL, template_info = NULL;
2876
2877   if ((template_info = get_template_info (t))
2878       && primary_template_instantiation_p (t))
2879     parms = INNERMOST_TEMPLATE_PARMS
2880         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2881
2882   return parms;
2883 }
2884
2885 /* Return the template parameters of the LEVELth level from the full list
2886    of template parameters PARMS.  */
2887
2888 tree
2889 get_template_parms_at_level (tree parms, int level)
2890 {
2891   tree p;
2892   if (!parms
2893       || TREE_CODE (parms) != TREE_LIST
2894       || level > TMPL_PARMS_DEPTH (parms))
2895     return NULL_TREE;
2896
2897   for (p = parms; p; p = TREE_CHAIN (p))
2898     if (TMPL_PARMS_DEPTH (p) == level)
2899       return p;
2900
2901   return NULL_TREE;
2902 }
2903
2904 /* Returns the template arguments of T if T is a template instantiation,
2905    NULL otherwise.  */
2906
2907 tree
2908 get_template_innermost_arguments (const_tree t)
2909 {
2910   tree args = NULL, template_info = NULL;
2911
2912   if ((template_info = get_template_info (t))
2913       && TI_ARGS (template_info))
2914     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2915
2916   return args;
2917 }
2918
2919 /* Return the argument pack elements of T if T is a template argument pack,
2920    NULL otherwise.  */
2921
2922 tree
2923 get_template_argument_pack_elems (const_tree t)
2924 {
2925   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2926       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2927     return NULL;
2928
2929   return ARGUMENT_PACK_ARGS (t);
2930 }
2931
2932 /* Structure used to track the progress of find_parameter_packs_r.  */
2933 struct find_parameter_pack_data 
2934 {
2935   /* TREE_LIST that will contain all of the parameter packs found by
2936      the traversal.  */
2937   tree* parameter_packs;
2938
2939   /* Set of AST nodes that have been visited by the traversal.  */
2940   struct pointer_set_t *visited;
2941 };
2942
2943 /* Identifies all of the argument packs that occur in a template
2944    argument and appends them to the TREE_LIST inside DATA, which is a
2945    find_parameter_pack_data structure. This is a subroutine of
2946    make_pack_expansion and uses_parameter_packs.  */
2947 static tree
2948 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2949 {
2950   tree t = *tp;
2951   struct find_parameter_pack_data* ppd = 
2952     (struct find_parameter_pack_data*)data;
2953   bool parameter_pack_p = false;
2954
2955   /* Identify whether this is a parameter pack or not.  */
2956   switch (TREE_CODE (t))
2957     {
2958     case TEMPLATE_PARM_INDEX:
2959       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2960         parameter_pack_p = true;
2961       break;
2962
2963     case TEMPLATE_TYPE_PARM:
2964     case TEMPLATE_TEMPLATE_PARM:
2965       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2966         parameter_pack_p = true;
2967       break;
2968
2969     case PARM_DECL:
2970       if (FUNCTION_PARAMETER_PACK_P (t))
2971         {
2972           /* We don't want to walk into the type of a PARM_DECL,
2973              because we don't want to see the type parameter pack.  */
2974           *walk_subtrees = 0;
2975           parameter_pack_p = true;
2976         }
2977       break;
2978
2979     default:
2980       /* Not a parameter pack.  */
2981       break;
2982     }
2983
2984   if (parameter_pack_p)
2985     {
2986       /* Add this parameter pack to the list.  */
2987       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2988     }
2989
2990   if (TYPE_P (t))
2991     cp_walk_tree (&TYPE_CONTEXT (t), 
2992                   &find_parameter_packs_r, ppd, ppd->visited);
2993
2994   /* This switch statement will return immediately if we don't find a
2995      parameter pack.  */
2996   switch (TREE_CODE (t)) 
2997     {
2998     case TEMPLATE_PARM_INDEX:
2999       return NULL_TREE;
3000
3001     case BOUND_TEMPLATE_TEMPLATE_PARM:
3002       /* Check the template itself.  */
3003       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3004                     &find_parameter_packs_r, ppd, ppd->visited);
3005       /* Check the template arguments.  */
3006       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3007                     ppd->visited);
3008       *walk_subtrees = 0;
3009       return NULL_TREE;
3010
3011     case TEMPLATE_TYPE_PARM:
3012     case TEMPLATE_TEMPLATE_PARM:
3013       return NULL_TREE;
3014
3015     case PARM_DECL:
3016       return NULL_TREE;
3017
3018     case RECORD_TYPE:
3019       if (TYPE_PTRMEMFUNC_P (t))
3020         return NULL_TREE;
3021       /* Fall through.  */
3022
3023     case UNION_TYPE:
3024     case ENUMERAL_TYPE:
3025       if (TYPE_TEMPLATE_INFO (t))
3026         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3027                       &find_parameter_packs_r, ppd, ppd->visited);
3028
3029       *walk_subtrees = 0;
3030       return NULL_TREE;
3031
3032     case CONSTRUCTOR:
3033     case TEMPLATE_DECL:
3034       cp_walk_tree (&TREE_TYPE (t),
3035                     &find_parameter_packs_r, ppd, ppd->visited);
3036       return NULL_TREE;
3037  
3038     case TYPENAME_TYPE:
3039       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3040                    ppd, ppd->visited);
3041       *walk_subtrees = 0;
3042       return NULL_TREE;
3043       
3044     case TYPE_PACK_EXPANSION:
3045     case EXPR_PACK_EXPANSION:
3046       *walk_subtrees = 0;
3047       return NULL_TREE;
3048
3049     case INTEGER_TYPE:
3050       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3051                     ppd, ppd->visited);
3052       *walk_subtrees = 0;
3053       return NULL_TREE;
3054
3055     case IDENTIFIER_NODE:
3056       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3057                     ppd->visited);
3058       *walk_subtrees = 0;
3059       return NULL_TREE;
3060
3061     default:
3062       return NULL_TREE;
3063     }
3064
3065   return NULL_TREE;
3066 }
3067
3068 /* Determines if the expression or type T uses any parameter packs.  */
3069 bool
3070 uses_parameter_packs (tree t)
3071 {
3072   tree parameter_packs = NULL_TREE;
3073   struct find_parameter_pack_data ppd;
3074   ppd.parameter_packs = &parameter_packs;
3075   ppd.visited = pointer_set_create ();
3076   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3077   pointer_set_destroy (ppd.visited);
3078   return parameter_packs != NULL_TREE;
3079 }
3080
3081 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3082    representation a base-class initializer into a parameter pack
3083    expansion. If all goes well, the resulting node will be an
3084    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3085    respectively.  */
3086 tree 
3087 make_pack_expansion (tree arg)
3088 {
3089   tree result;
3090   tree parameter_packs = NULL_TREE;
3091   bool for_types = false;
3092   struct find_parameter_pack_data ppd;
3093
3094   if (!arg || arg == error_mark_node)
3095     return arg;
3096
3097   if (TREE_CODE (arg) == TREE_LIST)
3098     {
3099       /* The only time we will see a TREE_LIST here is for a base
3100          class initializer.  In this case, the TREE_PURPOSE will be a
3101          _TYPE node (representing the base class expansion we're
3102          initializing) and the TREE_VALUE will be a TREE_LIST
3103          containing the initialization arguments. 
3104
3105          The resulting expansion looks somewhat different from most
3106          expansions. Rather than returning just one _EXPANSION, we
3107          return a TREE_LIST whose TREE_PURPOSE is a
3108          TYPE_PACK_EXPANSION containing the bases that will be
3109          initialized.  The TREE_VALUE will be identical to the
3110          original TREE_VALUE, which is a list of arguments that will
3111          be passed to each base.  We do not introduce any new pack
3112          expansion nodes into the TREE_VALUE (although it is possible
3113          that some already exist), because the TREE_PURPOSE and
3114          TREE_VALUE all need to be expanded together with the same
3115          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3116          resulting TREE_PURPOSE will mention the parameter packs in
3117          both the bases and the arguments to the bases.  */
3118       tree purpose;
3119       tree value;
3120       tree parameter_packs = NULL_TREE;
3121
3122       /* Determine which parameter packs will be used by the base
3123          class expansion.  */
3124       ppd.visited = pointer_set_create ();
3125       ppd.parameter_packs = &parameter_packs;
3126       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3127                     &ppd, ppd.visited);
3128
3129       if (parameter_packs == NULL_TREE)
3130         {
3131           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3132           pointer_set_destroy (ppd.visited);
3133           return error_mark_node;
3134         }
3135
3136       if (TREE_VALUE (arg) != void_type_node)
3137         {
3138           /* Collect the sets of parameter packs used in each of the
3139              initialization arguments.  */
3140           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3141             {
3142               /* Determine which parameter packs will be expanded in this
3143                  argument.  */
3144               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3145                             &ppd, ppd.visited);
3146             }
3147         }
3148
3149       pointer_set_destroy (ppd.visited);
3150
3151       /* Create the pack expansion type for the base type.  */
3152       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3153       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3154       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3155
3156       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3157          they will rarely be compared to anything.  */
3158       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3159
3160       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3161     }
3162
3163   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3164     for_types = true;
3165
3166   /* Build the PACK_EXPANSION_* node.  */
3167   result = for_types
3168      ? cxx_make_type (TYPE_PACK_EXPANSION)
3169      : make_node (EXPR_PACK_EXPANSION);
3170   SET_PACK_EXPANSION_PATTERN (result, arg);
3171   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3172     {
3173       /* Propagate type and const-expression information.  */
3174       TREE_TYPE (result) = TREE_TYPE (arg);
3175       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3176     }
3177   else
3178     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3179        they will rarely be compared to anything.  */
3180     SET_TYPE_STRUCTURAL_EQUALITY (result);
3181
3182   /* Determine which parameter packs will be expanded.  */
3183   ppd.parameter_packs = &parameter_packs;
3184   ppd.visited = pointer_set_create ();
3185   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3186   pointer_set_destroy (ppd.visited);
3187
3188   /* Make sure we found some parameter packs.  */
3189   if (parameter_packs == NULL_TREE)
3190     {
3191       if (TYPE_P (arg))
3192         error ("expansion pattern %<%T%> contains no argument packs", arg);
3193       else
3194         error ("expansion pattern %<%E%> contains no argument packs", arg);
3195       return error_mark_node;
3196     }
3197   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3198
3199   return result;
3200 }
3201
3202 /* Checks T for any "bare" parameter packs, which have not yet been
3203    expanded, and issues an error if any are found. This operation can
3204    only be done on full expressions or types (e.g., an expression
3205    statement, "if" condition, etc.), because we could have expressions like:
3206
3207      foo(f(g(h(args)))...)
3208
3209    where "args" is a parameter pack. check_for_bare_parameter_packs
3210    should not be called for the subexpressions args, h(args),
3211    g(h(args)), or f(g(h(args))), because we would produce erroneous
3212    error messages. 
3213
3214    Returns TRUE and emits an error if there were bare parameter packs,
3215    returns FALSE otherwise.  */
3216 bool 
3217 check_for_bare_parameter_packs (tree t)
3218 {
3219   tree parameter_packs = NULL_TREE;
3220   struct find_parameter_pack_data ppd;
3221
3222   if (!processing_template_decl || !t || t == error_mark_node)
3223     return false;
3224
3225   if (TREE_CODE (t) == TYPE_DECL)
3226     t = TREE_TYPE (t);
3227
3228   ppd.parameter_packs = &parameter_packs;
3229   ppd.visited = pointer_set_create ();
3230   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3231   pointer_set_destroy (ppd.visited);
3232
3233   if (parameter_packs) 
3234     {
3235       error ("parameter packs not expanded with %<...%>:");
3236       while (parameter_packs)
3237         {
3238           tree pack = TREE_VALUE (parameter_packs);
3239           tree name = NULL_TREE;
3240
3241           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3242               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3243             name = TYPE_NAME (pack);
3244           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3245             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3246           else
3247             name = DECL_NAME (pack);
3248
3249           if (name)
3250             inform (input_location, "        %qD", name);
3251           else
3252             inform (input_location, "        <anonymous>");
3253
3254           parameter_packs = TREE_CHAIN (parameter_packs);
3255         }
3256
3257       return true;
3258     }
3259
3260   return false;
3261 }
3262
3263 /* Expand any parameter packs that occur in the template arguments in
3264    ARGS.  */
3265 tree
3266 expand_template_argument_pack (tree args)
3267 {
3268   tree result_args = NULL_TREE;
3269   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3270   int num_result_args = -1;
3271   int non_default_args_count = -1;
3272
3273   /* First, determine if we need to expand anything, and the number of
3274      slots we'll need.  */
3275   for (in_arg = 0; in_arg < nargs; ++in_arg)
3276     {
3277       tree arg = TREE_VEC_ELT (args, in_arg);
3278       if (arg == NULL_TREE)
3279         return args;
3280       if (ARGUMENT_PACK_P (arg))
3281         {
3282           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3283           if (num_result_args < 0)
3284             num_result_args = in_arg + num_packed;
3285           else
3286             num_result_args += num_packed;
3287         }
3288       else
3289         {
3290           if (num_result_args >= 0)
3291             num_result_args++;
3292         }
3293     }
3294
3295   /* If no expansion is necessary, we're done.  */
3296   if (num_result_args < 0)
3297     return args;
3298
3299   /* Expand arguments.  */
3300   result_args = make_tree_vec (num_result_args);
3301   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3302     non_default_args_count =
3303       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3304   for (in_arg = 0; in_arg < nargs; ++in_arg)
3305     {
3306       tree arg = TREE_VEC_ELT (args, in_arg);
3307       if (ARGUMENT_PACK_P (arg))
3308         {
3309           tree packed = ARGUMENT_PACK_ARGS (arg);
3310           int i, num_packed = TREE_VEC_LENGTH (packed);
3311           for (i = 0; i < num_packed; ++i, ++out_arg)
3312             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3313           if (non_default_args_count > 0)
3314             non_default_args_count += num_packed;
3315         }
3316       else
3317         {
3318           TREE_VEC_ELT (result_args, out_arg) = arg;
3319           ++out_arg;
3320         }
3321     }
3322   if (non_default_args_count >= 0)
3323     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3324   return result_args;
3325 }
3326
3327 /* Checks if DECL shadows a template parameter.
3328
3329    [temp.local]: A template-parameter shall not be redeclared within its
3330    scope (including nested scopes).
3331
3332    Emits an error and returns TRUE if the DECL shadows a parameter,
3333    returns FALSE otherwise.  */
3334
3335 bool
3336 check_template_shadow (tree decl)
3337 {
3338   tree olddecl;
3339
3340   /* If we're not in a template, we can't possibly shadow a template
3341      parameter.  */
3342   if (!current_template_parms)
3343     return true;
3344
3345   /* Figure out what we're shadowing.  */
3346   if (TREE_CODE (decl) == OVERLOAD)
3347     decl = OVL_CURRENT (decl);
3348   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3349
3350   /* If there's no previous binding for this name, we're not shadowing
3351      anything, let alone a template parameter.  */
3352   if (!olddecl)
3353     return true;
3354
3355   /* If we're not shadowing a template parameter, we're done.  Note
3356      that OLDDECL might be an OVERLOAD (or perhaps even an
3357      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3358      node.  */
3359   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3360     return true;
3361
3362   /* We check for decl != olddecl to avoid bogus errors for using a
3363      name inside a class.  We check TPFI to avoid duplicate errors for
3364      inline member templates.  */
3365   if (decl == olddecl
3366       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3367     return true;
3368
3369   error ("declaration of %q+#D", decl);
3370   error (" shadows template parm %q+#D", olddecl);
3371   return false;
3372 }
3373
3374 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3375    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3376    template parameters.  */
3377
3378 static tree
3379 build_template_parm_index (int index,
3380                            int level,
3381                            int orig_level,
3382                            int num_siblings,
3383                            tree decl,
3384                            tree type)
3385 {
3386   tree t = make_node (TEMPLATE_PARM_INDEX);
3387   TEMPLATE_PARM_IDX (t) = index;
3388   TEMPLATE_PARM_LEVEL (t) = level;
3389   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3390   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3391   TEMPLATE_PARM_DECL (t) = decl;
3392   TREE_TYPE (t) = type;
3393   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3394   TREE_READONLY (t) = TREE_READONLY (decl);
3395
3396   return t;
3397 }
3398
3399 /* Find the canonical type parameter for the given template type
3400    parameter.  Returns the canonical type parameter, which may be TYPE
3401    if no such parameter existed.  */
3402
3403 static tree
3404 canonical_type_parameter (tree type)
3405 {
3406   tree list;
3407   int idx = TEMPLATE_TYPE_IDX (type);
3408   if (!canonical_template_parms)
3409     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3410
3411   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3412     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3413
3414   list = VEC_index (tree, canonical_template_parms, idx);
3415   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3416     list = TREE_CHAIN (list);
3417
3418   if (list)
3419     return TREE_VALUE (list);
3420   else
3421     {
3422       VEC_replace(tree, canonical_template_parms, idx,
3423                   tree_cons (NULL_TREE, type, 
3424                              VEC_index (tree, canonical_template_parms, idx)));
3425       return type;
3426     }
3427 }
3428
3429 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3430    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3431    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3432    new one is created.  */
3433
3434 static tree
3435 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3436                             tsubst_flags_t complain)
3437 {
3438   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3439       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3440           != TEMPLATE_PARM_LEVEL (index) - levels)
3441       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3442     {
3443       tree orig_decl = TEMPLATE_PARM_DECL (index);
3444       tree decl, t;
3445
3446       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3447                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3448       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3449       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3450       DECL_ARTIFICIAL (decl) = 1;
3451       SET_DECL_TEMPLATE_PARM_P (decl);
3452
3453       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3454                                      TEMPLATE_PARM_LEVEL (index) - levels,
3455                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3456                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3457                                      decl, type);
3458       TEMPLATE_PARM_DESCENDANTS (index) = t;
3459       TEMPLATE_PARM_PARAMETER_PACK (t) 
3460         = TEMPLATE_PARM_PARAMETER_PACK (index);
3461
3462         /* Template template parameters need this.  */
3463       if (TREE_CODE (decl) == TEMPLATE_DECL)
3464         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3465           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3466            args, complain);
3467     }
3468
3469   return TEMPLATE_PARM_DESCENDANTS (index);
3470 }
3471
3472 /* Process information from new template parameter PARM and append it
3473    to the LIST being built.  This new parameter is a non-type
3474    parameter iff IS_NON_TYPE is true. This new parameter is a
3475    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3476    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3477    parameter list PARM belongs to. This is used used to create a
3478    proper canonical type for the type of PARM that is to be created,
3479    iff PARM is a type.  If the size is not known, this parameter shall
3480    be set to 0.  */
3481
3482 tree
3483 process_template_parm (tree list, location_t parm_loc, tree parm,
3484                        bool is_non_type, bool is_parameter_pack,
3485                        unsigned num_template_parms)
3486 {
3487   tree decl = 0;
3488   tree defval;
3489   tree err_parm_list;
3490   int idx = 0;
3491
3492   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3493   defval = TREE_PURPOSE (parm);
3494
3495   if (list)
3496     {
3497       tree p = tree_last (list);
3498
3499       if (p && TREE_VALUE (p) != error_mark_node)
3500         {
3501           p = TREE_VALUE (p);
3502           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3503             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3504           else
3505             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3506         }
3507
3508       ++idx;
3509     }
3510   else
3511     idx = 0;
3512
3513   if (is_non_type)
3514     {
3515       parm = TREE_VALUE (parm);
3516
3517       SET_DECL_TEMPLATE_PARM_P (parm);
3518
3519       if (TREE_TYPE (parm) == error_mark_node)
3520         {
3521           err_parm_list = build_tree_list (defval, parm);
3522           TREE_VALUE (err_parm_list) = error_mark_node;
3523            return chainon (list, err_parm_list);
3524         }
3525       else
3526       {
3527         /* [temp.param]
3528
3529            The top-level cv-qualifiers on the template-parameter are
3530            ignored when determining its type.  */
3531         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3532         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3533           {
3534             err_parm_list = build_tree_list (defval, parm);
3535             TREE_VALUE (err_parm_list) = error_mark_node;
3536              return chainon (list, err_parm_list);
3537           }
3538
3539         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3540           {
3541             /* This template parameter is not a parameter pack, but it
3542                should be. Complain about "bare" parameter packs.  */
3543             check_for_bare_parameter_packs (TREE_TYPE (parm));
3544             
3545             /* Recover by calling this a parameter pack.  */
3546             is_parameter_pack = true;
3547           }
3548       }
3549
3550       /* A template parameter is not modifiable.  */
3551       TREE_CONSTANT (parm) = 1;
3552       TREE_READONLY (parm) = 1;
3553       decl = build_decl (parm_loc,
3554                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3555       TREE_CONSTANT (decl) = 1;
3556       TREE_READONLY (decl) = 1;
3557       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3558         = build_template_parm_index (idx, processing_template_decl,
3559                                      processing_template_decl,
3560                                      num_template_parms,
3561                                      decl, TREE_TYPE (parm));
3562
3563       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3564         = is_parameter_pack;
3565     }
3566   else
3567     {
3568       tree t;
3569       parm = TREE_VALUE (TREE_VALUE (parm));
3570
3571       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3572         {
3573           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3574           /* This is for distinguishing between real templates and template
3575              template parameters */
3576           TREE_TYPE (parm) = t;
3577           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3578           decl = parm;
3579         }
3580       else
3581         {
3582           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3583           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3584           decl = build_decl (parm_loc,
3585                              TYPE_DECL, parm, t);
3586         }
3587
3588       TYPE_NAME (t) = decl;
3589       TYPE_STUB_DECL (t) = decl;
3590       parm = decl;
3591       TEMPLATE_TYPE_PARM_INDEX (t)
3592         = build_template_parm_index (idx, processing_template_decl,
3593                                      processing_template_decl,
3594                                      num_template_parms,
3595                                      decl, TREE_TYPE (parm));
3596       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3597       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3598     }
3599   DECL_ARTIFICIAL (decl) = 1;
3600   SET_DECL_TEMPLATE_PARM_P (decl);
3601   pushdecl (decl);
3602   parm = build_tree_list (defval, parm);
3603   return chainon (list, parm);
3604 }
3605
3606 /* The end of a template parameter list has been reached.  Process the
3607    tree list into a parameter vector, converting each parameter into a more
3608    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3609    as PARM_DECLs.  */
3610
3611 tree
3612 end_template_parm_list (tree parms)
3613 {
3614   int nparms;
3615   tree parm, next;
3616   tree saved_parmlist = make_tree_vec (list_length (parms));
3617
3618   current_template_parms
3619     = tree_cons (size_int (processing_template_decl),
3620                  saved_parmlist, current_template_parms);
3621
3622   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3623     {
3624       next = TREE_CHAIN (parm);
3625       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3626       TREE_CHAIN (parm) = NULL_TREE;
3627     }
3628
3629   --processing_template_parmlist;
3630
3631   return saved_parmlist;
3632 }
3633
3634 /* Create a new type almost identical to TYPE but which has the
3635    following differences:
3636
3637      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3638      template sibling parameters of T.
3639
3640      2/ T has a new canonical type that matches the new number
3641      of sibling parms.
3642
3643      3/ From now on, T is going to be what lookups referring to the
3644      name of TYPE will return. No lookup should return TYPE anymore.
3645
3646    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3647
3648    This is a subroutine of fixup_template_parms.  */
3649
3650 static tree
3651 fixup_template_type_parm_type (tree type, int num_parms)
3652 {
3653   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3654   tree t;
3655   /* This is the decl which name is inserted into the symbol table for
3656      the template parm type. So whenever we lookup the type name, this
3657      is the DECL we get.  */
3658   tree decl;
3659
3660   /* Do not fix up the type twice.  */
3661   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3662     return type;
3663
3664   t = copy_type (type);
3665   decl = TYPE_NAME (t);
3666
3667   TYPE_MAIN_VARIANT (t) = t;
3668   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3669   TYPE_POINTER_TO (t) = 0;
3670   TYPE_REFERENCE_TO (t) = 0;
3671
3672   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3673                                    TEMPLATE_PARM_LEVEL (orig_idx),
3674                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3675                                    num_parms,
3676                                    decl, t);
3677   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3678   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3679   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3680
3681   TYPE_STUB_DECL (t) = decl;
3682   TEMPLATE_TYPE_DECL (t) = decl;
3683   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3684     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3685
3686   /* Update the type associated to the type name stored in the symbol
3687      table. Now, whenever the type name is looked up, the resulting
3688      type is properly fixed up.  */
3689   TREE_TYPE (decl) = t;
3690
3691   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3692
3693   return t;
3694 }
3695
3696 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3697    identical to I, but that is fixed up as to:
3698
3699    1/ carry the number of sibling parms (NUM_PARMS) of the template
3700    parm represented by I.
3701
3702    2/ replace all references to template parm types declared before I
3703    (in the same template parm list as I) by references to template
3704    parm types contained in ARGS. ARGS should contain the list of
3705    template parms that have been fixed up so far, in a form suitable
3706    to be passed to tsubst.
3707
3708    This is a subroutine of fixup_template_parms.  */
3709
3710 static tree
3711 fixup_template_parm_index (tree i, tree args, int num_parms)
3712 {
3713   tree index, decl, type;
3714
3715   if (i == NULL_TREE
3716       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3717       /* Do not fix up the index twice.  */
3718       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3719     return i;
3720
3721   decl = TEMPLATE_PARM_DECL (i);
3722   type = TREE_TYPE (decl);
3723
3724   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3725                                      TEMPLATE_PARM_LEVEL (i),
3726                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3727                                      num_parms,
3728                                      decl, type);
3729
3730   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3731   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3732
3733   type = tsubst (type, args, tf_none, NULL_TREE);
3734   
3735   TREE_TYPE (decl) = type;
3736   TREE_TYPE (index) = type;
3737
3738   return index;
3739 }
3740
3741 /* 
3742    This is a subroutine of fixup_template_parms.
3743
3744    It computes the canonical type of the type of the template
3745    parameter PARM_DESC and update all references to that type so that
3746    they use the newly computed canonical type. No access check is
3747    performed during the fixup. PARM_DESC is a TREE_LIST which
3748    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3749    default argument of the template parm if any. IDX is the index of
3750    the template parameter, starting at 0. NUM_PARMS is the number of
3751    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3752    TREE_VEC containing the full set of template parameters in a form
3753    suitable to be passed to substs functions as their ARGS
3754    argument. This is what current_template_args returns for a given
3755    template. The innermost vector of args in ARGLIST is the set of
3756    template parms that have been fixed up so far. This function adds
3757    the fixed up parameter into that vector.  */
3758
3759 static void
3760 fixup_template_parm (tree parm_desc,
3761                      int idx,
3762                      int num_parms,
3763                      tree arglist)
3764 {
3765   tree parm = TREE_VALUE (parm_desc);
3766   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3767
3768   push_deferring_access_checks (dk_no_check);
3769
3770   if (TREE_CODE (parm) == TYPE_DECL)
3771     {
3772       /* PARM is a template type parameter. Fix up its type, add
3773          the fixed-up template parm to the vector of fixed-up
3774          template parms so far, and substitute the fixed-up
3775          template parms into the default argument of this
3776          parameter.  */
3777       tree t =
3778         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3779       TREE_TYPE (parm) = t;
3780
3781       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3782     }
3783   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3784     {
3785       /* PARM is a template template parameter. This is going to
3786          be interesting.  */
3787       tree tparms, targs, innermost_args, t;
3788       int j;
3789
3790       /* First, fix up the parms of the template template parm
3791          because the parms are involved in defining the new canonical
3792          type of the template template parm.  */
3793
3794       /* So we need to substitute the template parm types that have
3795          been fixed up so far into the template parms of this template
3796          template parm. E.g, consider this:
3797
3798          template<class T, template<T u> class TT> class S;
3799
3800          In this case we want to substitute T into the
3801          template parameters of TT.
3802
3803          So let's walk the template parms of PARM here, and
3804          tsubst ARGLIST into into each of the template
3805          parms.   */
3806
3807       /* For this substitution we need to build the full set of
3808          template parameters and use that as arguments for the
3809          tsubsting function.  */
3810       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3811
3812       /* This will contain the innermost parms of PARM into which
3813          we have substituted so far.  */
3814       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3815       targs = add_to_template_args (arglist, innermost_args);
3816       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3817         {
3818           tree parameter;
3819
3820           parameter = TREE_VEC_ELT (tparms, j);
3821
3822           /* INNERMOST_ARGS needs to have at least the same number
3823              of elements as the index PARAMETER, ortherwise
3824              tsubsting into PARAMETER will result in partially
3825              instantiating it, reducing its tempate parm
3826              level. Let's tactically fill INNERMOST_ARGS for that
3827              purpose.  */
3828           TREE_VEC_ELT (innermost_args, j) =
3829             template_parm_to_arg (parameter);
3830
3831           fixup_template_parm (parameter, j,
3832                                TREE_VEC_LENGTH (tparms),
3833                                targs);
3834         }
3835
3836       /* Now fix up the type of the template template parm.  */
3837
3838       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3839       TREE_TYPE (parm) = t;
3840
3841       TREE_VEC_ELT (fixedup_args, idx) =
3842         template_parm_to_arg (parm_desc);
3843     }
3844   else if (TREE_CODE (parm) == PARM_DECL)
3845     {
3846       /* PARM is a non-type template parameter. We need to:
3847
3848        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3849        proper number of sibling parameters.
3850
3851        * Make lookups of the template parameter return a reference
3852        to the fixed-up index. No lookup should return references
3853        to the former index anymore.
3854
3855        * Substitute the template parms that got fixed up so far
3856
3857        * into the type of PARM.  */
3858
3859       tree index = DECL_INITIAL (parm);
3860
3861       /* PUSHED_DECL is the decl added to the symbol table with
3862          the name of the parameter. E,g:
3863              
3864          template<class T, T u> //#0
3865          auto my_function(T t) -> decltype(u); //#1
3866
3867          Here, when looking up u at //#1, we get the decl of u
3868          resulting from the declaration in #0. This is what
3869          PUSHED_DECL is. We need to replace the reference to the
3870          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3871          fixed-up TEMPLATE_PARM_INDEX.  */
3872       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3873
3874       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3875          fixup the type of PUSHED_DECL as well and luckily
3876          fixup_template_parm_index does it for us too.  */
3877       tree fixed_up_index =
3878         fixup_template_parm_index (index, arglist, num_parms);
3879
3880       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3881
3882       /* Add this fixed up PARM to the template parms we've fixed
3883          up so far and use that to substitute the fixed-up
3884          template parms into the type of PARM.  */
3885       TREE_VEC_ELT (fixedup_args, idx) =
3886         template_parm_to_arg (parm_desc);
3887       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3888                                  tf_none, NULL_TREE);
3889     }
3890
3891   TREE_PURPOSE (parm_desc) =
3892     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3893                          arglist, tf_none, parm);
3894
3895   pop_deferring_access_checks ();
3896 }
3897
3898 /* Walk the current template parms and properly compute the canonical
3899    types of the dependent types created during
3900    cp_parser_template_parameter_list.  */
3901
3902 void
3903 fixup_template_parms (void)
3904 {
3905   tree arglist;
3906   tree parameter_vec;
3907   tree fixedup_args;
3908   int i, num_parms;
3909
3910   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3911   if (parameter_vec == NULL_TREE)
3912     return;
3913
3914   num_parms = TREE_VEC_LENGTH (parameter_vec);
3915
3916   /* This vector contains the current innermost template parms that
3917      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3918      to be passed to tsubst* functions as their ARGS argument.  */
3919   fixedup_args = make_tree_vec (num_parms);
3920
3921   /* This vector contains the full set of template parms in a form
3922      suitable to be passed to substs functions as their ARGS
3923      argument.  */
3924   arglist = current_template_args ();
3925   arglist = add_outermost_template_args (arglist, fixedup_args);
3926
3927   /* Let's do the proper fixup now.  */
3928   for (i = 0; i < num_parms; ++i)
3929     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3930                          i, num_parms, arglist);
3931 }
3932
3933 /* end_template_decl is called after a template declaration is seen.  */
3934
3935 void
3936 end_template_decl (void)
3937 {
3938   reset_specialization ();
3939
3940   if (! processing_template_decl)
3941     return;
3942
3943   /* This matches the pushlevel in begin_template_parm_list.  */
3944   finish_scope ();
3945
3946   --processing_template_decl;
3947   current_template_parms = TREE_CHAIN (current_template_parms);
3948 }
3949
3950 /* Takes a TREE_LIST representing a template parameter and convert it
3951    into an argument suitable to be passed to the type substitution
3952    functions.  Note that If the TREE_LIST contains an error_mark
3953    node, the returned argument is error_mark_node.  */
3954
3955 static tree
3956 template_parm_to_arg (tree t)
3957 {
3958
3959   if (t == NULL_TREE
3960       || TREE_CODE (t) != TREE_LIST)
3961     return t;
3962
3963   if (error_operand_p (TREE_VALUE (t)))
3964     return error_mark_node;
3965
3966   t = TREE_VALUE (t);
3967
3968   if (TREE_CODE (t) == TYPE_DECL
3969       || TREE_CODE (t) == TEMPLATE_DECL)
3970     {
3971       t = TREE_TYPE (t);
3972
3973       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3974         {
3975           /* Turn this argument into a TYPE_ARGUMENT_PACK
3976              with a single element, which expands T.  */
3977           tree vec = make_tree_vec (1);
3978 #ifdef ENABLE_CHECKING
3979           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3980             (vec, TREE_VEC_LENGTH (vec));
3981 #endif
3982           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3983
3984           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3985           SET_ARGUMENT_PACK_ARGS (t, vec);
3986         }
3987     }
3988   else
3989     {
3990       t = DECL_INITIAL (t);
3991
3992       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3993         {
3994           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3995              with a single element, which expands T.  */
3996           tree vec = make_tree_vec (1);
3997           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3998 #ifdef ENABLE_CHECKING
3999           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
4000             (vec, TREE_VEC_LENGTH (vec));
4001 #endif
4002           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4003
4004           t  = make_node (NONTYPE_ARGUMENT_PACK);
4005           SET_ARGUMENT_PACK_ARGS (t, vec);
4006           TREE_TYPE (t) = type;
4007         }
4008     }
4009   return t;
4010 }
4011
4012 /* This function returns TRUE if PARM_PACK is a template parameter
4013    pack and if ARG_PACK is what template_parm_to_arg returned when
4014    passed PARM_PACK.  */
4015
4016 static bool
4017 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
4018 {
4019   /* For clarity in the comments below let's use the representation
4020      argument_pack<elements>' to denote an argument pack and its
4021      elements.
4022
4023      In the 'if' block below, we want to detect cases where
4024      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
4025      check if ARG_PACK is an argument pack which sole element is
4026      the expansion of PARM_PACK.  That argument pack is typically
4027      created by template_parm_to_arg when passed a parameter
4028      pack.  */
4029
4030   if (arg_pack
4031       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
4032       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
4033     {
4034       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
4035       tree pattern = PACK_EXPANSION_PATTERN (expansion);
4036       /* So we have an argument_pack<P...>.  We want to test if P
4037          is actually PARM_PACK.  We will not use cp_tree_equal to
4038          test P and PARM_PACK because during type fixup (by
4039          fixup_template_parm) P can be a pre-fixup version of a
4040          type and PARM_PACK be its post-fixup version.
4041          cp_tree_equal would consider them as different even
4042          though we would want to consider them compatible for our
4043          precise purpose here.
4044
4045          Thus we are going to consider that P and PARM_PACK are
4046          compatible if they have the same DECL.  */
4047       if ((/* If ARG_PACK is a type parameter pack named by the
4048               same DECL as parm_pack ...  */
4049            (TYPE_P (pattern)
4050             && TYPE_P (parm_pack)
4051             && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
4052            /* ... or if PARM_PACK is a non-type parameter named by the
4053               same DECL as ARG_PACK.  Note that PARM_PACK being a
4054               non-type parameter means it's either a PARM_DECL or a
4055               TEMPLATE_PARM_INDEX.  */
4056            || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
4057                && ((TREE_CODE (parm_pack) == PARM_DECL
4058                     && (TEMPLATE_PARM_DECL (pattern)
4059                         == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
4060                    || (TREE_CODE (parm_pack) == TEMPLATE_PARM_INDEX
4061                        && (TEMPLATE_PARM_DECL (pattern)
4062                            == TEMPLATE_PARM_DECL (parm_pack))))))
4063           && template_parameter_pack_p (pattern))
4064         return true;
4065     }
4066   return false;
4067 }
4068
4069 /* Within the declaration of a template, return all levels of template
4070    parameters that apply.  The template parameters are represented as
4071    a TREE_VEC, in the form documented in cp-tree.h for template
4072    arguments.  */
4073
4074 static tree
4075 current_template_args (void)
4076 {
4077   tree header;
4078   tree args = NULL_TREE;
4079   int length = TMPL_PARMS_DEPTH (current_template_parms);
4080   int l = length;
4081
4082   /* If there is only one level of template parameters, we do not
4083      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4084      TREE_VEC containing the arguments.  */
4085   if (length > 1)
4086     args = make_tree_vec (length);
4087
4088   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4089     {
4090       tree a = copy_node (TREE_VALUE (header));
4091       int i;
4092
4093       TREE_TYPE (a) = NULL_TREE;
4094       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4095         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4096
4097 #ifdef ENABLE_CHECKING
4098       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4099 #endif
4100
4101       if (length > 1)
4102         TREE_VEC_ELT (args, --l) = a;
4103       else
4104         args = a;
4105     }
4106
4107     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4108       /* This can happen for template parms of a template template
4109          parameter, e.g:
4110
4111          template<template<class T, class U> class TT> struct S;
4112
4113          Consider the level of the parms of TT; T and U both have
4114          level 2; TT has no template parm of level 1. So in this case
4115          the first element of full_template_args is NULL_TREE. If we
4116          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4117          of 2. This will make tsubst wrongly consider that T and U
4118          have level 1. Instead, let's create a dummy vector as the
4119          first element of full_template_args so that TMPL_ARG_DEPTH
4120          returns the correct depth for args.  */
4121       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4122   return args;
4123 }
4124
4125 /* Update the declared TYPE by doing any lookups which were thought to be
4126    dependent, but are not now that we know the SCOPE of the declarator.  */
4127
4128 tree
4129 maybe_update_decl_type (tree orig_type, tree scope)
4130 {
4131   tree type = orig_type;
4132
4133   if (type == NULL_TREE)
4134     return type;
4135
4136   if (TREE_CODE (orig_type) == TYPE_DECL)
4137     type = TREE_TYPE (type);
4138
4139   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4140       && dependent_type_p (type)
4141       /* Don't bother building up the args in this case.  */
4142       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4143     {
4144       /* tsubst in the args corresponding to the template parameters,
4145          including auto if present.  Most things will be unchanged, but
4146          make_typename_type and tsubst_qualified_id will resolve
4147          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4148       tree args = current_template_args ();
4149       tree auto_node = type_uses_auto (type);
4150       tree pushed;
4151       if (auto_node)
4152         {
4153           tree auto_vec = make_tree_vec (1);
4154           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4155           args = add_to_template_args (args, auto_vec);
4156         }
4157       pushed = push_scope (scope);
4158       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4159       if (pushed)
4160         pop_scope (scope);
4161     }
4162
4163   if (type == error_mark_node)
4164     return orig_type;
4165
4166   if (TREE_CODE (orig_type) == TYPE_DECL)
4167     {
4168       if (same_type_p (type, TREE_TYPE (orig_type)))
4169         type = orig_type;
4170       else
4171         type = TYPE_NAME (type);
4172     }
4173   return type;
4174 }
4175
4176 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4177    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4178    a member template.  Used by push_template_decl below.  */
4179
4180 static tree
4181 build_template_decl (tree decl, tree parms, bool member_template_p)
4182 {
4183   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4184   DECL_TEMPLATE_PARMS (tmpl) = parms;
4185   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4186   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4187   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4188
4189   return tmpl;
4190 }
4191
4192 struct template_parm_data
4193 {
4194   /* The level of the template parameters we are currently
4195      processing.  */
4196   int level;
4197
4198   /* The index of the specialization argument we are currently
4199      processing.  */
4200   int current_arg;
4201
4202   /* An array whose size is the number of template parameters.  The
4203      elements are nonzero if the parameter has been used in any one
4204      of the arguments processed so far.  */
4205   int* parms;
4206
4207   /* An array whose size is the number of template arguments.  The
4208      elements are nonzero if the argument makes use of template
4209      parameters of this level.  */
4210   int* arg_uses_template_parms;
4211 };
4212
4213 /* Subroutine of push_template_decl used to see if each template
4214    parameter in a partial specialization is used in the explicit
4215    argument list.  If T is of the LEVEL given in DATA (which is
4216    treated as a template_parm_data*), then DATA->PARMS is marked
4217    appropriately.  */
4218
4219 static int
4220 mark_template_parm (tree t, void* data)
4221 {
4222   int level;
4223   int idx;
4224   struct template_parm_data* tpd = (struct template_parm_data*) data;
4225
4226   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4227     {
4228       level = TEMPLATE_PARM_LEVEL (t);
4229       idx = TEMPLATE_PARM_IDX (t);
4230     }
4231   else
4232     {
4233       level = TEMPLATE_TYPE_LEVEL (t);
4234       idx = TEMPLATE_TYPE_IDX (t);
4235     }
4236
4237   if (level == tpd->level)
4238     {
4239       tpd->parms[idx] = 1;
4240       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4241     }
4242
4243   /* Return zero so that for_each_template_parm will continue the
4244      traversal of the tree; we want to mark *every* template parm.  */
4245   return 0;
4246 }
4247
4248 /* Process the partial specialization DECL.  */
4249
4250 static tree
4251 process_partial_specialization (tree decl)
4252 {
4253   tree type = TREE_TYPE (decl);
4254   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4255   tree specargs = CLASSTYPE_TI_ARGS (type);
4256   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4257   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4258   tree inner_parms;
4259   tree inst;
4260   int nargs = TREE_VEC_LENGTH (inner_args);
4261   int ntparms;
4262   int  i;
4263   bool did_error_intro = false;
4264   struct template_parm_data tpd;
4265   struct template_parm_data tpd2;
4266
4267   gcc_assert (current_template_parms);
4268
4269   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4270   ntparms = TREE_VEC_LENGTH (inner_parms);
4271
4272   /* We check that each of the template parameters given in the
4273      partial specialization is used in the argument list to the
4274      specialization.  For example:
4275
4276        template <class T> struct S;
4277        template <class T> struct S<T*>;
4278
4279      The second declaration is OK because `T*' uses the template
4280      parameter T, whereas
4281
4282        template <class T> struct S<int>;
4283
4284      is no good.  Even trickier is:
4285
4286        template <class T>
4287        struct S1
4288        {
4289           template <class U>
4290           struct S2;
4291           template <class U>
4292           struct S2<T>;
4293        };
4294
4295      The S2<T> declaration is actually invalid; it is a
4296      full-specialization.  Of course,
4297
4298           template <class U>
4299           struct S2<T (*)(U)>;
4300
4301      or some such would have been OK.  */
4302   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4303   tpd.parms = XALLOCAVEC (int, ntparms);
4304   memset (tpd.parms, 0, sizeof (int) * ntparms);
4305
4306   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4307   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4308   for (i = 0; i < nargs; ++i)
4309     {
4310       tpd.current_arg = i;
4311       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4312                               &mark_template_parm,
4313                               &tpd,
4314                               NULL,
4315                               /*include_nondeduced_p=*/false);
4316     }
4317   for (i = 0; i < ntparms; ++i)
4318     if (tpd.parms[i] == 0)
4319       {
4320         /* One of the template parms was not used in the
4321            specialization.  */
4322         if (!did_error_intro)
4323           {
4324             error ("template parameters not used in partial specialization:");
4325             did_error_intro = true;
4326           }
4327
4328         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4329       }
4330
4331   if (did_error_intro)
4332     return error_mark_node;
4333
4334   /* [temp.class.spec]
4335
4336      The argument list of the specialization shall not be identical to
4337      the implicit argument list of the primary template.  */
4338   if (comp_template_args
4339       (inner_args,
4340        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4341                                                    (maintmpl)))))
4342     error ("partial specialization %qT does not specialize any template arguments", type);
4343
4344   /* [temp.class.spec]
4345
4346      A partially specialized non-type argument expression shall not
4347      involve template parameters of the partial specialization except
4348      when the argument expression is a simple identifier.
4349
4350      The type of a template parameter corresponding to a specialized
4351      non-type argument shall not be dependent on a parameter of the
4352      specialization. 
4353
4354      Also, we verify that pack expansions only occur at the
4355      end of the argument list.  */
4356   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4357   tpd2.parms = 0;
4358   for (i = 0; i < nargs; ++i)
4359     {
4360       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4361       tree arg = TREE_VEC_ELT (inner_args, i);
4362       tree packed_args = NULL_TREE;
4363       int j, len = 1;
4364
4365       if (ARGUMENT_PACK_P (arg))
4366         {
4367           /* Extract the arguments from the argument pack. We'll be
4368              iterating over these in the following loop.  */
4369           packed_args = ARGUMENT_PACK_ARGS (arg);
4370           len = TREE_VEC_LENGTH (packed_args);
4371         }
4372
4373       for (j = 0; j < len; j++)
4374         {
4375           if (packed_args)
4376             /* Get the Jth argument in the parameter pack.  */
4377             arg = TREE_VEC_ELT (packed_args, j);
4378
4379           if (PACK_EXPANSION_P (arg))
4380             {
4381               /* Pack expansions must come at the end of the
4382                  argument list.  */
4383               if ((packed_args && j < len - 1)
4384                   || (!packed_args && i < nargs - 1))
4385                 {
4386                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4387                     error ("parameter pack argument %qE must be at the "
4388                            "end of the template argument list", arg);
4389                   else
4390                     error ("parameter pack argument %qT must be at the "
4391                            "end of the template argument list", arg);
4392                 }
4393             }
4394
4395           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4396             /* We only care about the pattern.  */
4397             arg = PACK_EXPANSION_PATTERN (arg);
4398
4399           if (/* These first two lines are the `non-type' bit.  */
4400               !TYPE_P (arg)
4401               && TREE_CODE (arg) != TEMPLATE_DECL
4402               /* This next line is the `argument expression is not just a
4403                  simple identifier' condition and also the `specialized
4404                  non-type argument' bit.  */
4405               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4406             {
4407               if ((!packed_args && tpd.arg_uses_template_parms[i])
4408                   || (packed_args && uses_template_parms (arg)))
4409                 error ("template argument %qE involves template parameter(s)",
4410                        arg);
4411               else 
4412                 {
4413                   /* Look at the corresponding template parameter,
4414                      marking which template parameters its type depends
4415                      upon.  */
4416                   tree type = TREE_TYPE (parm);
4417
4418                   if (!tpd2.parms)
4419                     {
4420                       /* We haven't yet initialized TPD2.  Do so now.  */
4421                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4422                       /* The number of parameters here is the number in the
4423                          main template, which, as checked in the assertion
4424                          above, is NARGS.  */
4425                       tpd2.parms = XALLOCAVEC (int, nargs);
4426                       tpd2.level = 
4427                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4428                     }
4429
4430                   /* Mark the template parameters.  But this time, we're
4431                      looking for the template parameters of the main
4432                      template, not in the specialization.  */
4433                   tpd2.current_arg = i;
4434                   tpd2.arg_uses_template_parms[i] = 0;
4435                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4436                   for_each_template_parm (type,
4437                                           &mark_template_parm,
4438                                           &tpd2,
4439                                           NULL,
4440                                           /*include_nondeduced_p=*/false);
4441
4442                   if (tpd2.arg_uses_template_parms [i])
4443                     {
4444                       /* The type depended on some template parameters.
4445                          If they are fully specialized in the
4446                          specialization, that's OK.  */
4447                       int j;
4448                       int count = 0;
4449                       for (j = 0; j < nargs; ++j)
4450                         if (tpd2.parms[j] != 0
4451                             && tpd.arg_uses_template_parms [j])
4452                           ++count;
4453                       if (count != 0)
4454                         error_n (input_location, count,
4455                                  "type %qT of template argument %qE depends "
4456                                  "on a template parameter",
4457                                  "type %qT of template argument %qE depends "
4458                                  "on template parameters",
4459                                  type,
4460                                  arg);
4461                     }
4462                 }
4463             }
4464         }
4465     }
4466
4467   /* We should only get here once.  */
4468   gcc_assert (!COMPLETE_TYPE_P (type));
4469
4470   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4471     = tree_cons (specargs, inner_parms,
4472                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4473   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4474
4475   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4476        inst = TREE_CHAIN (inst))
4477     {
4478       tree inst_type = TREE_VALUE (inst);
4479       if (COMPLETE_TYPE_P (inst_type)
4480           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4481         {
4482           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4483           if (spec && TREE_TYPE (spec) == type)
4484             permerror (input_location,
4485                        "partial specialization of %qT after instantiation "
4486                        "of %qT", type, inst_type);
4487         }
4488     }
4489
4490   return decl;
4491 }
4492
4493 /* Check that a template declaration's use of default arguments and
4494    parameter packs is not invalid.  Here, PARMS are the template
4495    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4496    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4497    specialization.
4498    
4499
4500    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4501    declaration (but not a definition); 1 indicates a declaration, 2
4502    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4503    emitted for extraneous default arguments.
4504
4505    Returns TRUE if there were no errors found, FALSE otherwise. */
4506
4507 bool
4508 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4509                          int is_partial, int is_friend_decl)
4510 {
4511   const char *msg;
4512   int last_level_to_check;
4513   tree parm_level;
4514   bool no_errors = true;
4515
4516   /* [temp.param]
4517
4518      A default template-argument shall not be specified in a
4519      function template declaration or a function template definition, nor
4520      in the template-parameter-list of the definition of a member of a
4521      class template.  */
4522
4523   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4524     /* You can't have a function template declaration in a local
4525        scope, nor you can you define a member of a class template in a
4526        local scope.  */
4527     return true;
4528
4529   if (current_class_type
4530       && !TYPE_BEING_DEFINED (current_class_type)
4531       && DECL_LANG_SPECIFIC (decl)
4532       && DECL_DECLARES_FUNCTION_P (decl)
4533       /* If this is either a friend defined in the scope of the class
4534          or a member function.  */
4535       && (DECL_FUNCTION_MEMBER_P (decl)
4536           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4537           : DECL_FRIEND_CONTEXT (decl)
4538           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4539           : false)
4540       /* And, if it was a member function, it really was defined in
4541          the scope of the class.  */
4542       && (!DECL_FUNCTION_MEMBER_P (decl)
4543           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4544     /* We already checked these parameters when the template was
4545        declared, so there's no need to do it again now.  This function
4546        was defined in class scope, but we're processing it's body now
4547        that the class is complete.  */
4548     return true;
4549
4550   /* Core issue 226 (C++0x only): the following only applies to class
4551      templates.  */
4552   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4553     {
4554       /* [temp.param]
4555
4556          If a template-parameter has a default template-argument, all
4557          subsequent template-parameters shall have a default
4558          template-argument supplied.  */
4559       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4560         {
4561           tree inner_parms = TREE_VALUE (parm_level);
4562           int ntparms = TREE_VEC_LENGTH (inner_parms);
4563           int seen_def_arg_p = 0;
4564           int i;
4565
4566           for (i = 0; i < ntparms; ++i)
4567             {
4568               tree parm = TREE_VEC_ELT (inner_parms, i);
4569
4570               if (parm == error_mark_node)
4571                 continue;
4572
4573               if (TREE_PURPOSE (parm))
4574                 seen_def_arg_p = 1;
4575               else if (seen_def_arg_p
4576                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4577                 {
4578                   error ("no default argument for %qD", TREE_VALUE (parm));
4579                   /* For better subsequent error-recovery, we indicate that
4580                      there should have been a default argument.  */
4581                   TREE_PURPOSE (parm) = error_mark_node;
4582                   no_errors = false;
4583                 }
4584               else if (is_primary
4585                        && !is_partial
4586                        && !is_friend_decl
4587                        /* Don't complain about an enclosing partial
4588                           specialization.  */
4589                        && parm_level == parms
4590                        && TREE_CODE (decl) == TYPE_DECL
4591                        && i < ntparms - 1
4592                        && template_parameter_pack_p (TREE_VALUE (parm)))
4593                 {
4594                   /* A primary class template can only have one
4595                      parameter pack, at the end of the template
4596                      parameter list.  */
4597
4598                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4599                     error ("parameter pack %qE must be at the end of the"
4600                            " template parameter list", TREE_VALUE (parm));
4601                   else
4602                     error ("parameter pack %qT must be at the end of the"
4603                            " template parameter list", 
4604                            TREE_TYPE (TREE_VALUE (parm)));
4605
4606                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4607                     = error_mark_node;
4608                   no_errors = false;
4609                 }
4610             }
4611         }
4612     }
4613
4614   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4615       || is_partial 
4616       || !is_primary
4617       || is_friend_decl)
4618     /* For an ordinary class template, default template arguments are
4619        allowed at the innermost level, e.g.:
4620          template <class T = int>
4621          struct S {};
4622        but, in a partial specialization, they're not allowed even
4623        there, as we have in [temp.class.spec]:
4624
4625          The template parameter list of a specialization shall not
4626          contain default template argument values.
4627
4628        So, for a partial specialization, or for a function template
4629        (in C++98/C++03), we look at all of them.  */
4630     ;
4631   else
4632     /* But, for a primary class template that is not a partial
4633        specialization we look at all template parameters except the
4634        innermost ones.  */
4635     parms = TREE_CHAIN (parms);
4636
4637   /* Figure out what error message to issue.  */
4638   if (is_friend_decl == 2)
4639     msg = G_("default template arguments may not be used in function template "
4640              "friend re-declaration");
4641   else if (is_friend_decl)
4642     msg = G_("default template arguments may not be used in function template "
4643              "friend declarations");
4644   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4645     msg = G_("default template arguments may not be used in function templates "
4646              "without -std=c++0x or -std=gnu++0x");
4647   else if (is_partial)
4648     msg = G_("default template arguments may not be used in "
4649              "partial specializations");
4650   else
4651     msg = G_("default argument for template parameter for class enclosing %qD");
4652
4653   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4654     /* If we're inside a class definition, there's no need to
4655        examine the parameters to the class itself.  On the one
4656        hand, they will be checked when the class is defined, and,
4657        on the other, default arguments are valid in things like:
4658          template <class T = double>
4659          struct S { template <class U> void f(U); };
4660        Here the default argument for `S' has no bearing on the
4661        declaration of `f'.  */
4662     last_level_to_check = template_class_depth (current_class_type) + 1;
4663   else
4664     /* Check everything.  */
4665     last_level_to_check = 0;
4666
4667   for (parm_level = parms;
4668        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4669        parm_level = TREE_CHAIN (parm_level))
4670     {
4671       tree inner_parms = TREE_VALUE (parm_level);
4672       int i;
4673       int ntparms;
4674
4675       ntparms = TREE_VEC_LENGTH (inner_parms);
4676       for (i = 0; i < ntparms; ++i)
4677         {
4678           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4679             continue;
4680
4681           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4682             {
4683               if (msg)
4684                 {
4685                   no_errors = false;
4686                   if (is_friend_decl == 2)
4687                     return no_errors;
4688
4689                   error (msg, decl);
4690                   msg = 0;
4691                 }
4692
4693               /* Clear out the default argument so that we are not
4694                  confused later.  */
4695               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4696             }
4697         }
4698
4699       /* At this point, if we're still interested in issuing messages,
4700          they must apply to classes surrounding the object declared.  */
4701       if (msg)
4702         msg = G_("default argument for template parameter for class "
4703                  "enclosing %qD");
4704     }
4705
4706   return no_errors;
4707 }
4708
4709 /* Worker for push_template_decl_real, called via
4710    for_each_template_parm.  DATA is really an int, indicating the
4711    level of the parameters we are interested in.  If T is a template
4712    parameter of that level, return nonzero.  */
4713
4714 static int
4715 template_parm_this_level_p (tree t, void* data)
4716 {
4717   int this_level = *(int *)data;
4718   int level;
4719
4720   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4721     level = TEMPLATE_PARM_LEVEL (t);
4722   else
4723     level = TEMPLATE_TYPE_LEVEL (t);
4724   return level == this_level;
4725 }
4726
4727 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4728    parameters given by current_template_args, or reuses a
4729    previously existing one, if appropriate.  Returns the DECL, or an
4730    equivalent one, if it is replaced via a call to duplicate_decls.
4731
4732    If IS_FRIEND is true, DECL is a friend declaration.  */
4733
4734 tree
4735 push_template_decl_real (tree decl, bool is_friend)
4736 {
4737   tree tmpl;
4738   tree args;
4739   tree info;
4740   tree ctx;
4741   int primary;
4742   int is_partial;
4743   int new_template_p = 0;
4744   /* True if the template is a member template, in the sense of
4745      [temp.mem].  */
4746   bool member_template_p = false;
4747
4748   if (decl == error_mark_node || !current_template_parms)
4749     return error_mark_node;
4750
4751   /* See if this is a partial specialization.  */
4752   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4753                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4754                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4755
4756   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4757     is_friend = true;
4758
4759   if (is_friend)
4760     /* For a friend, we want the context of the friend function, not
4761        the type of which it is a friend.  */
4762     ctx = CP_DECL_CONTEXT (decl);
4763   else if (CP_DECL_CONTEXT (decl)
4764            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4765     /* In the case of a virtual function, we want the class in which
4766        it is defined.  */
4767     ctx = CP_DECL_CONTEXT (decl);
4768   else
4769     /* Otherwise, if we're currently defining some class, the DECL
4770        is assumed to be a member of the class.  */
4771     ctx = current_scope ();
4772
4773   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4774     ctx = NULL_TREE;
4775
4776   if (!DECL_CONTEXT (decl))
4777     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4778
4779   /* See if this is a primary template.  */
4780   if (is_friend && ctx)
4781     /* A friend template that specifies a class context, i.e.
4782          template <typename T> friend void A<T>::f();
4783        is not primary.  */
4784     primary = 0;
4785   else
4786     primary = template_parm_scope_p ();
4787
4788   if (primary)
4789     {
4790       if (DECL_CLASS_SCOPE_P (decl))
4791         member_template_p = true;
4792       if (TREE_CODE (decl) == TYPE_DECL
4793           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4794         {
4795           error ("template class without a name");
4796           return error_mark_node;
4797         }
4798       else if (TREE_CODE (decl) == FUNCTION_DECL)
4799         {
4800           if (DECL_DESTRUCTOR_P (decl))
4801             {
4802               /* [temp.mem]
4803
4804                  A destructor shall not be a member template.  */
4805               error ("destructor %qD declared as member template", decl);
4806               return error_mark_node;
4807             }
4808           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4809               && (!prototype_p (TREE_TYPE (decl))
4810                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4811                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4812                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4813                       == void_list_node)))
4814             {
4815               /* [basic.stc.dynamic.allocation]
4816
4817                  An allocation function can be a function
4818                  template. ... Template allocation functions shall
4819                  have two or more parameters.  */
4820               error ("invalid template declaration of %qD", decl);
4821               return error_mark_node;
4822             }
4823         }
4824       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4825                && CLASS_TYPE_P (TREE_TYPE (decl)))
4826         /* OK */;
4827       else
4828         {
4829           error ("template declaration of %q#D", decl);
4830           return error_mark_node;
4831         }
4832     }
4833
4834   /* Check to see that the rules regarding the use of default
4835      arguments are not being violated.  */
4836   check_default_tmpl_args (decl, current_template_parms,
4837                            primary, is_partial, /*is_friend_decl=*/0);
4838
4839   /* Ensure that there are no parameter packs in the type of this
4840      declaration that have not been expanded.  */
4841   if (TREE_CODE (decl) == FUNCTION_DECL)
4842     {
4843       /* Check each of the arguments individually to see if there are
4844          any bare parameter packs.  */
4845       tree type = TREE_TYPE (decl);
4846       tree arg = DECL_ARGUMENTS (decl);
4847       tree argtype = TYPE_ARG_TYPES (type);
4848
4849       while (arg && argtype)
4850         {
4851           if (!FUNCTION_PARAMETER_PACK_P (arg)
4852               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4853             {
4854             /* This is a PARM_DECL that contains unexpanded parameter
4855                packs. We have already complained about this in the
4856                check_for_bare_parameter_packs call, so just replace
4857                these types with ERROR_MARK_NODE.  */
4858               TREE_TYPE (arg) = error_mark_node;
4859               TREE_VALUE (argtype) = error_mark_node;
4860             }
4861
4862           arg = DECL_CHAIN (arg);
4863           argtype = TREE_CHAIN (argtype);
4864         }
4865
4866       /* Check for bare parameter packs in the return type and the
4867          exception specifiers.  */
4868       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4869         /* Errors were already issued, set return type to int
4870            as the frontend doesn't expect error_mark_node as
4871            the return type.  */
4872         TREE_TYPE (type) = integer_type_node;
4873       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4874         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4875     }
4876   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4877     {
4878       TREE_TYPE (decl) = error_mark_node;
4879       return error_mark_node;
4880     }
4881
4882   if (is_partial)
4883     return process_partial_specialization (decl);
4884
4885   args = current_template_args ();
4886
4887   if (!ctx
4888       || TREE_CODE (ctx) == FUNCTION_DECL
4889       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4890       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4891     {
4892       if (DECL_LANG_SPECIFIC (decl)
4893           && DECL_TEMPLATE_INFO (decl)
4894           && DECL_TI_TEMPLATE (decl))
4895         tmpl = DECL_TI_TEMPLATE (decl);
4896       /* If DECL is a TYPE_DECL for a class-template, then there won't
4897          be DECL_LANG_SPECIFIC.  The information equivalent to
4898          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4899       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4900                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4901                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4902         {
4903           /* Since a template declaration already existed for this
4904              class-type, we must be redeclaring it here.  Make sure
4905              that the redeclaration is valid.  */
4906           redeclare_class_template (TREE_TYPE (decl),
4907                                     current_template_parms);
4908           /* We don't need to create a new TEMPLATE_DECL; just use the
4909              one we already had.  */
4910           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4911         }
4912       else
4913         {
4914           tmpl = build_template_decl (decl, current_template_parms,
4915                                       member_template_p);
4916           new_template_p = 1;
4917
4918           if (DECL_LANG_SPECIFIC (decl)
4919               && DECL_TEMPLATE_SPECIALIZATION (decl))
4920             {
4921               /* A specialization of a member template of a template
4922                  class.  */
4923               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4924               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4925               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4926             }
4927         }
4928     }
4929   else
4930     {
4931       tree a, t, current, parms;
4932       int i;
4933       tree tinfo = get_template_info (decl);
4934
4935       if (!tinfo)
4936         {
4937           error ("template definition of non-template %q#D", decl);
4938           return error_mark_node;
4939         }
4940
4941       tmpl = TI_TEMPLATE (tinfo);
4942
4943       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4944           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4945           && DECL_TEMPLATE_SPECIALIZATION (decl)
4946           && DECL_MEMBER_TEMPLATE_P (tmpl))
4947         {
4948           tree new_tmpl;
4949
4950           /* The declaration is a specialization of a member
4951              template, declared outside the class.  Therefore, the
4952              innermost template arguments will be NULL, so we
4953              replace them with the arguments determined by the
4954              earlier call to check_explicit_specialization.  */
4955           args = DECL_TI_ARGS (decl);
4956
4957           new_tmpl
4958             = build_template_decl (decl, current_template_parms,
4959                                    member_template_p);
4960           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4961           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4962           DECL_TI_TEMPLATE (decl) = new_tmpl;
4963           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4964           DECL_TEMPLATE_INFO (new_tmpl)
4965             = build_template_info (tmpl, args);
4966
4967           register_specialization (new_tmpl,
4968                                    most_general_template (tmpl),
4969                                    args,
4970                                    is_friend, 0);
4971           return decl;
4972         }
4973
4974       /* Make sure the template headers we got make sense.  */
4975
4976       parms = DECL_TEMPLATE_PARMS (tmpl);
4977       i = TMPL_PARMS_DEPTH (parms);
4978       if (TMPL_ARGS_DEPTH (args) != i)
4979         {
4980           error ("expected %d levels of template parms for %q#D, got %d",
4981                  i, decl, TMPL_ARGS_DEPTH (args));
4982         }
4983       else
4984         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4985           {
4986             a = TMPL_ARGS_LEVEL (args, i);
4987             t = INNERMOST_TEMPLATE_PARMS (parms);
4988
4989             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4990               {
4991                 if (current == decl)
4992                   error ("got %d template parameters for %q#D",
4993                          TREE_VEC_LENGTH (a), decl);
4994                 else
4995                   error ("got %d template parameters for %q#T",
4996                          TREE_VEC_LENGTH (a), current);
4997                 error ("  but %d required", TREE_VEC_LENGTH (t));
4998                 return error_mark_node;
4999               }
5000
5001             if (current == decl)
5002               current = ctx;
5003             else if (current == NULL_TREE)
5004               /* Can happen in erroneous input.  */
5005               break;
5006             else
5007               current = (TYPE_P (current)
5008                          ? TYPE_CONTEXT (current)
5009                          : DECL_CONTEXT (current));
5010           }
5011
5012       /* Check that the parms are used in the appropriate qualifying scopes
5013          in the declarator.  */
5014       if (!comp_template_args
5015           (TI_ARGS (tinfo),
5016            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5017         {
5018           error ("\
5019 template arguments to %qD do not match original template %qD",
5020                  decl, DECL_TEMPLATE_RESULT (tmpl));
5021           if (!uses_template_parms (TI_ARGS (tinfo)))
5022             inform (input_location, "use template<> for an explicit specialization");
5023           /* Avoid crash in import_export_decl.  */
5024           DECL_INTERFACE_KNOWN (decl) = 1;
5025           return error_mark_node;
5026         }
5027     }
5028
5029   DECL_TEMPLATE_RESULT (tmpl) = decl;
5030   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5031
5032   /* Push template declarations for global functions and types.  Note
5033      that we do not try to push a global template friend declared in a
5034      template class; such a thing may well depend on the template
5035      parameters of the class.  */
5036   if (new_template_p && !ctx
5037       && !(is_friend && template_class_depth (current_class_type) > 0))
5038     {
5039       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5040       if (tmpl == error_mark_node)
5041         return error_mark_node;
5042
5043       /* Hide template friend classes that haven't been declared yet.  */
5044       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5045         {
5046           DECL_ANTICIPATED (tmpl) = 1;
5047           DECL_FRIEND_P (tmpl) = 1;
5048         }
5049     }
5050
5051   if (primary)
5052     {
5053       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5054       int i;
5055
5056       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5057       if (DECL_CONV_FN_P (tmpl))
5058         {
5059           int depth = TMPL_PARMS_DEPTH (parms);
5060
5061           /* It is a conversion operator. See if the type converted to
5062              depends on innermost template operands.  */
5063
5064           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5065                                          depth))
5066             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5067         }
5068
5069       /* Give template template parms a DECL_CONTEXT of the template
5070          for which they are a parameter.  */
5071       parms = INNERMOST_TEMPLATE_PARMS (parms);
5072       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5073         {
5074           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5075           if (TREE_CODE (parm) == TEMPLATE_DECL)
5076             DECL_CONTEXT (parm) = tmpl;
5077         }
5078     }
5079
5080   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5081      back to its most general template.  If TMPL is a specialization,
5082      ARGS may only have the innermost set of arguments.  Add the missing
5083      argument levels if necessary.  */
5084   if (DECL_TEMPLATE_INFO (tmpl))
5085     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5086
5087   info = build_template_info (tmpl, args);
5088
5089   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5090     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5091   else if (DECL_LANG_SPECIFIC (decl))
5092     DECL_TEMPLATE_INFO (decl) = info;
5093
5094   return DECL_TEMPLATE_RESULT (tmpl);
5095 }
5096
5097 tree
5098 push_template_decl (tree decl)
5099 {
5100   return push_template_decl_real (decl, false);
5101 }
5102
5103 /* Called when a class template TYPE is redeclared with the indicated
5104    template PARMS, e.g.:
5105
5106      template <class T> struct S;
5107      template <class T> struct S {};  */
5108
5109 bool
5110 redeclare_class_template (tree type, tree parms)
5111 {
5112   tree tmpl;
5113   tree tmpl_parms;
5114   int i;
5115
5116   if (!TYPE_TEMPLATE_INFO (type))
5117     {
5118       error ("%qT is not a template type", type);
5119       return false;
5120     }
5121
5122   tmpl = TYPE_TI_TEMPLATE (type);
5123   if (!PRIMARY_TEMPLATE_P (tmpl))
5124     /* The type is nested in some template class.  Nothing to worry
5125        about here; there are no new template parameters for the nested
5126        type.  */
5127     return true;
5128
5129   if (!parms)
5130     {
5131       error ("template specifiers not specified in declaration of %qD",
5132              tmpl);
5133       return false;
5134     }
5135
5136   parms = INNERMOST_TEMPLATE_PARMS (parms);
5137   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5138
5139   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5140     {
5141       error_n (input_location, TREE_VEC_LENGTH (parms),
5142                "redeclared with %d template parameter",
5143                "redeclared with %d template parameters",
5144                TREE_VEC_LENGTH (parms));
5145       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5146                 "previous declaration %q+D used %d template parameter",
5147                 "previous declaration %q+D used %d template parameters",
5148                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5149       return false;
5150     }
5151
5152   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5153     {
5154       tree tmpl_parm;
5155       tree parm;
5156       tree tmpl_default;
5157       tree parm_default;
5158
5159       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5160           || TREE_VEC_ELT (parms, i) == error_mark_node)
5161         continue;
5162
5163       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5164       if (tmpl_parm == error_mark_node)
5165         return false;
5166
5167       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5168       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5169       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5170
5171       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5172          TEMPLATE_DECL.  */
5173       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5174           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5175               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5176           || (TREE_CODE (tmpl_parm) != PARM_DECL
5177               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5178                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5179           || (TREE_CODE (tmpl_parm) == PARM_DECL
5180               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5181                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5182         {
5183           error ("template parameter %q+#D", tmpl_parm);
5184           error ("redeclared here as %q#D", parm);
5185           return false;
5186         }
5187
5188       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5189         {
5190           /* We have in [temp.param]:
5191
5192              A template-parameter may not be given default arguments
5193              by two different declarations in the same scope.  */
5194           error_at (input_location, "redefinition of default argument for %q#D", parm);
5195           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5196                   "original definition appeared here");
5197           return false;
5198         }
5199
5200       if (parm_default != NULL_TREE)
5201         /* Update the previous template parameters (which are the ones
5202            that will really count) with the new default value.  */
5203         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5204       else if (tmpl_default != NULL_TREE)
5205         /* Update the new parameters, too; they'll be used as the
5206            parameters for any members.  */
5207         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5208     }
5209
5210     return true;
5211 }
5212
5213 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5214    (possibly simplified) expression.  */
5215
5216 static tree
5217 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5218 {
5219   if (expr == NULL_TREE)
5220     return NULL_TREE;
5221
5222   /* If we're in a template, but EXPR isn't value dependent, simplify
5223      it.  We're supposed to treat:
5224
5225        template <typename T> void f(T[1 + 1]);
5226        template <typename T> void f(T[2]);
5227
5228      as two declarations of the same function, for example.  */
5229   if (processing_template_decl
5230       && !type_dependent_expression_p (expr)
5231       && potential_constant_expression (expr)
5232       && !value_dependent_expression_p (expr))
5233     {
5234       HOST_WIDE_INT saved_processing_template_decl;
5235
5236       saved_processing_template_decl = processing_template_decl;
5237       processing_template_decl = 0;
5238       expr = tsubst_copy_and_build (expr,
5239                                     /*args=*/NULL_TREE,
5240                                     complain,
5241                                     /*in_decl=*/NULL_TREE,
5242                                     /*function_p=*/false,
5243                                     /*integral_constant_expression_p=*/true);
5244       processing_template_decl = saved_processing_template_decl;
5245     }
5246   return expr;
5247 }
5248
5249 tree
5250 fold_non_dependent_expr (tree expr)
5251 {
5252   return fold_non_dependent_expr_sfinae (expr, tf_error);
5253 }
5254
5255 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5256    must be a function or a pointer-to-function type, as specified
5257    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5258    and check that the resulting function has external linkage.  */
5259
5260 static tree
5261 convert_nontype_argument_function (tree type, tree expr)
5262 {
5263   tree fns = expr;
5264   tree fn, fn_no_ptr;
5265
5266   fn = instantiate_type (type, fns, tf_none);
5267   if (fn == error_mark_node)
5268     return error_mark_node;
5269
5270   fn_no_ptr = fn;
5271   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5272     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5273   if (TREE_CODE (fn_no_ptr) == BASELINK)
5274     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5275  
5276   /* [temp.arg.nontype]/1
5277
5278      A template-argument for a non-type, non-template template-parameter
5279      shall be one of:
5280      [...]
5281      -- the address of an object or function with external linkage.  */
5282   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5283     {
5284       error ("%qE is not a valid template argument for type %qT "
5285              "because function %qD has not external linkage",
5286              expr, type, fn_no_ptr);
5287       return NULL_TREE;
5288     }
5289
5290   return fn;
5291 }
5292
5293 /* Subroutine of convert_nontype_argument.
5294    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5295    Emit an error otherwise.  */
5296
5297 static bool
5298 check_valid_ptrmem_cst_expr (tree type, tree expr,
5299                              tsubst_flags_t complain)
5300 {
5301   STRIP_NOPS (expr);
5302   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5303     return true;
5304   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5305     return true;
5306   if (complain & tf_error)
5307     {
5308       error ("%qE is not a valid template argument for type %qT",
5309              expr, type);
5310       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5311     }
5312   return false;
5313 }
5314
5315 /* Returns TRUE iff the address of OP is value-dependent.
5316
5317    14.6.2.4 [temp.dep.temp]:
5318    A non-integral non-type template-argument is dependent if its type is
5319    dependent or it has either of the following forms
5320      qualified-id
5321      & qualified-id
5322    and contains a nested-name-specifier which specifies a class-name that
5323    names a dependent type.
5324
5325    We generalize this to just say that the address of a member of a
5326    dependent class is value-dependent; the above doesn't cover the
5327    address of a static data member named with an unqualified-id.  */
5328
5329 static bool
5330 has_value_dependent_address (tree op)
5331 {
5332   /* We could use get_inner_reference here, but there's no need;
5333      this is only relevant for template non-type arguments, which
5334      can only be expressed as &id-expression.  */
5335   if (DECL_P (op))
5336     {
5337       tree ctx = CP_DECL_CONTEXT (op);
5338       if (TYPE_P (ctx) && dependent_type_p (ctx))
5339         return true;
5340     }
5341
5342   return false;
5343 }
5344
5345 /* The next set of functions are used for providing helpful explanatory
5346    diagnostics for failed overload resolution.  Their messages should be
5347    indented by two spaces for consistency with the messages in
5348    call.c  */
5349
5350 static int
5351 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5352 {
5353   return 0;
5354 }
5355
5356 static int
5357 unify_parameter_deduction_failure (bool explain_p, tree parm)
5358 {
5359   if (explain_p)
5360     inform (input_location,
5361             "  couldn't deduce template parameter %qD", parm);
5362   return 1;
5363 }
5364
5365 static int
5366 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5367 {
5368   return 1;
5369 }
5370
5371 static int
5372 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5373 {
5374   if (explain_p)
5375     inform (input_location,
5376             "  types %qT and %qT have incompatible cv-qualifiers",
5377             parm, arg);
5378   return 1;
5379 }
5380
5381 static int
5382 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5383 {
5384   if (explain_p)
5385     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5386   return 1;
5387 }
5388
5389 static int
5390 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5391 {
5392   if (explain_p)
5393     inform (input_location,
5394             "  template parameter %qD is not a parameter pack, but "
5395             "argument %qD is",
5396             parm, arg);
5397   return 1;
5398 }
5399
5400 static int
5401 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5402 {
5403   if (explain_p)
5404     inform (input_location,
5405             "  template argument %qE does not match "
5406             "pointer-to-member constant %qE",
5407             arg, parm);
5408   return 1;
5409 }
5410
5411 static int
5412 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5413 {
5414   if (explain_p)
5415     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5416   return 1;
5417 }
5418
5419 static int
5420 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5421 {
5422   if (explain_p)
5423     inform (input_location,
5424             "  inconsistent parameter pack deduction with %qT and %qT",
5425             old_arg, new_arg);
5426   return 1;
5427 }
5428
5429 static int
5430 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5431 {
5432   if (explain_p)
5433     inform (input_location,
5434             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5435             parm, first, second);
5436   return 1;
5437 }
5438
5439 static int
5440 unify_vla_arg (bool explain_p, tree arg)
5441 {
5442   if (explain_p)
5443     inform (input_location,
5444             "  variable-sized array type %qT is not "
5445             "a valid template argument",
5446             arg);
5447   return 1;
5448 }
5449
5450 static int
5451 unify_method_type_error (bool explain_p, tree arg)
5452 {
5453   if (explain_p)
5454     inform (input_location,
5455             "  member function type %qT is not a valid template argument",
5456             arg);
5457   return 1;
5458 }
5459
5460 static int
5461 unify_arity (bool explain_p, int have, int wanted)
5462 {
5463   if (explain_p)
5464     inform_n (input_location, wanted,
5465               "  candidate expects %d argument, %d provided",
5466               "  candidate expects %d arguments, %d provided",
5467               wanted, have);
5468   return 1;
5469 }
5470
5471 static int
5472 unify_too_many_arguments (bool explain_p, int have, int wanted)
5473 {
5474   return unify_arity (explain_p, have, wanted);
5475 }
5476
5477 static int
5478 unify_too_few_arguments (bool explain_p, int have, int wanted)
5479 {
5480   return unify_arity (explain_p, have, wanted);
5481 }
5482
5483 static int
5484 unify_arg_conversion (bool explain_p, tree to_type,
5485                       tree from_type, tree arg)
5486 {
5487   if (explain_p)
5488     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5489             arg, from_type, to_type);
5490   return 1;
5491 }
5492
5493 static int
5494 unify_no_common_base (bool explain_p, enum template_base_result r,
5495                       tree parm, tree arg)
5496 {
5497   if (explain_p)
5498     switch (r)
5499       {
5500       case tbr_ambiguous_baseclass:
5501         inform (input_location, "  %qT is an ambiguous base class of %qT",
5502                 arg, parm);
5503         break;
5504       default:
5505         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5506         break;
5507       }
5508   return 1;
5509 }
5510
5511 static int
5512 unify_inconsistent_template_template_parameters (bool explain_p)
5513 {
5514   if (explain_p)
5515     inform (input_location,
5516             "  template parameters of a template template argument are "
5517             "inconsistent with other deduced template arguments");
5518   return 1;
5519 }
5520
5521 static int
5522 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5523 {
5524   if (explain_p)
5525     inform (input_location,
5526             "  can't deduce a template for %qT from non-template type %qT",
5527             parm, arg);
5528   return 1;
5529 }
5530
5531 static int
5532 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5533 {
5534   if (explain_p)
5535     inform (input_location,
5536             "  template argument %qE does not match %qD", arg, parm);
5537   return 1;
5538 }
5539
5540 static int
5541 unify_overload_resolution_failure (bool explain_p, tree arg)
5542 {
5543   if (explain_p)
5544     inform (input_location,
5545             "  could not resolve address from overloaded function %qE",
5546             arg);
5547   return 1;
5548 }
5549
5550 /* Attempt to convert the non-type template parameter EXPR to the
5551    indicated TYPE.  If the conversion is successful, return the
5552    converted value.  If the conversion is unsuccessful, return
5553    NULL_TREE if we issued an error message, or error_mark_node if we
5554    did not.  We issue error messages for out-and-out bad template
5555    parameters, but not simply because the conversion failed, since we
5556    might be just trying to do argument deduction.  Both TYPE and EXPR
5557    must be non-dependent.
5558
5559    The conversion follows the special rules described in
5560    [temp.arg.nontype], and it is much more strict than an implicit
5561    conversion.
5562
5563    This function is called twice for each template argument (see
5564    lookup_template_class for a more accurate description of this
5565    problem). This means that we need to handle expressions which
5566    are not valid in a C++ source, but can be created from the
5567    first call (for instance, casts to perform conversions). These
5568    hacks can go away after we fix the double coercion problem.  */
5569
5570 static tree
5571 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5572 {
5573   tree expr_type;
5574
5575   /* Detect immediately string literals as invalid non-type argument.
5576      This special-case is not needed for correctness (we would easily
5577      catch this later), but only to provide better diagnostic for this
5578      common user mistake. As suggested by DR 100, we do not mention
5579      linkage issues in the diagnostic as this is not the point.  */
5580   /* FIXME we're making this OK.  */
5581   if (TREE_CODE (expr) == STRING_CST)
5582     {
5583       if (complain & tf_error)
5584         error ("%qE is not a valid template argument for type %qT "
5585                "because string literals can never be used in this context",
5586                expr, type);
5587       return NULL_TREE;
5588     }
5589
5590   /* Add the ADDR_EXPR now for the benefit of
5591      value_dependent_expression_p.  */
5592   if (TYPE_PTROBV_P (type)
5593       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5594     expr = decay_conversion (expr);
5595
5596   /* If we are in a template, EXPR may be non-dependent, but still
5597      have a syntactic, rather than semantic, form.  For example, EXPR
5598      might be a SCOPE_REF, rather than the VAR_DECL to which the
5599      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5600      so that access checking can be performed when the template is
5601      instantiated -- but here we need the resolved form so that we can
5602      convert the argument.  */
5603   if (TYPE_REF_OBJ_P (type)
5604       && has_value_dependent_address (expr))
5605     /* If we want the address and it's value-dependent, don't fold.  */;
5606   else if (!type_unknown_p (expr))
5607     expr = fold_non_dependent_expr_sfinae (expr, complain);
5608   if (error_operand_p (expr))
5609     return error_mark_node;
5610   expr_type = TREE_TYPE (expr);
5611   if (TREE_CODE (type) == REFERENCE_TYPE)
5612     expr = mark_lvalue_use (expr);
5613   else
5614     expr = mark_rvalue_use (expr);
5615
5616   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5617      to a non-type argument of "nullptr".  */
5618   if (expr == nullptr_node
5619       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5620     expr = convert (type, expr);
5621
5622   /* In C++11, non-type template arguments can be arbitrary constant
5623      expressions.  But don't fold a PTRMEM_CST to a CONSTRUCTOR yet.  */
5624   if (cxx_dialect >= cxx0x && TREE_CODE (expr) != PTRMEM_CST)
5625     expr = maybe_constant_value (expr);
5626
5627   /* HACK: Due to double coercion, we can get a
5628      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5629      which is the tree that we built on the first call (see
5630      below when coercing to reference to object or to reference to
5631      function). We just strip everything and get to the arg.
5632      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5633      for examples.  */
5634   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5635     {
5636       tree probe_type, probe = expr;
5637       if (REFERENCE_REF_P (probe))
5638         probe = TREE_OPERAND (probe, 0);
5639       probe_type = TREE_TYPE (probe);
5640       if (TREE_CODE (probe) == NOP_EXPR)
5641         {
5642           /* ??? Maybe we could use convert_from_reference here, but we
5643              would need to relax its constraints because the NOP_EXPR
5644              could actually change the type to something more cv-qualified,
5645              and this is not folded by convert_from_reference.  */
5646           tree addr = TREE_OPERAND (probe, 0);
5647           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5648           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5649           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5650           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5651                       (TREE_TYPE (probe_type),
5652                        TREE_TYPE (TREE_TYPE (addr))));
5653
5654           expr = TREE_OPERAND (addr, 0);
5655           expr_type = TREE_TYPE (expr);
5656         }
5657     }
5658
5659   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5660      parameter is a pointer to object, through decay and
5661      qualification conversion. Let's strip everything.  */
5662   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5663     {
5664       STRIP_NOPS (expr);
5665       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5666       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5667       /* Skip the ADDR_EXPR only if it is part of the decay for
5668          an array. Otherwise, it is part of the original argument
5669          in the source code.  */
5670       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5671         expr = TREE_OPERAND (expr, 0);
5672       expr_type = TREE_TYPE (expr);
5673     }
5674
5675   /* [temp.arg.nontype]/5, bullet 1
5676
5677      For a non-type template-parameter of integral or enumeration type,
5678      integral promotions (_conv.prom_) and integral conversions
5679      (_conv.integral_) are applied.  */
5680   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5681     {
5682       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5683       t = maybe_constant_value (t);
5684       if (t != error_mark_node)
5685         expr = t;
5686
5687       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5688         return error_mark_node;
5689
5690       /* Notice that there are constant expressions like '4 % 0' which
5691          do not fold into integer constants.  */
5692       if (TREE_CODE (expr) != INTEGER_CST)
5693         {
5694           if (complain & tf_error)
5695             {
5696               int errs = errorcount, warns = warningcount;
5697               expr = cxx_constant_value (expr);
5698               if (errorcount > errs || warningcount > warns)
5699                 inform (EXPR_LOC_OR_HERE (expr),
5700                         "in template argument for type %qT ", type);
5701               if (expr == error_mark_node)
5702                 return NULL_TREE;
5703               /* else cxx_constant_value complained but gave us
5704                  a real constant, so go ahead.  */
5705               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5706             }
5707           else
5708             return NULL_TREE;
5709         }
5710     }
5711   /* [temp.arg.nontype]/5, bullet 2
5712
5713      For a non-type template-parameter of type pointer to object,
5714      qualification conversions (_conv.qual_) and the array-to-pointer
5715      conversion (_conv.array_) are applied.  */
5716   else if (TYPE_PTROBV_P (type))
5717     {
5718       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5719
5720          A template-argument for a non-type, non-template template-parameter
5721          shall be one of: [...]
5722
5723          -- the name of a non-type template-parameter;
5724          -- the address of an object or function with external linkage, [...]
5725             expressed as "& id-expression" where the & is optional if the name
5726             refers to a function or array, or if the corresponding
5727             template-parameter is a reference.
5728
5729         Here, we do not care about functions, as they are invalid anyway
5730         for a parameter of type pointer-to-object.  */
5731
5732       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5733         /* Non-type template parameters are OK.  */
5734         ;
5735       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5736         /* Null pointer values are OK in C++11.  */;
5737       else if (TREE_CODE (expr) != ADDR_EXPR
5738                && TREE_CODE (expr_type) != ARRAY_TYPE)
5739         {
5740           if (TREE_CODE (expr) == VAR_DECL)
5741             {
5742               error ("%qD is not a valid template argument "
5743                      "because %qD is a variable, not the address of "
5744                      "a variable",
5745                      expr, expr);
5746               return NULL_TREE;
5747             }
5748           /* Other values, like integer constants, might be valid
5749              non-type arguments of some other type.  */
5750           return error_mark_node;
5751         }
5752       else
5753         {
5754           tree decl;
5755
5756           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5757                   ? TREE_OPERAND (expr, 0) : expr);
5758           if (TREE_CODE (decl) != VAR_DECL)
5759             {
5760               error ("%qE is not a valid template argument of type %qT "
5761                      "because %qE is not a variable",
5762                      expr, type, decl);
5763               return NULL_TREE;
5764             }
5765           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5766             {
5767               error ("%qE is not a valid template argument of type %qT "
5768                      "because %qD does not have external linkage",
5769                      expr, type, decl);
5770               return NULL_TREE;
5771             }
5772         }
5773
5774       expr = decay_conversion (expr);
5775       if (expr == error_mark_node)
5776         return error_mark_node;
5777
5778       expr = perform_qualification_conversions (type, expr);
5779       if (expr == error_mark_node)
5780         return error_mark_node;
5781     }
5782   /* [temp.arg.nontype]/5, bullet 3
5783
5784      For a non-type template-parameter of type reference to object, no
5785      conversions apply. The type referred to by the reference may be more
5786      cv-qualified than the (otherwise identical) type of the
5787      template-argument. The template-parameter is bound directly to the
5788      template-argument, which must be an lvalue.  */
5789   else if (TYPE_REF_OBJ_P (type))
5790     {
5791       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5792                                                       expr_type))
5793         return error_mark_node;
5794
5795       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5796         {
5797           error ("%qE is not a valid template argument for type %qT "
5798                  "because of conflicts in cv-qualification", expr, type);
5799           return NULL_TREE;
5800         }
5801
5802       if (!real_lvalue_p (expr))
5803         {
5804           error ("%qE is not a valid template argument for type %qT "
5805                  "because it is not an lvalue", expr, type);
5806           return NULL_TREE;
5807         }
5808
5809       /* [temp.arg.nontype]/1
5810
5811          A template-argument for a non-type, non-template template-parameter
5812          shall be one of: [...]
5813
5814          -- the address of an object or function with external linkage.  */
5815       if (TREE_CODE (expr) == INDIRECT_REF
5816           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5817         {
5818           expr = TREE_OPERAND (expr, 0);
5819           if (DECL_P (expr))
5820             {
5821               error ("%q#D is not a valid template argument for type %qT "
5822                      "because a reference variable does not have a constant "
5823                      "address", expr, type);
5824               return NULL_TREE;
5825             }
5826         }
5827
5828       if (!DECL_P (expr))
5829         {
5830           error ("%qE is not a valid template argument for type %qT "
5831                  "because it is not an object with external linkage",
5832                  expr, type);
5833           return NULL_TREE;
5834         }
5835
5836       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5837         {
5838           error ("%qE is not a valid template argument for type %qT "
5839                  "because object %qD has not external linkage",
5840                  expr, type, expr);
5841           return NULL_TREE;
5842         }
5843
5844       expr = build_nop (type, build_address (expr));
5845     }
5846   /* [temp.arg.nontype]/5, bullet 4
5847
5848      For a non-type template-parameter of type pointer to function, only
5849      the function-to-pointer conversion (_conv.func_) is applied. If the
5850      template-argument represents a set of overloaded functions (or a
5851      pointer to such), the matching function is selected from the set
5852      (_over.over_).  */
5853   else if (TYPE_PTRFN_P (type))
5854     {
5855       /* If the argument is a template-id, we might not have enough
5856          context information to decay the pointer.  */
5857       if (!type_unknown_p (expr_type))
5858         {
5859           expr = decay_conversion (expr);
5860           if (expr == error_mark_node)
5861             return error_mark_node;
5862         }
5863
5864       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5865         /* Null pointer values are OK in C++11.  */
5866         return perform_qualification_conversions (type, expr);
5867
5868       expr = convert_nontype_argument_function (type, expr);
5869       if (!expr || expr == error_mark_node)
5870         return expr;
5871
5872       if (TREE_CODE (expr) != ADDR_EXPR)
5873         {
5874           error ("%qE is not a valid template argument for type %qT", expr, type);
5875           error ("it must be the address of a function with external linkage");
5876           return NULL_TREE;
5877         }
5878     }
5879   /* [temp.arg.nontype]/5, bullet 5
5880
5881      For a non-type template-parameter of type reference to function, no
5882      conversions apply. If the template-argument represents a set of
5883      overloaded functions, the matching function is selected from the set
5884      (_over.over_).  */
5885   else if (TYPE_REFFN_P (type))
5886     {
5887       if (TREE_CODE (expr) == ADDR_EXPR)
5888         {
5889           error ("%qE is not a valid template argument for type %qT "
5890                  "because it is a pointer", expr, type);
5891           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5892           return NULL_TREE;
5893         }
5894
5895       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5896       if (!expr || expr == error_mark_node)
5897         return expr;
5898
5899       expr = build_nop (type, build_address (expr));
5900     }
5901   /* [temp.arg.nontype]/5, bullet 6
5902
5903      For a non-type template-parameter of type pointer to member function,
5904      no conversions apply. If the template-argument represents a set of
5905      overloaded member functions, the matching member function is selected
5906      from the set (_over.over_).  */
5907   else if (TYPE_PTRMEMFUNC_P (type))
5908     {
5909       expr = instantiate_type (type, expr, tf_none);
5910       if (expr == error_mark_node)
5911         return error_mark_node;
5912
5913       /* [temp.arg.nontype] bullet 1 says the pointer to member
5914          expression must be a pointer-to-member constant.  */
5915       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5916         return error_mark_node;
5917
5918       /* There is no way to disable standard conversions in
5919          resolve_address_of_overloaded_function (called by
5920          instantiate_type). It is possible that the call succeeded by
5921          converting &B::I to &D::I (where B is a base of D), so we need
5922          to reject this conversion here.
5923
5924          Actually, even if there was a way to disable standard conversions,
5925          it would still be better to reject them here so that we can
5926          provide a superior diagnostic.  */
5927       if (!same_type_p (TREE_TYPE (expr), type))
5928         {
5929           error ("%qE is not a valid template argument for type %qT "
5930                  "because it is of type %qT", expr, type,
5931                  TREE_TYPE (expr));
5932           /* If we are just one standard conversion off, explain.  */
5933           if (can_convert (type, TREE_TYPE (expr)))
5934             inform (input_location,
5935                     "standard conversions are not allowed in this context");
5936           return NULL_TREE;
5937         }
5938     }
5939   /* [temp.arg.nontype]/5, bullet 7
5940
5941      For a non-type template-parameter of type pointer to data member,
5942      qualification conversions (_conv.qual_) are applied.  */
5943   else if (TYPE_PTRMEM_P (type))
5944     {
5945       /* [temp.arg.nontype] bullet 1 says the pointer to member
5946          expression must be a pointer-to-member constant.  */
5947       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5948         return error_mark_node;
5949
5950       expr = perform_qualification_conversions (type, expr);
5951       if (expr == error_mark_node)
5952         return expr;
5953     }
5954   else if (NULLPTR_TYPE_P (type))
5955     {
5956       if (expr != nullptr_node)
5957         {
5958           error ("%qE is not a valid template argument for type %qT "
5959                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
5960           return NULL_TREE;
5961         }
5962       return expr;
5963     }
5964   /* A template non-type parameter must be one of the above.  */
5965   else
5966     gcc_unreachable ();
5967
5968   /* Sanity check: did we actually convert the argument to the
5969      right type?  */
5970   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5971               (type, TREE_TYPE (expr)));
5972   return expr;
5973 }
5974
5975 /* Subroutine of coerce_template_template_parms, which returns 1 if
5976    PARM_PARM and ARG_PARM match using the rule for the template
5977    parameters of template template parameters. Both PARM and ARG are
5978    template parameters; the rest of the arguments are the same as for
5979    coerce_template_template_parms.
5980  */
5981 static int
5982 coerce_template_template_parm (tree parm,
5983                               tree arg,
5984                               tsubst_flags_t complain,
5985                               tree in_decl,
5986                               tree outer_args)
5987 {
5988   if (arg == NULL_TREE || arg == error_mark_node
5989       || parm == NULL_TREE || parm == error_mark_node)
5990     return 0;
5991   
5992   if (TREE_CODE (arg) != TREE_CODE (parm))
5993     return 0;
5994   
5995   switch (TREE_CODE (parm))
5996     {
5997     case TEMPLATE_DECL:
5998       /* We encounter instantiations of templates like
5999          template <template <template <class> class> class TT>
6000          class C;  */
6001       {
6002         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6003         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6004         
6005         if (!coerce_template_template_parms
6006             (parmparm, argparm, complain, in_decl, outer_args))
6007           return 0;
6008       }
6009       /* Fall through.  */
6010       
6011     case TYPE_DECL:
6012       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6013           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6014         /* Argument is a parameter pack but parameter is not.  */
6015         return 0;
6016       break;
6017       
6018     case PARM_DECL:
6019       /* The tsubst call is used to handle cases such as
6020          
6021            template <int> class C {};
6022            template <class T, template <T> class TT> class D {};
6023            D<int, C> d;
6024
6025          i.e. the parameter list of TT depends on earlier parameters.  */
6026       if (!uses_template_parms (TREE_TYPE (arg))
6027           && !same_type_p
6028                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6029                  TREE_TYPE (arg)))
6030         return 0;
6031       
6032       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6033           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6034         /* Argument is a parameter pack but parameter is not.  */
6035         return 0;
6036       
6037       break;
6038
6039     default:
6040       gcc_unreachable ();
6041     }
6042
6043   return 1;
6044 }
6045
6046
6047 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6048    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6049    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6050    or PARM_DECL.
6051
6052    Consider the example:
6053      template <class T> class A;
6054      template<template <class U> class TT> class B;
6055
6056    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6057    the parameters to A, and OUTER_ARGS contains A.  */
6058
6059 static int
6060 coerce_template_template_parms (tree parm_parms,
6061                                 tree arg_parms,
6062                                 tsubst_flags_t complain,
6063                                 tree in_decl,
6064                                 tree outer_args)
6065 {
6066   int nparms, nargs, i;
6067   tree parm, arg;
6068   int variadic_p = 0;
6069
6070   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6071   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6072
6073   nparms = TREE_VEC_LENGTH (parm_parms);
6074   nargs = TREE_VEC_LENGTH (arg_parms);
6075
6076   /* Determine whether we have a parameter pack at the end of the
6077      template template parameter's template parameter list.  */
6078   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6079     {
6080       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6081       
6082       if (parm == error_mark_node)
6083         return 0;
6084
6085       switch (TREE_CODE (parm))
6086         {
6087         case TEMPLATE_DECL:
6088         case TYPE_DECL:
6089           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6090             variadic_p = 1;
6091           break;
6092           
6093         case PARM_DECL:
6094           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6095             variadic_p = 1;
6096           break;
6097           
6098         default:
6099           gcc_unreachable ();
6100         }
6101     }
6102  
6103   if (nargs != nparms
6104       && !(variadic_p && nargs >= nparms - 1))
6105     return 0;
6106
6107   /* Check all of the template parameters except the parameter pack at
6108      the end (if any).  */
6109   for (i = 0; i < nparms - variadic_p; ++i)
6110     {
6111       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6112           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6113         continue;
6114
6115       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6116       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6117
6118       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6119                                           outer_args))
6120         return 0;
6121
6122     }
6123
6124   if (variadic_p)
6125     {
6126       /* Check each of the template parameters in the template
6127          argument against the template parameter pack at the end of
6128          the template template parameter.  */
6129       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6130         return 0;
6131
6132       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6133
6134       for (; i < nargs; ++i)
6135         {
6136           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6137             continue;
6138  
6139           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6140  
6141           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6142                                               outer_args))
6143             return 0;
6144         }
6145     }
6146
6147   return 1;
6148 }
6149
6150 /* Verifies that the deduced template arguments (in TARGS) for the
6151    template template parameters (in TPARMS) represent valid bindings,
6152    by comparing the template parameter list of each template argument
6153    to the template parameter list of its corresponding template
6154    template parameter, in accordance with DR150. This
6155    routine can only be called after all template arguments have been
6156    deduced. It will return TRUE if all of the template template
6157    parameter bindings are okay, FALSE otherwise.  */
6158 bool 
6159 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6160 {
6161   int i, ntparms = TREE_VEC_LENGTH (tparms);
6162   bool ret = true;
6163
6164   /* We're dealing with template parms in this process.  */
6165   ++processing_template_decl;
6166
6167   targs = INNERMOST_TEMPLATE_ARGS (targs);
6168
6169   for (i = 0; i < ntparms; ++i)
6170     {
6171       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6172       tree targ = TREE_VEC_ELT (targs, i);
6173
6174       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6175         {
6176           tree packed_args = NULL_TREE;
6177           int idx, len = 1;
6178
6179           if (ARGUMENT_PACK_P (targ))
6180             {
6181               /* Look inside the argument pack.  */
6182               packed_args = ARGUMENT_PACK_ARGS (targ);
6183               len = TREE_VEC_LENGTH (packed_args);
6184             }
6185
6186           for (idx = 0; idx < len; ++idx)
6187             {
6188               tree targ_parms = NULL_TREE;
6189
6190               if (packed_args)
6191                 /* Extract the next argument from the argument
6192                    pack.  */
6193                 targ = TREE_VEC_ELT (packed_args, idx);
6194
6195               if (PACK_EXPANSION_P (targ))
6196                 /* Look at the pattern of the pack expansion.  */
6197                 targ = PACK_EXPANSION_PATTERN (targ);
6198
6199               /* Extract the template parameters from the template
6200                  argument.  */
6201               if (TREE_CODE (targ) == TEMPLATE_DECL)
6202                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6203               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6204                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6205
6206               /* Verify that we can coerce the template template
6207                  parameters from the template argument to the template
6208                  parameter.  This requires an exact match.  */
6209               if (targ_parms
6210                   && !coerce_template_template_parms
6211                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6212                         targ_parms,
6213                         tf_none,
6214                         tparm,
6215                         targs))
6216                 {
6217                   ret = false;
6218                   goto out;
6219                 }
6220             }
6221         }
6222     }
6223
6224  out:
6225
6226   --processing_template_decl;
6227   return ret;
6228 }
6229
6230 /* Since type attributes aren't mangled, we need to strip them from
6231    template type arguments.  */
6232
6233 static tree
6234 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6235 {
6236   tree mv;
6237   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6238     return arg;
6239   mv = TYPE_MAIN_VARIANT (arg);
6240   arg = strip_typedefs (arg);
6241   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6242       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6243     {
6244       if (complain & tf_warning)
6245         warning (0, "ignoring attributes on template argument %qT", arg);
6246       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6247       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6248     }
6249   return arg;
6250 }
6251
6252 /* Convert the indicated template ARG as necessary to match the
6253    indicated template PARM.  Returns the converted ARG, or
6254    error_mark_node if the conversion was unsuccessful.  Error and
6255    warning messages are issued under control of COMPLAIN.  This
6256    conversion is for the Ith parameter in the parameter list.  ARGS is
6257    the full set of template arguments deduced so far.  */
6258
6259 static tree
6260 convert_template_argument (tree parm,
6261                            tree arg,
6262                            tree args,
6263                            tsubst_flags_t complain,
6264                            int i,
6265                            tree in_decl)
6266 {
6267   tree orig_arg;
6268   tree val;
6269   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6270
6271   if (TREE_CODE (arg) == TREE_LIST
6272       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6273     {
6274       /* The template argument was the name of some
6275          member function.  That's usually
6276          invalid, but static members are OK.  In any
6277          case, grab the underlying fields/functions
6278          and issue an error later if required.  */
6279       orig_arg = TREE_VALUE (arg);
6280       TREE_TYPE (arg) = unknown_type_node;
6281     }
6282
6283   orig_arg = arg;
6284
6285   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6286   requires_type = (TREE_CODE (parm) == TYPE_DECL
6287                    || requires_tmpl_type);
6288
6289   /* When determining whether an argument pack expansion is a template,
6290      look at the pattern.  */
6291   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6292     arg = PACK_EXPANSION_PATTERN (arg);
6293
6294   /* Deal with an injected-class-name used as a template template arg.  */
6295   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6296     {
6297       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6298       if (TREE_CODE (t) == TEMPLATE_DECL)
6299         {
6300           if (cxx_dialect >= cxx0x)
6301             /* OK under DR 1004.  */;
6302           else if (complain & tf_warning_or_error)
6303             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6304                      " used as template template argument", TYPE_NAME (arg));
6305           else if (flag_pedantic_errors)
6306             t = arg;
6307
6308           arg = t;
6309         }
6310     }
6311
6312   is_tmpl_type = 
6313     ((TREE_CODE (arg) == TEMPLATE_DECL
6314       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6315      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6316      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6317
6318   if (is_tmpl_type
6319       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6320           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6321     arg = TYPE_STUB_DECL (arg);
6322
6323   is_type = TYPE_P (arg) || is_tmpl_type;
6324
6325   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6326       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6327     {
6328       permerror (input_location, "to refer to a type member of a template parameter, "
6329                  "use %<typename %E%>", orig_arg);
6330
6331       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6332                                      TREE_OPERAND (arg, 1),
6333                                      typename_type,
6334                                      complain & tf_error);
6335       arg = orig_arg;
6336       is_type = 1;
6337     }
6338   if (is_type != requires_type)
6339     {
6340       if (in_decl)
6341         {
6342           if (complain & tf_error)
6343             {
6344               error ("type/value mismatch at argument %d in template "
6345                      "parameter list for %qD",
6346                      i + 1, in_decl);
6347               if (is_type)
6348                 error ("  expected a constant of type %qT, got %qT",
6349                        TREE_TYPE (parm),
6350                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6351               else if (requires_tmpl_type)
6352                 error ("  expected a class template, got %qE", orig_arg);
6353               else
6354                 error ("  expected a type, got %qE", orig_arg);
6355             }
6356         }
6357       return error_mark_node;
6358     }
6359   if (is_tmpl_type ^ requires_tmpl_type)
6360     {
6361       if (in_decl && (complain & tf_error))
6362         {
6363           error ("type/value mismatch at argument %d in template "
6364                  "parameter list for %qD",
6365                  i + 1, in_decl);
6366           if (is_tmpl_type)
6367             error ("  expected a type, got %qT", DECL_NAME (arg));
6368           else
6369             error ("  expected a class template, got %qT", orig_arg);
6370         }
6371       return error_mark_node;
6372     }
6373
6374   if (is_type)
6375     {
6376       if (requires_tmpl_type)
6377         {
6378           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6379             /* The number of argument required is not known yet.
6380                Just accept it for now.  */
6381             val = TREE_TYPE (arg);
6382           else
6383             {
6384               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6385               tree argparm;
6386
6387               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6388
6389               if (coerce_template_template_parms (parmparm, argparm,
6390                                                   complain, in_decl,
6391                                                   args))
6392                 {
6393                   val = arg;
6394
6395                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6396                      TEMPLATE_DECL.  */
6397                   if (val != error_mark_node)
6398                     {
6399                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6400                         val = TREE_TYPE (val);
6401                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6402                         val = make_pack_expansion (val);
6403                     }
6404                 }
6405               else
6406                 {
6407                   if (in_decl && (complain & tf_error))
6408                     {
6409                       error ("type/value mismatch at argument %d in "
6410                              "template parameter list for %qD",
6411                              i + 1, in_decl);
6412                       error ("  expected a template of type %qD, got %qT",
6413                              parm, orig_arg);
6414                     }
6415
6416                   val = error_mark_node;
6417                 }
6418             }
6419         }
6420       else
6421         val = orig_arg;
6422       /* We only form one instance of each template specialization.
6423          Therefore, if we use a non-canonical variant (i.e., a
6424          typedef), any future messages referring to the type will use
6425          the typedef, which is confusing if those future uses do not
6426          themselves also use the typedef.  */
6427       if (TYPE_P (val))
6428         val = canonicalize_type_argument (val, complain);
6429     }
6430   else
6431     {
6432       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6433
6434       if (invalid_nontype_parm_type_p (t, complain))
6435         return error_mark_node;
6436
6437       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6438         {
6439           if (same_type_p (t, TREE_TYPE (orig_arg)))
6440             val = orig_arg;
6441           else
6442             {
6443               /* Not sure if this is reachable, but it doesn't hurt
6444                  to be robust.  */
6445               error ("type mismatch in nontype parameter pack");
6446               val = error_mark_node;
6447             }
6448         }
6449       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6450         /* We used to call digest_init here.  However, digest_init
6451            will report errors, which we don't want when complain
6452            is zero.  More importantly, digest_init will try too
6453            hard to convert things: for example, `0' should not be
6454            converted to pointer type at this point according to
6455            the standard.  Accepting this is not merely an
6456            extension, since deciding whether or not these
6457            conversions can occur is part of determining which
6458            function template to call, or whether a given explicit
6459            argument specification is valid.  */
6460         val = convert_nontype_argument (t, orig_arg, complain);
6461       else
6462         val = orig_arg;
6463
6464       if (val == NULL_TREE)
6465         val = error_mark_node;
6466       else if (val == error_mark_node && (complain & tf_error))
6467         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6468
6469       if (TREE_CODE (val) == SCOPE_REF)
6470         {
6471           /* Strip typedefs from the SCOPE_REF.  */
6472           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6473           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6474                                                    complain);
6475           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6476                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6477         }
6478     }
6479
6480   return val;
6481 }
6482
6483 /* Coerces the remaining template arguments in INNER_ARGS (from
6484    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6485    Returns the coerced argument pack. PARM_IDX is the position of this
6486    parameter in the template parameter list. ARGS is the original
6487    template argument list.  */
6488 static tree
6489 coerce_template_parameter_pack (tree parms,
6490                                 int parm_idx,
6491                                 tree args,
6492                                 tree inner_args,
6493                                 int arg_idx,
6494                                 tree new_args,
6495                                 int* lost,
6496                                 tree in_decl,
6497                                 tsubst_flags_t complain)
6498 {
6499   tree parm = TREE_VEC_ELT (parms, parm_idx);
6500   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6501   tree packed_args;
6502   tree argument_pack;
6503   tree packed_types = NULL_TREE;
6504
6505   if (arg_idx > nargs)
6506     arg_idx = nargs;
6507
6508   packed_args = make_tree_vec (nargs - arg_idx);
6509
6510   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6511       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6512     {
6513       /* When the template parameter is a non-type template
6514          parameter pack whose type uses parameter packs, we need
6515          to look at each of the template arguments
6516          separately. Build a vector of the types for these
6517          non-type template parameters in PACKED_TYPES.  */
6518       tree expansion 
6519         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6520       packed_types = tsubst_pack_expansion (expansion, args,
6521                                             complain, in_decl);
6522
6523       if (packed_types == error_mark_node)
6524         return error_mark_node;
6525
6526       /* Check that we have the right number of arguments.  */
6527       if (arg_idx < nargs
6528           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6529           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6530         {
6531           int needed_parms 
6532             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6533           error ("wrong number of template arguments (%d, should be %d)",
6534                  nargs, needed_parms);
6535           return error_mark_node;
6536         }
6537
6538       /* If we aren't able to check the actual arguments now
6539          (because they haven't been expanded yet), we can at least
6540          verify that all of the types used for the non-type
6541          template parameter pack are, in fact, valid for non-type
6542          template parameters.  */
6543       if (arg_idx < nargs 
6544           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6545         {
6546           int j, len = TREE_VEC_LENGTH (packed_types);
6547           for (j = 0; j < len; ++j)
6548             {
6549               tree t = TREE_VEC_ELT (packed_types, j);
6550               if (invalid_nontype_parm_type_p (t, complain))
6551                 return error_mark_node;
6552             }
6553         }
6554     }
6555
6556   /* Convert the remaining arguments, which will be a part of the
6557      parameter pack "parm".  */
6558   for (; arg_idx < nargs; ++arg_idx)
6559     {
6560       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6561       tree actual_parm = TREE_VALUE (parm);
6562
6563       if (packed_types && !PACK_EXPANSION_P (arg))
6564         {
6565           /* When we have a vector of types (corresponding to the
6566              non-type template parameter pack that uses parameter
6567              packs in its type, as mention above), and the
6568              argument is not an expansion (which expands to a
6569              currently unknown number of arguments), clone the
6570              parm and give it the next type in PACKED_TYPES.  */
6571           actual_parm = copy_node (actual_parm);
6572           TREE_TYPE (actual_parm) = 
6573             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6574         }
6575
6576       if (arg != error_mark_node)
6577         arg = convert_template_argument (actual_parm, 
6578                                          arg, new_args, complain, parm_idx,
6579                                          in_decl);
6580       if (arg == error_mark_node)
6581         (*lost)++;
6582       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6583     }
6584
6585   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6586       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6587     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6588   else
6589     {
6590       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6591       TREE_TYPE (argument_pack) 
6592         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6593       TREE_CONSTANT (argument_pack) = 1;
6594     }
6595
6596   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6597 #ifdef ENABLE_CHECKING
6598   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6599                                        TREE_VEC_LENGTH (packed_args));
6600 #endif
6601   return argument_pack;
6602 }
6603
6604 /* Convert all template arguments to their appropriate types, and
6605    return a vector containing the innermost resulting template
6606    arguments.  If any error occurs, return error_mark_node. Error and
6607    warning messages are issued under control of COMPLAIN.
6608
6609    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6610    for arguments not specified in ARGS.  Otherwise, if
6611    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6612    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6613    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6614    ARGS.  */
6615
6616 static tree
6617 coerce_template_parms (tree parms,
6618                        tree args,
6619                        tree in_decl,
6620                        tsubst_flags_t complain,
6621                        bool require_all_args,
6622                        bool use_default_args)
6623 {
6624   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6625   tree inner_args;
6626   tree new_args;
6627   tree new_inner_args;
6628   int saved_unevaluated_operand;
6629   int saved_inhibit_evaluation_warnings;
6630
6631   /* When used as a boolean value, indicates whether this is a
6632      variadic template parameter list. Since it's an int, we can also
6633      subtract it from nparms to get the number of non-variadic
6634      parameters.  */
6635   int variadic_p = 0;
6636   int post_variadic_parms = 0;
6637
6638   if (args == error_mark_node)
6639     return error_mark_node;
6640
6641   nparms = TREE_VEC_LENGTH (parms);
6642
6643   /* Determine if there are any parameter packs.  */
6644   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6645     {
6646       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6647       if (variadic_p)
6648         ++post_variadic_parms;
6649       if (template_parameter_pack_p (tparm))
6650         ++variadic_p;
6651     }
6652
6653   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6654   /* If there are no parameters that follow a parameter pack, we need to
6655      expand any argument packs so that we can deduce a parameter pack from
6656      some non-packed args followed by an argument pack, as in variadic85.C.
6657      If there are such parameters, we need to leave argument packs intact
6658      so the arguments are assigned properly.  This can happen when dealing
6659      with a nested class inside a partial specialization of a class
6660      template, as in variadic92.C, or when deducing a template parameter pack
6661      from a sub-declarator, as in variadic114.C.  */
6662   if (!post_variadic_parms)
6663     inner_args = expand_template_argument_pack (inner_args);
6664
6665   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6666   if ((nargs > nparms && !variadic_p)
6667       || (nargs < nparms - variadic_p
6668           && require_all_args
6669           && (!use_default_args
6670               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6671                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6672     {
6673       if (complain & tf_error)
6674         {
6675           if (variadic_p)
6676             {
6677               nparms -= variadic_p;
6678               error ("wrong number of template arguments "
6679                      "(%d, should be %d or more)", nargs, nparms);
6680             }
6681           else
6682              error ("wrong number of template arguments "
6683                     "(%d, should be %d)", nargs, nparms);
6684
6685           if (in_decl)
6686             error ("provided for %q+D", in_decl);
6687         }
6688
6689       return error_mark_node;
6690     }
6691
6692   /* We need to evaluate the template arguments, even though this
6693      template-id may be nested within a "sizeof".  */
6694   saved_unevaluated_operand = cp_unevaluated_operand;
6695   cp_unevaluated_operand = 0;
6696   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6697   c_inhibit_evaluation_warnings = 0;
6698   new_inner_args = make_tree_vec (nparms);
6699   new_args = add_outermost_template_args (args, new_inner_args);
6700   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6701     {
6702       tree arg;
6703       tree parm;
6704
6705       /* Get the Ith template parameter.  */
6706       parm = TREE_VEC_ELT (parms, parm_idx);
6707  
6708       if (parm == error_mark_node)
6709       {
6710         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6711         continue;
6712       }
6713
6714       /* Calculate the next argument.  */
6715       if (arg_idx < nargs)
6716         arg = TREE_VEC_ELT (inner_args, arg_idx);
6717       else
6718         arg = NULL_TREE;
6719
6720       if (template_parameter_pack_p (TREE_VALUE (parm))
6721           && !(arg && ARGUMENT_PACK_P (arg)))
6722         {
6723           /* All remaining arguments will be placed in the
6724              template parameter pack PARM.  */
6725           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6726                                                 inner_args, arg_idx,
6727                                                 new_args, &lost,
6728                                                 in_decl, complain);
6729
6730           /* Store this argument.  */
6731           if (arg == error_mark_node)
6732             lost++;
6733           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6734
6735           /* We are done with all of the arguments.  */
6736           arg_idx = nargs;
6737           
6738           continue;
6739         }
6740       else if (arg)
6741         {
6742           if (PACK_EXPANSION_P (arg))
6743             {
6744               if (complain & tf_error)
6745                 {
6746                   /* FIXME this restriction was removed by N2555; see
6747                      bug 35722.  */
6748                   /* If ARG is a pack expansion, but PARM is not a
6749                      template parameter pack (if it were, we would have
6750                      handled it above), we're trying to expand into a
6751                      fixed-length argument list.  */
6752                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6753                     sorry ("cannot expand %<%E%> into a fixed-length "
6754                            "argument list", arg);
6755                   else
6756                     sorry ("cannot expand %<%T%> into a fixed-length "
6757                            "argument list", arg);
6758                 }
6759               ++lost;
6760             }
6761         }
6762       else if (require_all_args)
6763         {
6764           /* There must be a default arg in this case.  */
6765           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6766                                      complain, in_decl);
6767           /* The position of the first default template argument,
6768              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6769              Record that.  */
6770           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6771             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6772         }
6773       else
6774         break;
6775
6776       if (arg == error_mark_node)
6777         {
6778           if (complain & tf_error)
6779             error ("template argument %d is invalid", arg_idx + 1);
6780         }
6781       else if (!arg)
6782         /* This only occurs if there was an error in the template
6783            parameter list itself (which we would already have
6784            reported) that we are trying to recover from, e.g., a class
6785            template with a parameter list such as
6786            template<typename..., typename>.  */
6787         ++lost;
6788       else
6789         arg = convert_template_argument (TREE_VALUE (parm),
6790                                          arg, new_args, complain, 
6791                                          parm_idx, in_decl);
6792
6793       if (arg == error_mark_node)
6794         lost++;
6795       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6796     }
6797   cp_unevaluated_operand = saved_unevaluated_operand;
6798   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6799
6800   if (lost)
6801     return error_mark_node;
6802
6803 #ifdef ENABLE_CHECKING
6804   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6805     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6806                                          TREE_VEC_LENGTH (new_inner_args));
6807 #endif
6808
6809   return new_inner_args;
6810 }
6811
6812 /* Returns 1 if template args OT and NT are equivalent.  */
6813
6814 static int
6815 template_args_equal (tree ot, tree nt)
6816 {
6817   if (nt == ot)
6818     return 1;
6819   if (nt == NULL_TREE || ot == NULL_TREE)
6820     return false;
6821
6822   if (TREE_CODE (nt) == TREE_VEC)
6823     /* For member templates */
6824     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6825   else if (PACK_EXPANSION_P (ot))
6826     return PACK_EXPANSION_P (nt) 
6827       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6828                               PACK_EXPANSION_PATTERN (nt));
6829   else if (ARGUMENT_PACK_P (ot))
6830     {
6831       int i, len;
6832       tree opack, npack;
6833
6834       if (!ARGUMENT_PACK_P (nt))
6835         return 0;
6836
6837       opack = ARGUMENT_PACK_ARGS (ot);
6838       npack = ARGUMENT_PACK_ARGS (nt);
6839       len = TREE_VEC_LENGTH (opack);
6840       if (TREE_VEC_LENGTH (npack) != len)
6841         return 0;
6842       for (i = 0; i < len; ++i)
6843         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6844                                   TREE_VEC_ELT (npack, i)))
6845           return 0;
6846       return 1;
6847     }
6848   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6849     {
6850       /* We get here probably because we are in the middle of substituting
6851          into the pattern of a pack expansion. In that case the
6852          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6853          interested in. So we want to use the initial pack argument for
6854          the comparison.  */
6855       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6856       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6857         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6858       return template_args_equal (ot, nt);
6859     }
6860   else if (TYPE_P (nt))
6861     return TYPE_P (ot) && same_type_p (ot, nt);
6862   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6863     return 0;
6864   else
6865     return cp_tree_equal (ot, nt);
6866 }
6867
6868 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6869    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6870    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6871
6872 static int
6873 comp_template_args_with_info (tree oldargs, tree newargs,
6874                               tree *oldarg_ptr, tree *newarg_ptr)
6875 {
6876   int i;
6877
6878   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6879     return 0;
6880
6881   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6882     {
6883       tree nt = TREE_VEC_ELT (newargs, i);
6884       tree ot = TREE_VEC_ELT (oldargs, i);
6885
6886       if (! template_args_equal (ot, nt))
6887         {
6888           if (oldarg_ptr != NULL)
6889             *oldarg_ptr = ot;
6890           if (newarg_ptr != NULL)
6891             *newarg_ptr = nt;
6892           return 0;
6893         }
6894     }
6895   return 1;
6896 }
6897
6898 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6899    of template arguments.  Returns 0 otherwise.  */
6900
6901 int
6902 comp_template_args (tree oldargs, tree newargs)
6903 {
6904   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6905 }
6906
6907 static void
6908 add_pending_template (tree d)
6909 {
6910   tree ti = (TYPE_P (d)
6911              ? CLASSTYPE_TEMPLATE_INFO (d)
6912              : DECL_TEMPLATE_INFO (d));
6913   struct pending_template *pt;
6914   int level;
6915
6916   if (TI_PENDING_TEMPLATE_FLAG (ti))
6917     return;
6918
6919   /* We are called both from instantiate_decl, where we've already had a
6920      tinst_level pushed, and instantiate_template, where we haven't.
6921      Compensate.  */
6922   level = !current_tinst_level || current_tinst_level->decl != d;
6923
6924   if (level)
6925     push_tinst_level (d);
6926
6927   pt = ggc_alloc_pending_template ();
6928   pt->next = NULL;
6929   pt->tinst = current_tinst_level;
6930   if (last_pending_template)
6931     last_pending_template->next = pt;
6932   else
6933     pending_templates = pt;
6934
6935   last_pending_template = pt;
6936
6937   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6938
6939   if (level)
6940     pop_tinst_level ();
6941 }
6942
6943
6944 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6945    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6946    documentation for TEMPLATE_ID_EXPR.  */
6947
6948 tree
6949 lookup_template_function (tree fns, tree arglist)
6950 {
6951   tree type;
6952
6953   if (fns == error_mark_node || arglist == error_mark_node)
6954     return error_mark_node;
6955
6956   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6957
6958   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6959     {
6960       error ("%q#D is not a function template", fns);
6961       return error_mark_node;
6962     }
6963
6964   if (BASELINK_P (fns))
6965     {
6966       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6967                                          unknown_type_node,
6968                                          BASELINK_FUNCTIONS (fns),
6969                                          arglist);
6970       return fns;
6971     }
6972
6973   type = TREE_TYPE (fns);
6974   if (TREE_CODE (fns) == OVERLOAD || !type)
6975     type = unknown_type_node;
6976
6977   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6978 }
6979
6980 /* Within the scope of a template class S<T>, the name S gets bound
6981    (in build_self_reference) to a TYPE_DECL for the class, not a
6982    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6983    or one of its enclosing classes, and that type is a template,
6984    return the associated TEMPLATE_DECL.  Otherwise, the original
6985    DECL is returned.
6986
6987    Also handle the case when DECL is a TREE_LIST of ambiguous
6988    injected-class-names from different bases.  */
6989
6990 tree
6991 maybe_get_template_decl_from_type_decl (tree decl)
6992 {
6993   if (decl == NULL_TREE)
6994     return decl;
6995
6996   /* DR 176: A lookup that finds an injected-class-name (10.2
6997      [class.member.lookup]) can result in an ambiguity in certain cases
6998      (for example, if it is found in more than one base class). If all of
6999      the injected-class-names that are found refer to specializations of
7000      the same class template, and if the name is followed by a
7001      template-argument-list, the reference refers to the class template
7002      itself and not a specialization thereof, and is not ambiguous.  */
7003   if (TREE_CODE (decl) == TREE_LIST)
7004     {
7005       tree t, tmpl = NULL_TREE;
7006       for (t = decl; t; t = TREE_CHAIN (t))
7007         {
7008           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7009           if (!tmpl)
7010             tmpl = elt;
7011           else if (tmpl != elt)
7012             break;
7013         }
7014       if (tmpl && t == NULL_TREE)
7015         return tmpl;
7016       else
7017         return decl;
7018     }
7019
7020   return (decl != NULL_TREE
7021           && DECL_SELF_REFERENCE_P (decl)
7022           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7023     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7024 }
7025
7026 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
7027    parameters, find the desired type.
7028
7029    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7030
7031    IN_DECL, if non-NULL, is the template declaration we are trying to
7032    instantiate.
7033
7034    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7035    the class we are looking up.
7036
7037    Issue error and warning messages under control of COMPLAIN.
7038
7039    If the template class is really a local class in a template
7040    function, then the FUNCTION_CONTEXT is the function in which it is
7041    being instantiated.
7042
7043    ??? Note that this function is currently called *twice* for each
7044    template-id: the first time from the parser, while creating the
7045    incomplete type (finish_template_type), and the second type during the
7046    real instantiation (instantiate_template_class). This is surely something
7047    that we want to avoid. It also causes some problems with argument
7048    coercion (see convert_nontype_argument for more information on this).  */
7049
7050 static tree
7051 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7052                          int entering_scope, tsubst_flags_t complain)
7053 {
7054   tree templ = NULL_TREE, parmlist;
7055   tree t;
7056   spec_entry **slot;
7057   spec_entry *entry;
7058   spec_entry elt;
7059   hashval_t hash;
7060
7061   if (TREE_CODE (d1) == IDENTIFIER_NODE)
7062     {
7063       tree value = innermost_non_namespace_value (d1);
7064       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7065         templ = value;
7066       else
7067         {
7068           if (context)
7069             push_decl_namespace (context);
7070           templ = lookup_name (d1);
7071           templ = maybe_get_template_decl_from_type_decl (templ);
7072           if (context)
7073             pop_decl_namespace ();
7074         }
7075       if (templ)
7076         context = DECL_CONTEXT (templ);
7077     }
7078   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7079     {
7080       tree type = TREE_TYPE (d1);
7081
7082       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7083          an implicit typename for the second A.  Deal with it.  */
7084       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7085         type = TREE_TYPE (type);
7086
7087       if (CLASSTYPE_TEMPLATE_INFO (type))
7088         {
7089           templ = CLASSTYPE_TI_TEMPLATE (type);
7090           d1 = DECL_NAME (templ);
7091         }
7092     }
7093   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7094            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7095     {
7096       templ = TYPE_TI_TEMPLATE (d1);
7097       d1 = DECL_NAME (templ);
7098     }
7099   else if (TREE_CODE (d1) == TEMPLATE_DECL
7100            && DECL_TEMPLATE_RESULT (d1)
7101            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7102     {
7103       templ = d1;
7104       d1 = DECL_NAME (templ);
7105       context = DECL_CONTEXT (templ);
7106     }
7107
7108   /* Issue an error message if we didn't find a template.  */
7109   if (! templ)
7110     {
7111       if (complain & tf_error)
7112         error ("%qT is not a template", d1);
7113       return error_mark_node;
7114     }
7115
7116   if (TREE_CODE (templ) != TEMPLATE_DECL
7117          /* Make sure it's a user visible template, if it was named by
7118             the user.  */
7119       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7120           && !PRIMARY_TEMPLATE_P (templ)))
7121     {
7122       if (complain & tf_error)
7123         {
7124           error ("non-template type %qT used as a template", d1);
7125           if (in_decl)
7126             error ("for template declaration %q+D", in_decl);
7127         }
7128       return error_mark_node;
7129     }
7130
7131   complain &= ~tf_user;
7132
7133   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7134     {
7135       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7136          template arguments */
7137
7138       tree parm;
7139       tree arglist2;
7140       tree outer;
7141
7142       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7143
7144       /* Consider an example where a template template parameter declared as
7145
7146            template <class T, class U = std::allocator<T> > class TT
7147
7148          The template parameter level of T and U are one level larger than
7149          of TT.  To proper process the default argument of U, say when an
7150          instantiation `TT<int>' is seen, we need to build the full
7151          arguments containing {int} as the innermost level.  Outer levels,
7152          available when not appearing as default template argument, can be
7153          obtained from the arguments of the enclosing template.
7154
7155          Suppose that TT is later substituted with std::vector.  The above
7156          instantiation is `TT<int, std::allocator<T> >' with TT at
7157          level 1, and T at level 2, while the template arguments at level 1
7158          becomes {std::vector} and the inner level 2 is {int}.  */
7159
7160       outer = DECL_CONTEXT (templ);
7161       if (outer)
7162         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7163       else if (current_template_parms)
7164         /* This is an argument of the current template, so we haven't set
7165            DECL_CONTEXT yet.  */
7166         outer = current_template_args ();
7167
7168       if (outer)
7169         arglist = add_to_template_args (outer, arglist);
7170
7171       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7172                                         complain,
7173                                         /*require_all_args=*/true,
7174                                         /*use_default_args=*/true);
7175       if (arglist2 == error_mark_node
7176           || (!uses_template_parms (arglist2)
7177               && check_instantiated_args (templ, arglist2, complain)))
7178         return error_mark_node;
7179
7180       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7181       return parm;
7182     }
7183   else
7184     {
7185       tree template_type = TREE_TYPE (templ);
7186       tree gen_tmpl;
7187       tree type_decl;
7188       tree found = NULL_TREE;
7189       int arg_depth;
7190       int parm_depth;
7191       int is_dependent_type;
7192       int use_partial_inst_tmpl = false;
7193
7194       gen_tmpl = most_general_template (templ);
7195       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7196       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7197       arg_depth = TMPL_ARGS_DEPTH (arglist);
7198
7199       if (arg_depth == 1 && parm_depth > 1)
7200         {
7201           /* We've been given an incomplete set of template arguments.
7202              For example, given:
7203
7204                template <class T> struct S1 {
7205                  template <class U> struct S2 {};
7206                  template <class U> struct S2<U*> {};
7207                 };
7208
7209              we will be called with an ARGLIST of `U*', but the
7210              TEMPLATE will be `template <class T> template
7211              <class U> struct S1<T>::S2'.  We must fill in the missing
7212              arguments.  */
7213           arglist
7214             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7215                                            arglist);
7216           arg_depth = TMPL_ARGS_DEPTH (arglist);
7217         }
7218
7219       /* Now we should have enough arguments.  */
7220       gcc_assert (parm_depth == arg_depth);
7221
7222       /* From here on, we're only interested in the most general
7223          template.  */
7224
7225       /* Calculate the BOUND_ARGS.  These will be the args that are
7226          actually tsubst'd into the definition to create the
7227          instantiation.  */
7228       if (parm_depth > 1)
7229         {
7230           /* We have multiple levels of arguments to coerce, at once.  */
7231           int i;
7232           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7233
7234           tree bound_args = make_tree_vec (parm_depth);
7235
7236           for (i = saved_depth,
7237                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7238                i > 0 && t != NULL_TREE;
7239                --i, t = TREE_CHAIN (t))
7240             {
7241               tree a;
7242               if (i == saved_depth)
7243                 a = coerce_template_parms (TREE_VALUE (t),
7244                                            arglist, gen_tmpl,
7245                                            complain,
7246                                            /*require_all_args=*/true,
7247                                            /*use_default_args=*/true);
7248               else
7249                 /* Outer levels should have already been coerced.  */
7250                 a = TMPL_ARGS_LEVEL (arglist, i);
7251
7252               /* Don't process further if one of the levels fails.  */
7253               if (a == error_mark_node)
7254                 {
7255                   /* Restore the ARGLIST to its full size.  */
7256                   TREE_VEC_LENGTH (arglist) = saved_depth;
7257                   return error_mark_node;
7258                 }
7259
7260               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7261
7262               /* We temporarily reduce the length of the ARGLIST so
7263                  that coerce_template_parms will see only the arguments
7264                  corresponding to the template parameters it is
7265                  examining.  */
7266               TREE_VEC_LENGTH (arglist)--;
7267             }
7268
7269           /* Restore the ARGLIST to its full size.  */
7270           TREE_VEC_LENGTH (arglist) = saved_depth;
7271
7272           arglist = bound_args;
7273         }
7274       else
7275         arglist
7276           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7277                                    INNERMOST_TEMPLATE_ARGS (arglist),
7278                                    gen_tmpl,
7279                                    complain,
7280                                    /*require_all_args=*/true,
7281                                    /*use_default_args=*/true);
7282
7283       if (arglist == error_mark_node)
7284         /* We were unable to bind the arguments.  */
7285         return error_mark_node;
7286
7287       /* In the scope of a template class, explicit references to the
7288          template class refer to the type of the template, not any
7289          instantiation of it.  For example, in:
7290
7291            template <class T> class C { void f(C<T>); }
7292
7293          the `C<T>' is just the same as `C'.  Outside of the
7294          class, however, such a reference is an instantiation.  */
7295       if ((entering_scope
7296            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7297            || currently_open_class (template_type))
7298           /* comp_template_args is expensive, check it last.  */
7299           && comp_template_args (TYPE_TI_ARGS (template_type),
7300                                  arglist))
7301         return template_type;
7302
7303       /* If we already have this specialization, return it.  */
7304       elt.tmpl = gen_tmpl;
7305       elt.args = arglist;
7306       hash = hash_specialization (&elt);
7307       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7308                                                   &elt, hash);
7309
7310       if (entry)
7311         return entry->spec;
7312
7313       is_dependent_type = uses_template_parms (arglist);
7314
7315       /* If the deduced arguments are invalid, then the binding
7316          failed.  */
7317       if (!is_dependent_type
7318           && check_instantiated_args (gen_tmpl,
7319                                       INNERMOST_TEMPLATE_ARGS (arglist),
7320                                       complain))
7321         return error_mark_node;
7322
7323       if (!is_dependent_type
7324           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7325           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7326           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7327         {
7328           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7329                                       DECL_NAME (gen_tmpl),
7330                                       /*tag_scope=*/ts_global);
7331           return found;
7332         }
7333
7334       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7335                         complain, in_decl);
7336       if (!context)
7337         context = global_namespace;
7338
7339       /* Create the type.  */
7340       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7341         {
7342           if (!is_dependent_type)
7343             {
7344               set_current_access_from_decl (TYPE_NAME (template_type));
7345               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7346                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7347                                       arglist, complain, in_decl),
7348                               SCOPED_ENUM_P (template_type), NULL);
7349             }
7350           else
7351             {
7352               /* We don't want to call start_enum for this type, since
7353                  the values for the enumeration constants may involve
7354                  template parameters.  And, no one should be interested
7355                  in the enumeration constants for such a type.  */
7356               t = cxx_make_type (ENUMERAL_TYPE);
7357               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7358             }
7359           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7360           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7361             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7362         }
7363       else
7364         {
7365           t = make_class_type (TREE_CODE (template_type));
7366           CLASSTYPE_DECLARED_CLASS (t)
7367             = CLASSTYPE_DECLARED_CLASS (template_type);
7368           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7369           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7370
7371           /* A local class.  Make sure the decl gets registered properly.  */
7372           if (context == current_function_decl)
7373             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7374
7375           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7376             /* This instantiation is another name for the primary
7377                template type. Set the TYPE_CANONICAL field
7378                appropriately. */
7379             TYPE_CANONICAL (t) = template_type;
7380           else if (any_template_arguments_need_structural_equality_p (arglist))
7381             /* Some of the template arguments require structural
7382                equality testing, so this template class requires
7383                structural equality testing. */
7384             SET_TYPE_STRUCTURAL_EQUALITY (t);
7385         }
7386
7387       /* If we called start_enum or pushtag above, this information
7388          will already be set up.  */
7389       if (!TYPE_NAME (t))
7390         {
7391           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7392
7393           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7394           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7395           DECL_SOURCE_LOCATION (type_decl)
7396             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7397         }
7398       else
7399         type_decl = TYPE_NAME (t);
7400
7401       TREE_PRIVATE (type_decl)
7402         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7403       TREE_PROTECTED (type_decl)
7404         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7405       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7406         {
7407           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7408           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7409         }
7410
7411       /* Let's consider the explicit specialization of a member
7412          of a class template specialization that is implicitely instantiated,
7413          e.g.:
7414              template<class T>
7415              struct S
7416              {
7417                template<class U> struct M {}; //#0
7418              };
7419
7420              template<>
7421              template<>
7422              struct S<int>::M<char> //#1
7423              {
7424                int i;
7425              };
7426         [temp.expl.spec]/4 says this is valid.
7427
7428         In this case, when we write:
7429         S<int>::M<char> m;
7430
7431         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7432         the one of #0.
7433
7434         When we encounter #1, we want to store the partial instantiation
7435         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7436
7437         For all cases other than this "explicit specialization of member of a
7438         class template", we just want to store the most general template into
7439         the CLASSTYPE_TI_TEMPLATE of M.
7440
7441         This case of "explicit specialization of member of a class template"
7442         only happens when:
7443         1/ the enclosing class is an instantiation of, and therefore not
7444         the same as, the context of the most general template, and
7445         2/ we aren't looking at the partial instantiation itself, i.e.
7446         the innermost arguments are not the same as the innermost parms of
7447         the most general template.
7448
7449         So it's only when 1/ and 2/ happens that we want to use the partial
7450         instantiation of the member template in lieu of its most general
7451         template.  */
7452
7453       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7454           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7455           /* the enclosing class must be an instantiation...  */
7456           && CLASS_TYPE_P (context)
7457           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7458         {
7459           tree partial_inst_args;
7460           TREE_VEC_LENGTH (arglist)--;
7461           ++processing_template_decl;
7462           partial_inst_args =
7463             tsubst (INNERMOST_TEMPLATE_ARGS
7464                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7465                     arglist, complain, NULL_TREE);
7466           --processing_template_decl;
7467           TREE_VEC_LENGTH (arglist)++;
7468           use_partial_inst_tmpl =
7469             /*...and we must not be looking at the partial instantiation
7470              itself. */
7471             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7472                                  partial_inst_args);
7473         }
7474
7475       if (!use_partial_inst_tmpl)
7476         /* This case is easy; there are no member templates involved.  */
7477         found = gen_tmpl;
7478       else
7479         {
7480           /* This is a full instantiation of a member template.  Find
7481              the partial instantiation of which this is an instance.  */
7482
7483           /* Temporarily reduce by one the number of levels in the ARGLIST
7484              so as to avoid comparing the last set of arguments.  */
7485           TREE_VEC_LENGTH (arglist)--;
7486           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7487           TREE_VEC_LENGTH (arglist)++;
7488           found = CLASSTYPE_TI_TEMPLATE (found);
7489         }
7490
7491       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7492
7493       elt.spec = t;
7494       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7495                                                        &elt, hash, INSERT);
7496       *slot = ggc_alloc_spec_entry ();
7497       **slot = elt;
7498
7499       /* Note this use of the partial instantiation so we can check it
7500          later in maybe_process_partial_specialization.  */
7501       DECL_TEMPLATE_INSTANTIATIONS (templ)
7502         = tree_cons (arglist, t,
7503                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7504
7505       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7506         /* Now that the type has been registered on the instantiations
7507            list, we set up the enumerators.  Because the enumeration
7508            constants may involve the enumeration type itself, we make
7509            sure to register the type first, and then create the
7510            constants.  That way, doing tsubst_expr for the enumeration
7511            constants won't result in recursive calls here; we'll find
7512            the instantiation and exit above.  */
7513         tsubst_enum (template_type, t, arglist);
7514
7515       if (is_dependent_type)
7516         /* If the type makes use of template parameters, the
7517            code that generates debugging information will crash.  */
7518         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7519
7520       /* Possibly limit visibility based on template args.  */
7521       TREE_PUBLIC (type_decl) = 1;
7522       determine_visibility (type_decl);
7523
7524       return t;
7525     }
7526 }
7527
7528 /* Wrapper for lookup_template_class_1.  */
7529
7530 tree
7531 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7532                        int entering_scope, tsubst_flags_t complain)
7533 {
7534   tree ret;
7535   timevar_push (TV_TEMPLATE_INST);
7536   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7537                                  entering_scope, complain);
7538   timevar_pop (TV_TEMPLATE_INST);
7539   return ret;
7540 }
7541 \f
7542 struct pair_fn_data
7543 {
7544   tree_fn_t fn;
7545   void *data;
7546   /* True when we should also visit template parameters that occur in
7547      non-deduced contexts.  */
7548   bool include_nondeduced_p;
7549   struct pointer_set_t *visited;
7550 };
7551
7552 /* Called from for_each_template_parm via walk_tree.  */
7553
7554 static tree
7555 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7556 {
7557   tree t = *tp;
7558   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7559   tree_fn_t fn = pfd->fn;
7560   void *data = pfd->data;
7561
7562   if (TYPE_P (t)
7563       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7564       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7565                                  pfd->include_nondeduced_p))
7566     return error_mark_node;
7567
7568   switch (TREE_CODE (t))
7569     {
7570     case RECORD_TYPE:
7571       if (TYPE_PTRMEMFUNC_P (t))
7572         break;
7573       /* Fall through.  */
7574
7575     case UNION_TYPE:
7576     case ENUMERAL_TYPE:
7577       if (!TYPE_TEMPLATE_INFO (t))
7578         *walk_subtrees = 0;
7579       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7580                                        fn, data, pfd->visited, 
7581                                        pfd->include_nondeduced_p))
7582         return error_mark_node;
7583       break;
7584
7585     case INTEGER_TYPE:
7586       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7587                                   fn, data, pfd->visited, 
7588                                   pfd->include_nondeduced_p)
7589           || for_each_template_parm (TYPE_MAX_VALUE (t),
7590                                      fn, data, pfd->visited,
7591                                      pfd->include_nondeduced_p))
7592         return error_mark_node;
7593       break;
7594
7595     case METHOD_TYPE:
7596       /* Since we're not going to walk subtrees, we have to do this
7597          explicitly here.  */
7598       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7599                                   pfd->visited, pfd->include_nondeduced_p))
7600         return error_mark_node;
7601       /* Fall through.  */
7602
7603     case FUNCTION_TYPE:
7604       /* Check the return type.  */
7605       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7606                                   pfd->include_nondeduced_p))
7607         return error_mark_node;
7608
7609       /* Check the parameter types.  Since default arguments are not
7610          instantiated until they are needed, the TYPE_ARG_TYPES may
7611          contain expressions that involve template parameters.  But,
7612          no-one should be looking at them yet.  And, once they're
7613          instantiated, they don't contain template parameters, so
7614          there's no point in looking at them then, either.  */
7615       {
7616         tree parm;
7617
7618         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7619           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7620                                       pfd->visited, pfd->include_nondeduced_p))
7621             return error_mark_node;
7622
7623         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7624            want walk_tree walking into them itself.  */
7625         *walk_subtrees = 0;
7626       }
7627       break;
7628
7629     case TYPEOF_TYPE:
7630     case UNDERLYING_TYPE:
7631       if (pfd->include_nondeduced_p
7632           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7633                                      pfd->visited, 
7634                                      pfd->include_nondeduced_p))
7635         return error_mark_node;
7636       break;
7637
7638     case FUNCTION_DECL:
7639     case VAR_DECL:
7640       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7641           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7642                                      pfd->visited, pfd->include_nondeduced_p))
7643         return error_mark_node;
7644       /* Fall through.  */
7645
7646     case PARM_DECL:
7647     case CONST_DECL:
7648       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7649           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7650                                      pfd->visited, pfd->include_nondeduced_p))
7651         return error_mark_node;
7652       if (DECL_CONTEXT (t)
7653           && pfd->include_nondeduced_p
7654           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7655                                      pfd->visited, pfd->include_nondeduced_p))
7656         return error_mark_node;
7657       break;
7658
7659     case BOUND_TEMPLATE_TEMPLATE_PARM:
7660       /* Record template parameters such as `T' inside `TT<T>'.  */
7661       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7662                                   pfd->include_nondeduced_p))
7663         return error_mark_node;
7664       /* Fall through.  */
7665
7666     case TEMPLATE_TEMPLATE_PARM:
7667     case TEMPLATE_TYPE_PARM:
7668     case TEMPLATE_PARM_INDEX:
7669       if (fn && (*fn)(t, data))
7670         return error_mark_node;
7671       else if (!fn)
7672         return error_mark_node;
7673       break;
7674
7675     case TEMPLATE_DECL:
7676       /* A template template parameter is encountered.  */
7677       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7678           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7679                                      pfd->include_nondeduced_p))
7680         return error_mark_node;
7681
7682       /* Already substituted template template parameter */
7683       *walk_subtrees = 0;
7684       break;
7685
7686     case TYPENAME_TYPE:
7687       if (!fn
7688           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7689                                      data, pfd->visited, 
7690                                      pfd->include_nondeduced_p))
7691         return error_mark_node;
7692       break;
7693
7694     case CONSTRUCTOR:
7695       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7696           && pfd->include_nondeduced_p
7697           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7698                                      (TREE_TYPE (t)), fn, data,
7699                                      pfd->visited, pfd->include_nondeduced_p))
7700         return error_mark_node;
7701       break;
7702
7703     case INDIRECT_REF:
7704     case COMPONENT_REF:
7705       /* If there's no type, then this thing must be some expression
7706          involving template parameters.  */
7707       if (!fn && !TREE_TYPE (t))
7708         return error_mark_node;
7709       break;
7710
7711     case MODOP_EXPR:
7712     case CAST_EXPR:
7713     case REINTERPRET_CAST_EXPR:
7714     case CONST_CAST_EXPR:
7715     case STATIC_CAST_EXPR:
7716     case DYNAMIC_CAST_EXPR:
7717     case ARROW_EXPR:
7718     case DOTSTAR_EXPR:
7719     case TYPEID_EXPR:
7720     case PSEUDO_DTOR_EXPR:
7721       if (!fn)
7722         return error_mark_node;
7723       break;
7724
7725     default:
7726       break;
7727     }
7728
7729   /* We didn't find any template parameters we liked.  */
7730   return NULL_TREE;
7731 }
7732
7733 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7734    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7735    call FN with the parameter and the DATA.
7736    If FN returns nonzero, the iteration is terminated, and
7737    for_each_template_parm returns 1.  Otherwise, the iteration
7738    continues.  If FN never returns a nonzero value, the value
7739    returned by for_each_template_parm is 0.  If FN is NULL, it is
7740    considered to be the function which always returns 1.
7741
7742    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7743    parameters that occur in non-deduced contexts.  When false, only
7744    visits those template parameters that can be deduced.  */
7745
7746 static int
7747 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7748                         struct pointer_set_t *visited,
7749                         bool include_nondeduced_p)
7750 {
7751   struct pair_fn_data pfd;
7752   int result;
7753
7754   /* Set up.  */
7755   pfd.fn = fn;
7756   pfd.data = data;
7757   pfd.include_nondeduced_p = include_nondeduced_p;
7758
7759   /* Walk the tree.  (Conceptually, we would like to walk without
7760      duplicates, but for_each_template_parm_r recursively calls
7761      for_each_template_parm, so we would need to reorganize a fair
7762      bit to use walk_tree_without_duplicates, so we keep our own
7763      visited list.)  */
7764   if (visited)
7765     pfd.visited = visited;
7766   else
7767     pfd.visited = pointer_set_create ();
7768   result = cp_walk_tree (&t,
7769                          for_each_template_parm_r,
7770                          &pfd,
7771                          pfd.visited) != NULL_TREE;
7772
7773   /* Clean up.  */
7774   if (!visited)
7775     {
7776       pointer_set_destroy (pfd.visited);
7777       pfd.visited = 0;
7778     }
7779
7780   return result;
7781 }
7782
7783 /* Returns true if T depends on any template parameter.  */
7784
7785 int
7786 uses_template_parms (tree t)
7787 {
7788   bool dependent_p;
7789   int saved_processing_template_decl;
7790
7791   saved_processing_template_decl = processing_template_decl;
7792   if (!saved_processing_template_decl)
7793     processing_template_decl = 1;
7794   if (TYPE_P (t))
7795     dependent_p = dependent_type_p (t);
7796   else if (TREE_CODE (t) == TREE_VEC)
7797     dependent_p = any_dependent_template_arguments_p (t);
7798   else if (TREE_CODE (t) == TREE_LIST)
7799     dependent_p = (uses_template_parms (TREE_VALUE (t))
7800                    || uses_template_parms (TREE_CHAIN (t)));
7801   else if (TREE_CODE (t) == TYPE_DECL)
7802     dependent_p = dependent_type_p (TREE_TYPE (t));
7803   else if (DECL_P (t)
7804            || EXPR_P (t)
7805            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7806            || TREE_CODE (t) == OVERLOAD
7807            || TREE_CODE (t) == BASELINK
7808            || TREE_CODE (t) == IDENTIFIER_NODE
7809            || TREE_CODE (t) == TRAIT_EXPR
7810            || TREE_CODE (t) == CONSTRUCTOR
7811            || CONSTANT_CLASS_P (t))
7812     dependent_p = (type_dependent_expression_p (t)
7813                    || value_dependent_expression_p (t));
7814   else
7815     {
7816       gcc_assert (t == error_mark_node);
7817       dependent_p = false;
7818     }
7819
7820   processing_template_decl = saved_processing_template_decl;
7821
7822   return dependent_p;
7823 }
7824
7825 /* Returns true if T depends on any template parameter with level LEVEL.  */
7826
7827 int
7828 uses_template_parms_level (tree t, int level)
7829 {
7830   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7831                                  /*include_nondeduced_p=*/true);
7832 }
7833
7834 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7835    ill-formed translation unit, i.e. a variable or function that isn't
7836    usable in a constant expression.  */
7837
7838 static inline bool
7839 neglectable_inst_p (tree d)
7840 {
7841   return (DECL_P (d)
7842           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7843                : decl_maybe_constant_var_p (d)));
7844 }
7845
7846 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7847    neglectable and instantiated from within an erroneous instantiation.  */
7848
7849 static bool
7850 limit_bad_template_recursion (tree decl)
7851 {
7852   struct tinst_level *lev = current_tinst_level;
7853   int errs = errorcount + sorrycount;
7854   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7855     return false;
7856
7857   for (; lev; lev = lev->next)
7858     if (neglectable_inst_p (lev->decl))
7859       break;
7860
7861   return (lev && errs > lev->errors);
7862 }
7863
7864 static int tinst_depth;
7865 extern int max_tinst_depth;
7866 #ifdef GATHER_STATISTICS
7867 int depth_reached;
7868 #endif
7869 static GTY(()) struct tinst_level *last_error_tinst_level;
7870
7871 /* We're starting to instantiate D; record the template instantiation context
7872    for diagnostics and to restore it later.  */
7873
7874 int
7875 push_tinst_level (tree d)
7876 {
7877   struct tinst_level *new_level;
7878
7879   if (tinst_depth >= max_tinst_depth)
7880     {
7881       last_error_tinst_level = current_tinst_level;
7882       if (TREE_CODE (d) == TREE_LIST)
7883         error ("template instantiation depth exceeds maximum of %d (use "
7884                "-ftemplate-depth= to increase the maximum) substituting %qS",
7885                max_tinst_depth, d);
7886       else
7887         error ("template instantiation depth exceeds maximum of %d (use "
7888                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7889                max_tinst_depth, d);
7890
7891       print_instantiation_context ();
7892
7893       return 0;
7894     }
7895
7896   /* If the current instantiation caused problems, don't let it instantiate
7897      anything else.  Do allow deduction substitution and decls usable in
7898      constant expressions.  */
7899   if (limit_bad_template_recursion (d))
7900     return 0;
7901
7902   new_level = ggc_alloc_tinst_level ();
7903   new_level->decl = d;
7904   new_level->locus = input_location;
7905   new_level->errors = errorcount+sorrycount;
7906   new_level->in_system_header_p = in_system_header;
7907   new_level->next = current_tinst_level;
7908   current_tinst_level = new_level;
7909
7910   ++tinst_depth;
7911 #ifdef GATHER_STATISTICS
7912   if (tinst_depth > depth_reached)
7913     depth_reached = tinst_depth;
7914 #endif
7915
7916   return 1;
7917 }
7918
7919 /* We're done instantiating this template; return to the instantiation
7920    context.  */
7921
7922 void
7923 pop_tinst_level (void)
7924 {
7925   /* Restore the filename and line number stashed away when we started
7926      this instantiation.  */
7927   input_location = current_tinst_level->locus;
7928   current_tinst_level = current_tinst_level->next;
7929   --tinst_depth;
7930 }
7931
7932 /* We're instantiating a deferred template; restore the template
7933    instantiation context in which the instantiation was requested, which
7934    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7935
7936 static tree
7937 reopen_tinst_level (struct tinst_level *level)
7938 {
7939   struct tinst_level *t;
7940
7941   tinst_depth = 0;
7942   for (t = level; t; t = t->next)
7943     ++tinst_depth;
7944
7945   current_tinst_level = level;
7946   pop_tinst_level ();
7947   if (current_tinst_level)
7948     current_tinst_level->errors = errorcount+sorrycount;
7949   return level->decl;
7950 }
7951
7952 /* Returns the TINST_LEVEL which gives the original instantiation
7953    context.  */
7954
7955 struct tinst_level *
7956 outermost_tinst_level (void)
7957 {
7958   struct tinst_level *level = current_tinst_level;
7959   if (level)
7960     while (level->next)
7961       level = level->next;
7962   return level;
7963 }
7964
7965 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7966
7967 bool
7968 parameter_of_template_p (tree parm, tree templ)
7969 {
7970   tree parms;
7971   int i;
7972
7973   if (!parm || !templ)
7974     return false;
7975
7976   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7977   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7978
7979   parms = DECL_TEMPLATE_PARMS (templ);
7980   parms = INNERMOST_TEMPLATE_PARMS (parms);
7981
7982   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7983     {
7984       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7985       if (parm == p
7986           || (DECL_INITIAL (parm)
7987               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7988         return true;
7989     }
7990
7991   return false;
7992 }
7993
7994 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7995    vector of template arguments, as for tsubst.
7996
7997    Returns an appropriate tsubst'd friend declaration.  */
7998
7999 static tree
8000 tsubst_friend_function (tree decl, tree args)
8001 {
8002   tree new_friend;
8003
8004   if (TREE_CODE (decl) == FUNCTION_DECL
8005       && DECL_TEMPLATE_INSTANTIATION (decl)
8006       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8007     /* This was a friend declared with an explicit template
8008        argument list, e.g.:
8009
8010        friend void f<>(T);
8011
8012        to indicate that f was a template instantiation, not a new
8013        function declaration.  Now, we have to figure out what
8014        instantiation of what template.  */
8015     {
8016       tree template_id, arglist, fns;
8017       tree new_args;
8018       tree tmpl;
8019       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8020
8021       /* Friend functions are looked up in the containing namespace scope.
8022          We must enter that scope, to avoid finding member functions of the
8023          current class with same name.  */
8024       push_nested_namespace (ns);
8025       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8026                          tf_warning_or_error, NULL_TREE,
8027                          /*integral_constant_expression_p=*/false);
8028       pop_nested_namespace (ns);
8029       arglist = tsubst (DECL_TI_ARGS (decl), args,
8030                         tf_warning_or_error, NULL_TREE);
8031       template_id = lookup_template_function (fns, arglist);
8032
8033       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8034       tmpl = determine_specialization (template_id, new_friend,
8035                                        &new_args,
8036                                        /*need_member_template=*/0,
8037                                        TREE_VEC_LENGTH (args),
8038                                        tsk_none);
8039       return instantiate_template (tmpl, new_args, tf_error);
8040     }
8041
8042   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8043
8044   /* The NEW_FRIEND will look like an instantiation, to the
8045      compiler, but is not an instantiation from the point of view of
8046      the language.  For example, we might have had:
8047
8048      template <class T> struct S {
8049        template <class U> friend void f(T, U);
8050      };
8051
8052      Then, in S<int>, template <class U> void f(int, U) is not an
8053      instantiation of anything.  */
8054   if (new_friend == error_mark_node)
8055     return error_mark_node;
8056
8057   DECL_USE_TEMPLATE (new_friend) = 0;
8058   if (TREE_CODE (decl) == TEMPLATE_DECL)
8059     {
8060       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8061       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8062         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8063     }
8064
8065   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8066      is not a template instantiation and should not be mangled like
8067      one.  Therefore, we forget the mangling here; we'll recompute it
8068      later if we need it.  */
8069   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8070     {
8071       SET_DECL_RTL (new_friend, NULL);
8072       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8073     }
8074
8075   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8076     {
8077       tree old_decl;
8078       tree new_friend_template_info;
8079       tree new_friend_result_template_info;
8080       tree ns;
8081       int  new_friend_is_defn;
8082
8083       /* We must save some information from NEW_FRIEND before calling
8084          duplicate decls since that function will free NEW_FRIEND if
8085          possible.  */
8086       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8087       new_friend_is_defn =
8088             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8089                            (template_for_substitution (new_friend)))
8090              != NULL_TREE);
8091       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8092         {
8093           /* This declaration is a `primary' template.  */
8094           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8095
8096           new_friend_result_template_info
8097             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8098         }
8099       else
8100         new_friend_result_template_info = NULL_TREE;
8101
8102       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8103       if (new_friend_is_defn)
8104         DECL_INITIAL (new_friend) = error_mark_node;
8105
8106       /* Inside pushdecl_namespace_level, we will push into the
8107          current namespace. However, the friend function should go
8108          into the namespace of the template.  */
8109       ns = decl_namespace_context (new_friend);
8110       push_nested_namespace (ns);
8111       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8112       pop_nested_namespace (ns);
8113
8114       if (old_decl == error_mark_node)
8115         return error_mark_node;
8116
8117       if (old_decl != new_friend)
8118         {
8119           /* This new friend declaration matched an existing
8120              declaration.  For example, given:
8121
8122                template <class T> void f(T);
8123                template <class U> class C {
8124                  template <class T> friend void f(T) {}
8125                };
8126
8127              the friend declaration actually provides the definition
8128              of `f', once C has been instantiated for some type.  So,
8129              old_decl will be the out-of-class template declaration,
8130              while new_friend is the in-class definition.
8131
8132              But, if `f' was called before this point, the
8133              instantiation of `f' will have DECL_TI_ARGS corresponding
8134              to `T' but not to `U', references to which might appear
8135              in the definition of `f'.  Previously, the most general
8136              template for an instantiation of `f' was the out-of-class
8137              version; now it is the in-class version.  Therefore, we
8138              run through all specialization of `f', adding to their
8139              DECL_TI_ARGS appropriately.  In particular, they need a
8140              new set of outer arguments, corresponding to the
8141              arguments for this class instantiation.
8142
8143              The same situation can arise with something like this:
8144
8145                friend void f(int);
8146                template <class T> class C {
8147                  friend void f(T) {}
8148                };
8149
8150              when `C<int>' is instantiated.  Now, `f(int)' is defined
8151              in the class.  */
8152
8153           if (!new_friend_is_defn)
8154             /* On the other hand, if the in-class declaration does
8155                *not* provide a definition, then we don't want to alter
8156                existing definitions.  We can just leave everything
8157                alone.  */
8158             ;
8159           else
8160             {
8161               tree new_template = TI_TEMPLATE (new_friend_template_info);
8162               tree new_args = TI_ARGS (new_friend_template_info);
8163
8164               /* Overwrite whatever template info was there before, if
8165                  any, with the new template information pertaining to
8166                  the declaration.  */
8167               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8168
8169               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8170                 {
8171                   /* We should have called reregister_specialization in
8172                      duplicate_decls.  */
8173                   gcc_assert (retrieve_specialization (new_template,
8174                                                        new_args, 0)
8175                               == old_decl);
8176
8177                   /* Instantiate it if the global has already been used.  */
8178                   if (DECL_ODR_USED (old_decl))
8179                     instantiate_decl (old_decl, /*defer_ok=*/true,
8180                                       /*expl_inst_class_mem_p=*/false);
8181                 }
8182               else
8183                 {
8184                   tree t;
8185
8186                   /* Indicate that the old function template is a partial
8187                      instantiation.  */
8188                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8189                     = new_friend_result_template_info;
8190
8191                   gcc_assert (new_template
8192                               == most_general_template (new_template));
8193                   gcc_assert (new_template != old_decl);
8194
8195                   /* Reassign any specializations already in the hash table
8196                      to the new more general template, and add the
8197                      additional template args.  */
8198                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8199                        t != NULL_TREE;
8200                        t = TREE_CHAIN (t))
8201                     {
8202                       tree spec = TREE_VALUE (t);
8203                       spec_entry elt;
8204
8205                       elt.tmpl = old_decl;
8206                       elt.args = DECL_TI_ARGS (spec);
8207                       elt.spec = NULL_TREE;
8208
8209                       htab_remove_elt (decl_specializations, &elt);
8210
8211                       DECL_TI_ARGS (spec)
8212                         = add_outermost_template_args (new_args,
8213                                                        DECL_TI_ARGS (spec));
8214
8215                       register_specialization
8216                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8217
8218                     }
8219                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8220                 }
8221             }
8222
8223           /* The information from NEW_FRIEND has been merged into OLD_DECL
8224              by duplicate_decls.  */
8225           new_friend = old_decl;
8226         }
8227     }
8228   else
8229     {
8230       tree context = DECL_CONTEXT (new_friend);
8231       bool dependent_p;
8232
8233       /* In the code
8234            template <class T> class C {
8235              template <class U> friend void C1<U>::f (); // case 1
8236              friend void C2<T>::f ();                    // case 2
8237            };
8238          we only need to make sure CONTEXT is a complete type for
8239          case 2.  To distinguish between the two cases, we note that
8240          CONTEXT of case 1 remains dependent type after tsubst while
8241          this isn't true for case 2.  */
8242       ++processing_template_decl;
8243       dependent_p = dependent_type_p (context);
8244       --processing_template_decl;
8245
8246       if (!dependent_p
8247           && !complete_type_or_else (context, NULL_TREE))
8248         return error_mark_node;
8249
8250       if (COMPLETE_TYPE_P (context))
8251         {
8252           /* Check to see that the declaration is really present, and,
8253              possibly obtain an improved declaration.  */
8254           tree fn = check_classfn (context,
8255                                    new_friend, NULL_TREE);
8256
8257           if (fn)
8258             new_friend = fn;
8259         }
8260     }
8261
8262   return new_friend;
8263 }
8264
8265 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8266    template arguments, as for tsubst.
8267
8268    Returns an appropriate tsubst'd friend type or error_mark_node on
8269    failure.  */
8270
8271 static tree
8272 tsubst_friend_class (tree friend_tmpl, tree args)
8273 {
8274   tree friend_type;
8275   tree tmpl;
8276   tree context;
8277
8278   context = CP_DECL_CONTEXT (friend_tmpl);
8279
8280   if (context != global_namespace)
8281     {
8282       if (TREE_CODE (context) == NAMESPACE_DECL)
8283         push_nested_namespace (context);
8284       else
8285         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8286     }
8287
8288   /* Look for a class template declaration.  We look for hidden names
8289      because two friend declarations of the same template are the
8290      same.  For example, in:
8291
8292        struct A { 
8293          template <typename> friend class F;
8294        };
8295        template <typename> struct B { 
8296          template <typename> friend class F;
8297        };
8298
8299      both F templates are the same.  */
8300   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8301                            /*block_p=*/true, 0, 
8302                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8303
8304   /* But, if we don't find one, it might be because we're in a
8305      situation like this:
8306
8307        template <class T>
8308        struct S {
8309          template <class U>
8310          friend struct S;
8311        };
8312
8313      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8314      for `S<int>', not the TEMPLATE_DECL.  */
8315   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8316     {
8317       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8318       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8319     }
8320
8321   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8322     {
8323       /* The friend template has already been declared.  Just
8324          check to see that the declarations match, and install any new
8325          default parameters.  We must tsubst the default parameters,
8326          of course.  We only need the innermost template parameters
8327          because that is all that redeclare_class_template will look
8328          at.  */
8329       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8330           > TMPL_ARGS_DEPTH (args))
8331         {
8332           tree parms;
8333           location_t saved_input_location;
8334           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8335                                          args, tf_warning_or_error);
8336
8337           saved_input_location = input_location;
8338           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8339           redeclare_class_template (TREE_TYPE (tmpl), parms);
8340           input_location = saved_input_location;
8341           
8342         }
8343
8344       friend_type = TREE_TYPE (tmpl);
8345     }
8346   else
8347     {
8348       /* The friend template has not already been declared.  In this
8349          case, the instantiation of the template class will cause the
8350          injection of this template into the global scope.  */
8351       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8352       if (tmpl == error_mark_node)
8353         return error_mark_node;
8354
8355       /* The new TMPL is not an instantiation of anything, so we
8356          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8357          the new type because that is supposed to be the corresponding
8358          template decl, i.e., TMPL.  */
8359       DECL_USE_TEMPLATE (tmpl) = 0;
8360       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8361       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8362       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8363         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8364
8365       /* Inject this template into the global scope.  */
8366       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8367     }
8368
8369   if (context != global_namespace)
8370     {
8371       if (TREE_CODE (context) == NAMESPACE_DECL)
8372         pop_nested_namespace (context);
8373       else
8374         pop_nested_class ();
8375     }
8376
8377   return friend_type;
8378 }
8379
8380 /* Returns zero if TYPE cannot be completed later due to circularity.
8381    Otherwise returns one.  */
8382
8383 static int
8384 can_complete_type_without_circularity (tree type)
8385 {
8386   if (type == NULL_TREE || type == error_mark_node)
8387     return 0;
8388   else if (COMPLETE_TYPE_P (type))
8389     return 1;
8390   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8391     return can_complete_type_without_circularity (TREE_TYPE (type));
8392   else if (CLASS_TYPE_P (type)
8393            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8394     return 0;
8395   else
8396     return 1;
8397 }
8398
8399 /* Apply any attributes which had to be deferred until instantiation
8400    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8401    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8402
8403 static void
8404 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8405                                 tree args, tsubst_flags_t complain, tree in_decl)
8406 {
8407   tree last_dep = NULL_TREE;
8408   tree t;
8409   tree *p;
8410
8411   for (t = attributes; t; t = TREE_CHAIN (t))
8412     if (ATTR_IS_DEPENDENT (t))
8413       {
8414         last_dep = t;
8415         attributes = copy_list (attributes);
8416         break;
8417       }
8418
8419   if (DECL_P (*decl_p))
8420     {
8421       if (TREE_TYPE (*decl_p) == error_mark_node)
8422         return;
8423       p = &DECL_ATTRIBUTES (*decl_p);
8424     }
8425   else
8426     p = &TYPE_ATTRIBUTES (*decl_p);
8427
8428   if (last_dep)
8429     {
8430       tree late_attrs = NULL_TREE;
8431       tree *q = &late_attrs;
8432
8433       for (*p = attributes; *p; )
8434         {
8435           t = *p;
8436           if (ATTR_IS_DEPENDENT (t))
8437             {
8438               *p = TREE_CHAIN (t);
8439               TREE_CHAIN (t) = NULL_TREE;
8440               /* If the first attribute argument is an identifier, don't
8441                  pass it through tsubst.  Attributes like mode, format,
8442                  cleanup and several target specific attributes expect it
8443                  unmodified.  */
8444               if (TREE_VALUE (t)
8445                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8446                   && TREE_VALUE (TREE_VALUE (t))
8447                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8448                       == IDENTIFIER_NODE))
8449                 {
8450                   tree chain
8451                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8452                                    in_decl,
8453                                    /*integral_constant_expression_p=*/false);
8454                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8455                     TREE_VALUE (t)
8456                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8457                                    chain);
8458                 }
8459               else
8460                 TREE_VALUE (t)
8461                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8462                                  /*integral_constant_expression_p=*/false);
8463               *q = t;
8464               q = &TREE_CHAIN (t);
8465             }
8466           else
8467             p = &TREE_CHAIN (t);
8468         }
8469
8470       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8471     }
8472 }
8473
8474 /* Perform (or defer) access check for typedefs that were referenced
8475    from within the template TMPL code.
8476    This is a subroutine of instantiate_template and instantiate_class_template.
8477    TMPL is the template to consider and TARGS is the list of arguments of
8478    that template.  */
8479
8480 static void
8481 perform_typedefs_access_check (tree tmpl, tree targs)
8482 {
8483   location_t saved_location;
8484   int i;
8485   qualified_typedef_usage_t *iter;
8486
8487   if (!tmpl
8488       || (!CLASS_TYPE_P (tmpl)
8489           && TREE_CODE (tmpl) != FUNCTION_DECL))
8490     return;
8491
8492   saved_location = input_location;
8493   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8494                     get_types_needing_access_check (tmpl),
8495                     i, iter)
8496     {
8497       tree type_decl = iter->typedef_decl;
8498       tree type_scope = iter->context;
8499
8500       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8501         continue;
8502
8503       if (uses_template_parms (type_decl))
8504         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8505       if (uses_template_parms (type_scope))
8506         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8507
8508       /* Make access check error messages point to the location
8509          of the use of the typedef.  */
8510       input_location = iter->locus;
8511       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8512                                      type_decl, type_decl);
8513     }
8514     input_location = saved_location;
8515 }
8516
8517 static tree
8518 instantiate_class_template_1 (tree type)
8519 {
8520   tree templ, args, pattern, t, member;
8521   tree typedecl;
8522   tree pbinfo;
8523   tree base_list;
8524   unsigned int saved_maximum_field_alignment;
8525
8526   if (type == error_mark_node)
8527     return error_mark_node;
8528
8529   if (COMPLETE_OR_OPEN_TYPE_P (type)
8530       || uses_template_parms (type))
8531     return type;
8532
8533   /* Figure out which template is being instantiated.  */
8534   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8535   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8536
8537   /* Determine what specialization of the original template to
8538      instantiate.  */
8539   t = most_specialized_class (type, templ, tf_warning_or_error);
8540   if (t == error_mark_node)
8541     {
8542       TYPE_BEING_DEFINED (type) = 1;
8543       return error_mark_node;
8544     }
8545   else if (t)
8546     {
8547       /* This TYPE is actually an instantiation of a partial
8548          specialization.  We replace the innermost set of ARGS with
8549          the arguments appropriate for substitution.  For example,
8550          given:
8551
8552            template <class T> struct S {};
8553            template <class T> struct S<T*> {};
8554
8555          and supposing that we are instantiating S<int*>, ARGS will
8556          presently be {int*} -- but we need {int}.  */
8557       pattern = TREE_TYPE (t);
8558       args = TREE_PURPOSE (t);
8559     }
8560   else
8561     {
8562       pattern = TREE_TYPE (templ);
8563       args = CLASSTYPE_TI_ARGS (type);
8564     }
8565
8566   /* If the template we're instantiating is incomplete, then clearly
8567      there's nothing we can do.  */
8568   if (!COMPLETE_TYPE_P (pattern))
8569     return type;
8570
8571   /* If we've recursively instantiated too many templates, stop.  */
8572   if (! push_tinst_level (type))
8573     return type;
8574
8575   /* Now we're really doing the instantiation.  Mark the type as in
8576      the process of being defined.  */
8577   TYPE_BEING_DEFINED (type) = 1;
8578
8579   /* We may be in the middle of deferred access check.  Disable
8580      it now.  */
8581   push_deferring_access_checks (dk_no_deferred);
8582
8583   push_to_top_level ();
8584   /* Use #pragma pack from the template context.  */
8585   saved_maximum_field_alignment = maximum_field_alignment;
8586   maximum_field_alignment = TYPE_PRECISION (pattern);
8587
8588   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8589
8590   /* Set the input location to the most specialized template definition.
8591      This is needed if tsubsting causes an error.  */
8592   typedecl = TYPE_MAIN_DECL (pattern);
8593   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8594     DECL_SOURCE_LOCATION (typedecl);
8595
8596   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8597   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8598   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8599   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8600   if (ANON_AGGR_TYPE_P (pattern))
8601     SET_ANON_AGGR_TYPE_P (type);
8602   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8603     {
8604       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8605       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8606     }
8607   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8608
8609   pbinfo = TYPE_BINFO (pattern);
8610
8611   /* We should never instantiate a nested class before its enclosing
8612      class; we need to look up the nested class by name before we can
8613      instantiate it, and that lookup should instantiate the enclosing
8614      class.  */
8615   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8616               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8617
8618   base_list = NULL_TREE;
8619   if (BINFO_N_BASE_BINFOS (pbinfo))
8620     {
8621       tree pbase_binfo;
8622       tree pushed_scope;
8623       int i;
8624
8625       /* We must enter the scope containing the type, as that is where
8626          the accessibility of types named in dependent bases are
8627          looked up from.  */
8628       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8629
8630       /* Substitute into each of the bases to determine the actual
8631          basetypes.  */
8632       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8633         {
8634           tree base;
8635           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8636           tree expanded_bases = NULL_TREE;
8637           int idx, len = 1;
8638
8639           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8640             {
8641               expanded_bases = 
8642                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8643                                        args, tf_error, NULL_TREE);
8644               if (expanded_bases == error_mark_node)
8645                 continue;
8646
8647               len = TREE_VEC_LENGTH (expanded_bases);
8648             }
8649
8650           for (idx = 0; idx < len; idx++)
8651             {
8652               if (expanded_bases)
8653                 /* Extract the already-expanded base class.  */
8654                 base = TREE_VEC_ELT (expanded_bases, idx);
8655               else
8656                 /* Substitute to figure out the base class.  */
8657                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8658                                NULL_TREE);
8659
8660               if (base == error_mark_node)
8661                 continue;
8662
8663               base_list = tree_cons (access, base, base_list);
8664               if (BINFO_VIRTUAL_P (pbase_binfo))
8665                 TREE_TYPE (base_list) = integer_type_node;
8666             }
8667         }
8668
8669       /* The list is now in reverse order; correct that.  */
8670       base_list = nreverse (base_list);
8671
8672       if (pushed_scope)
8673         pop_scope (pushed_scope);
8674     }
8675   /* Now call xref_basetypes to set up all the base-class
8676      information.  */
8677   xref_basetypes (type, base_list);
8678
8679   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8680                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8681                                   args, tf_error, NULL_TREE);
8682   fixup_attribute_variants (type);
8683
8684   /* Now that our base classes are set up, enter the scope of the
8685      class, so that name lookups into base classes, etc. will work
8686      correctly.  This is precisely analogous to what we do in
8687      begin_class_definition when defining an ordinary non-template
8688      class, except we also need to push the enclosing classes.  */
8689   push_nested_class (type);
8690
8691   /* Now members are processed in the order of declaration.  */
8692   for (member = CLASSTYPE_DECL_LIST (pattern);
8693        member; member = TREE_CHAIN (member))
8694     {
8695       tree t = TREE_VALUE (member);
8696
8697       if (TREE_PURPOSE (member))
8698         {
8699           if (TYPE_P (t))
8700             {
8701               /* Build new CLASSTYPE_NESTED_UTDS.  */
8702
8703               tree newtag;
8704               bool class_template_p;
8705
8706               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8707                                   && TYPE_LANG_SPECIFIC (t)
8708                                   && CLASSTYPE_IS_TEMPLATE (t));
8709               /* If the member is a class template, then -- even after
8710                  substitution -- there may be dependent types in the
8711                  template argument list for the class.  We increment
8712                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8713                  that function will assume that no types are dependent
8714                  when outside of a template.  */
8715               if (class_template_p)
8716                 ++processing_template_decl;
8717               newtag = tsubst (t, args, tf_error, NULL_TREE);
8718               if (class_template_p)
8719                 --processing_template_decl;
8720               if (newtag == error_mark_node)
8721                 continue;
8722
8723               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8724                 {
8725                   tree name = TYPE_IDENTIFIER (t);
8726
8727                   if (class_template_p)
8728                     /* Unfortunately, lookup_template_class sets
8729                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8730                        instantiation (i.e., for the type of a member
8731                        template class nested within a template class.)
8732                        This behavior is required for
8733                        maybe_process_partial_specialization to work
8734                        correctly, but is not accurate in this case;
8735                        the TAG is not an instantiation of anything.
8736                        (The corresponding TEMPLATE_DECL is an
8737                        instantiation, but the TYPE is not.) */
8738                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8739
8740                   /* Now, we call pushtag to put this NEWTAG into the scope of
8741                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8742                      pushtag calling push_template_decl.  We don't have to do
8743                      this for enums because it will already have been done in
8744                      tsubst_enum.  */
8745                   if (name)
8746                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8747                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8748                 }
8749             }
8750           else if (TREE_CODE (t) == FUNCTION_DECL
8751                    || DECL_FUNCTION_TEMPLATE_P (t))
8752             {
8753               /* Build new TYPE_METHODS.  */
8754               tree r;
8755
8756               if (TREE_CODE (t) == TEMPLATE_DECL)
8757                 ++processing_template_decl;
8758               r = tsubst (t, args, tf_error, NULL_TREE);
8759               if (TREE_CODE (t) == TEMPLATE_DECL)
8760                 --processing_template_decl;
8761               set_current_access_from_decl (r);
8762               finish_member_declaration (r);
8763               /* Instantiate members marked with attribute used.  */
8764               if (r != error_mark_node && DECL_PRESERVE_P (r))
8765                 mark_used (r);
8766             }
8767           else
8768             {
8769               /* Build new TYPE_FIELDS.  */
8770               if (TREE_CODE (t) == STATIC_ASSERT)
8771                 {
8772                   tree condition = 
8773                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8774                                  tf_warning_or_error, NULL_TREE,
8775                                  /*integral_constant_expression_p=*/true);
8776                   finish_static_assert (condition,
8777                                         STATIC_ASSERT_MESSAGE (t), 
8778                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8779                                         /*member_p=*/true);
8780                 }
8781               else if (TREE_CODE (t) != CONST_DECL)
8782                 {
8783                   tree r;
8784
8785                   /* The file and line for this declaration, to
8786                      assist in error message reporting.  Since we
8787                      called push_tinst_level above, we don't need to
8788                      restore these.  */
8789                   input_location = DECL_SOURCE_LOCATION (t);
8790
8791                   if (TREE_CODE (t) == TEMPLATE_DECL)
8792                     ++processing_template_decl;
8793                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8794                   if (TREE_CODE (t) == TEMPLATE_DECL)
8795                     --processing_template_decl;
8796                   if (TREE_CODE (r) == VAR_DECL)
8797                     {
8798                       /* In [temp.inst]:
8799
8800                            [t]he initialization (and any associated
8801                            side-effects) of a static data member does
8802                            not occur unless the static data member is
8803                            itself used in a way that requires the
8804                            definition of the static data member to
8805                            exist.
8806
8807                          Therefore, we do not substitute into the
8808                          initialized for the static data member here.  */
8809                       finish_static_data_member_decl
8810                         (r,
8811                          /*init=*/NULL_TREE,
8812                          /*init_const_expr_p=*/false,
8813                          /*asmspec_tree=*/NULL_TREE,
8814                          /*flags=*/0);
8815                       /* Instantiate members marked with attribute used.  */
8816                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8817                         mark_used (r);
8818                     }
8819                   else if (TREE_CODE (r) == FIELD_DECL)
8820                     {
8821                       /* Determine whether R has a valid type and can be
8822                          completed later.  If R is invalid, then it is
8823                          replaced by error_mark_node so that it will not be
8824                          added to TYPE_FIELDS.  */
8825                       tree rtype = TREE_TYPE (r);
8826                       if (can_complete_type_without_circularity (rtype))
8827                         complete_type (rtype);
8828
8829                       if (!COMPLETE_TYPE_P (rtype))
8830                         {
8831                           cxx_incomplete_type_error (r, rtype);
8832                           r = error_mark_node;
8833                         }
8834                     }
8835
8836                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8837                      such a thing will already have been added to the field
8838                      list by tsubst_enum in finish_member_declaration in the
8839                      CLASSTYPE_NESTED_UTDS case above.  */
8840                   if (!(TREE_CODE (r) == TYPE_DECL
8841                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8842                         && DECL_ARTIFICIAL (r)))
8843                     {
8844                       set_current_access_from_decl (r);
8845                       finish_member_declaration (r);
8846                     }
8847                 }
8848             }
8849         }
8850       else
8851         {
8852           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8853             {
8854               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8855
8856               tree friend_type = t;
8857               bool adjust_processing_template_decl = false;
8858
8859               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8860                 {
8861                   /* template <class T> friend class C;  */
8862                   friend_type = tsubst_friend_class (friend_type, args);
8863                   adjust_processing_template_decl = true;
8864                 }
8865               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8866                 {
8867                   /* template <class T> friend class C::D;  */
8868                   friend_type = tsubst (friend_type, args,
8869                                         tf_warning_or_error, NULL_TREE);
8870                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8871                     friend_type = TREE_TYPE (friend_type);
8872                   adjust_processing_template_decl = true;
8873                 }
8874               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8875                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8876                 {
8877                   /* This could be either
8878
8879                        friend class T::C;
8880
8881                      when dependent_type_p is false or
8882
8883                        template <class U> friend class T::C;
8884
8885                      otherwise.  */
8886                   friend_type = tsubst (friend_type, args,
8887                                         tf_warning_or_error, NULL_TREE);
8888                   /* Bump processing_template_decl for correct
8889                      dependent_type_p calculation.  */
8890                   ++processing_template_decl;
8891                   if (dependent_type_p (friend_type))
8892                     adjust_processing_template_decl = true;
8893                   --processing_template_decl;
8894                 }
8895               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8896                        && hidden_name_p (TYPE_NAME (friend_type)))
8897                 {
8898                   /* friend class C;
8899
8900                      where C hasn't been declared yet.  Let's lookup name
8901                      from namespace scope directly, bypassing any name that
8902                      come from dependent base class.  */
8903                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8904
8905                   /* The call to xref_tag_from_type does injection for friend
8906                      classes.  */
8907                   push_nested_namespace (ns);
8908                   friend_type =
8909                     xref_tag_from_type (friend_type, NULL_TREE,
8910                                         /*tag_scope=*/ts_current);
8911                   pop_nested_namespace (ns);
8912                 }
8913               else if (uses_template_parms (friend_type))
8914                 /* friend class C<T>;  */
8915                 friend_type = tsubst (friend_type, args,
8916                                       tf_warning_or_error, NULL_TREE);
8917               /* Otherwise it's
8918
8919                    friend class C;
8920
8921                  where C is already declared or
8922
8923                    friend class C<int>;
8924
8925                  We don't have to do anything in these cases.  */
8926
8927               if (adjust_processing_template_decl)
8928                 /* Trick make_friend_class into realizing that the friend
8929                    we're adding is a template, not an ordinary class.  It's
8930                    important that we use make_friend_class since it will
8931                    perform some error-checking and output cross-reference
8932                    information.  */
8933                 ++processing_template_decl;
8934
8935               if (friend_type != error_mark_node)
8936                 make_friend_class (type, friend_type, /*complain=*/false);
8937
8938               if (adjust_processing_template_decl)
8939                 --processing_template_decl;
8940             }
8941           else
8942             {
8943               /* Build new DECL_FRIENDLIST.  */
8944               tree r;
8945
8946               /* The file and line for this declaration, to
8947                  assist in error message reporting.  Since we
8948                  called push_tinst_level above, we don't need to
8949                  restore these.  */
8950               input_location = DECL_SOURCE_LOCATION (t);
8951
8952               if (TREE_CODE (t) == TEMPLATE_DECL)
8953                 {
8954                   ++processing_template_decl;
8955                   push_deferring_access_checks (dk_no_check);
8956                 }
8957
8958               r = tsubst_friend_function (t, args);
8959               add_friend (type, r, /*complain=*/false);
8960               if (TREE_CODE (t) == TEMPLATE_DECL)
8961                 {
8962                   pop_deferring_access_checks ();
8963                   --processing_template_decl;
8964                 }
8965             }
8966         }
8967     }
8968
8969   if (CLASSTYPE_LAMBDA_EXPR (type))
8970     {
8971       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8972       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8973         {
8974           apply_lambda_return_type (lambda, void_type_node);
8975           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8976         }
8977       instantiate_decl (lambda_function (type), false, false);
8978       maybe_add_lambda_conv_op (type);
8979     }
8980
8981   /* Set the file and line number information to whatever is given for
8982      the class itself.  This puts error messages involving generated
8983      implicit functions at a predictable point, and the same point
8984      that would be used for non-template classes.  */
8985   input_location = DECL_SOURCE_LOCATION (typedecl);
8986
8987   unreverse_member_declarations (type);
8988   finish_struct_1 (type);
8989   TYPE_BEING_DEFINED (type) = 0;
8990
8991   /* We don't instantiate default arguments for member functions.  14.7.1:
8992
8993      The implicit instantiation of a class template specialization causes
8994      the implicit instantiation of the declarations, but not of the
8995      definitions or default arguments, of the class member functions,
8996      member classes, static data members and member templates....  */
8997
8998   /* Some typedefs referenced from within the template code need to be access
8999      checked at template instantiation time, i.e now. These types were
9000      added to the template at parsing time. Let's get those and perform
9001      the access checks then.  */
9002   perform_typedefs_access_check (pattern, args);
9003   perform_deferred_access_checks ();
9004   pop_nested_class ();
9005   maximum_field_alignment = saved_maximum_field_alignment;
9006   pop_from_top_level ();
9007   pop_deferring_access_checks ();
9008   pop_tinst_level ();
9009
9010   /* The vtable for a template class can be emitted in any translation
9011      unit in which the class is instantiated.  When there is no key
9012      method, however, finish_struct_1 will already have added TYPE to
9013      the keyed_classes list.  */
9014   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9015     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9016
9017   return type;
9018 }
9019
9020 /* Wrapper for instantiate_class_template_1.  */
9021
9022 tree
9023 instantiate_class_template (tree type)
9024 {
9025   tree ret;
9026   timevar_push (TV_TEMPLATE_INST);
9027   ret = instantiate_class_template_1 (type);
9028   timevar_pop (TV_TEMPLATE_INST);
9029   return ret;
9030 }
9031
9032 static tree
9033 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9034 {
9035   tree r;
9036
9037   if (!t)
9038     r = t;
9039   else if (TYPE_P (t))
9040     r = tsubst (t, args, complain, in_decl);
9041   else
9042     {
9043       if (!(complain & tf_warning))
9044         ++c_inhibit_evaluation_warnings;
9045       r = tsubst_expr (t, args, complain, in_decl,
9046                        /*integral_constant_expression_p=*/true);
9047       if (!(complain & tf_warning))
9048         --c_inhibit_evaluation_warnings;
9049       /* Preserve the raw-reference nature of T.  */
9050       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9051           && REFERENCE_REF_P (r))
9052         r = TREE_OPERAND (r, 0);
9053     }
9054   return r;
9055 }
9056
9057 /* Given a function parameter pack TMPL_PARM and some function parameters
9058    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9059    and set *SPEC_P to point at the next point in the list.  */
9060
9061 static tree
9062 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9063 {
9064   /* Collect all of the extra "packed" parameters into an
9065      argument pack.  */
9066   tree parmvec;
9067   tree parmtypevec;
9068   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9069   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9070   tree spec_parm = *spec_p;
9071   int i, len;
9072
9073   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9074     if (tmpl_parm
9075         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9076       break;
9077
9078   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9079   parmvec = make_tree_vec (len);
9080   parmtypevec = make_tree_vec (len);
9081   spec_parm = *spec_p;
9082   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9083     {
9084       TREE_VEC_ELT (parmvec, i) = spec_parm;
9085       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9086     }
9087
9088   /* Build the argument packs.  */
9089   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9090   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9091   TREE_TYPE (argpack) = argtypepack;
9092   *spec_p = spec_parm;
9093
9094   return argpack;
9095 }
9096
9097 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9098    NONTYPE_ARGUMENT_PACK.  */
9099
9100 static tree
9101 make_fnparm_pack (tree spec_parm)
9102 {
9103   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9104 }
9105
9106 /* Substitute ARGS into T, which is an pack expansion
9107    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9108    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9109    (if only a partial substitution could be performed) or
9110    ERROR_MARK_NODE if there was an error.  */
9111 tree
9112 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9113                        tree in_decl)
9114 {
9115   tree pattern;
9116   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
9117   int i, len = -1;
9118   tree result;
9119   int incomplete = 0;
9120   htab_t saved_local_specializations = NULL;
9121
9122   gcc_assert (PACK_EXPANSION_P (t));
9123   pattern = PACK_EXPANSION_PATTERN (t);
9124
9125   /* Determine the argument packs that will instantiate the parameter
9126      packs used in the expansion expression. While we're at it,
9127      compute the number of arguments to be expanded and make sure it
9128      is consistent.  */
9129   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9130        pack = TREE_CHAIN (pack))
9131     {
9132       tree parm_pack = TREE_VALUE (pack);
9133       tree arg_pack = NULL_TREE;
9134       tree orig_arg = NULL_TREE;
9135
9136       if (TREE_CODE (parm_pack) == PARM_DECL)
9137         {
9138           if (!cp_unevaluated_operand)
9139             arg_pack = retrieve_local_specialization (parm_pack);
9140           else
9141             {
9142               /* We can't rely on local_specializations for a parameter
9143                  name used later in a function declaration (such as in a
9144                  late-specified return type).  Even if it exists, it might
9145                  have the wrong value for a recursive call.  Just make a
9146                  dummy decl, since it's only used for its type.  */
9147               arg_pack = tsubst_decl (parm_pack, args, complain);
9148               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9149                 /* Partial instantiation of the parm_pack, we can't build
9150                    up an argument pack yet.  */
9151                 arg_pack = NULL_TREE;
9152               else
9153                 arg_pack = make_fnparm_pack (arg_pack);
9154             }
9155         }
9156       else
9157         {
9158           int level, idx, levels;
9159           template_parm_level_and_index (parm_pack, &level, &idx);
9160
9161           levels = TMPL_ARGS_DEPTH (args);
9162           if (level <= levels)
9163             arg_pack = TMPL_ARG (args, level, idx);
9164         }
9165
9166       orig_arg = arg_pack;
9167       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9168         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9169       
9170       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9171         /* This can only happen if we forget to expand an argument
9172            pack somewhere else. Just return an error, silently.  */
9173         {
9174           result = make_tree_vec (1);
9175           TREE_VEC_ELT (result, 0) = error_mark_node;
9176           return result;
9177         }
9178
9179       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9180         /* The argument pack that the parameter maps to is just an
9181            expansion of the parameter itself, such as one would find
9182            in the implicit typedef of a class inside the class itself.
9183            Consider this parameter "unsubstituted", so that we will
9184            maintain the outer pack expansion.  */
9185         arg_pack = NULL_TREE;
9186           
9187       if (arg_pack)
9188         {
9189           int my_len = 
9190             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9191
9192           /* It's all-or-nothing with incomplete argument packs.  */
9193           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9194             return error_mark_node;
9195           
9196           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9197             incomplete = 1;
9198
9199           if (len < 0)
9200             len = my_len;
9201           else if (len != my_len)
9202             {
9203               if (incomplete)
9204                 /* We got explicit args for some packs but not others;
9205                    do nothing now and try again after deduction.  */
9206                 return t;
9207               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9208                 error ("mismatched argument pack lengths while expanding "
9209                        "%<%T%>",
9210                        pattern);
9211               else
9212                 error ("mismatched argument pack lengths while expanding "
9213                        "%<%E%>",
9214                        pattern);
9215               return error_mark_node;
9216             }
9217
9218           /* Keep track of the parameter packs and their corresponding
9219              argument packs.  */
9220           packs = tree_cons (parm_pack, arg_pack, packs);
9221           TREE_TYPE (packs) = orig_arg;
9222         }
9223       else
9224         /* We can't substitute for this parameter pack.  */
9225         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
9226                                          TREE_VALUE (pack),
9227                                          unsubstituted_packs);
9228     }
9229
9230   /* We cannot expand this expansion expression, because we don't have
9231      all of the argument packs we need. Substitute into the pattern
9232      and return a PACK_EXPANSION_*. The caller will need to deal with
9233      that.  */
9234   if (unsubstituted_packs)
9235     {
9236       tree new_pat;
9237       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9238         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9239                                /*integral_constant_expression_p=*/false);
9240       else
9241         new_pat = tsubst (pattern, args, complain, in_decl);
9242       return make_pack_expansion (new_pat);
9243     }
9244
9245   /* We could not find any argument packs that work.  */
9246   if (len < 0)
9247     return error_mark_node;
9248
9249   if (cp_unevaluated_operand)
9250     {
9251       /* We're in a late-specified return type, so create our own local
9252          specializations table; the current table is either NULL or (in the
9253          case of recursive unification) might have bindings that we don't
9254          want to use or alter.  */
9255       saved_local_specializations = local_specializations;
9256       local_specializations = htab_create (37,
9257                                            hash_local_specialization,
9258                                            eq_local_specializations,
9259                                            NULL);
9260     }
9261
9262   /* For each argument in each argument pack, substitute into the
9263      pattern.  */
9264   result = make_tree_vec (len + incomplete);
9265   for (i = 0; i < len + incomplete; ++i)
9266     {
9267       /* For parameter pack, change the substitution of the parameter
9268          pack to the ith argument in its argument pack, then expand
9269          the pattern.  */
9270       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9271         {
9272           tree parm = TREE_PURPOSE (pack);
9273
9274           if (TREE_CODE (parm) == PARM_DECL)
9275             {
9276               /* Select the Ith argument from the pack.  */
9277               tree arg = make_node (ARGUMENT_PACK_SELECT);
9278               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9279               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9280               mark_used (parm);
9281               register_local_specialization (arg, parm);
9282             }
9283           else
9284             {
9285               tree value = parm;
9286               int idx, level;
9287               template_parm_level_and_index (parm, &level, &idx);
9288               
9289               if (i < len) 
9290                 {
9291                   /* Select the Ith argument from the pack. */
9292                   value = make_node (ARGUMENT_PACK_SELECT);
9293                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
9294                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
9295                 }
9296
9297               /* Update the corresponding argument.  */
9298               TMPL_ARG (args, level, idx) = value;
9299             }
9300         }
9301
9302       /* Substitute into the PATTERN with the altered arguments.  */
9303       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9304         TREE_VEC_ELT (result, i) = 
9305           tsubst_expr (pattern, args, complain, in_decl,
9306                        /*integral_constant_expression_p=*/false);
9307       else
9308         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9309
9310       if (i == len)
9311         /* When we have incomplete argument packs, the last "expanded"
9312            result is itself a pack expansion, which allows us
9313            to deduce more arguments.  */
9314         TREE_VEC_ELT (result, i) = 
9315           make_pack_expansion (TREE_VEC_ELT (result, i));
9316
9317       if (TREE_VEC_ELT (result, i) == error_mark_node)
9318         {
9319           result = error_mark_node;
9320           break;
9321         }
9322     }
9323
9324   /* Update ARGS to restore the substitution from parameter packs to
9325      their argument packs.  */
9326   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9327     {
9328       tree parm = TREE_PURPOSE (pack);
9329
9330       if (TREE_CODE (parm) == PARM_DECL)
9331         register_local_specialization (TREE_TYPE (pack), parm);
9332       else
9333         {
9334           int idx, level;
9335           template_parm_level_and_index (parm, &level, &idx);
9336           
9337           /* Update the corresponding argument.  */
9338           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9339             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9340               TREE_TYPE (pack);
9341           else
9342             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9343         }
9344     }
9345
9346   if (saved_local_specializations)
9347     {
9348       htab_delete (local_specializations);
9349       local_specializations = saved_local_specializations;
9350     }
9351   
9352   return result;
9353 }
9354
9355 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9356    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9357    parameter packs; all parms generated from a function parameter pack will
9358    have the same DECL_PARM_INDEX.  */
9359
9360 tree
9361 get_pattern_parm (tree parm, tree tmpl)
9362 {
9363   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9364   tree patparm;
9365
9366   if (DECL_ARTIFICIAL (parm))
9367     {
9368       for (patparm = DECL_ARGUMENTS (pattern);
9369            patparm; patparm = DECL_CHAIN (patparm))
9370         if (DECL_ARTIFICIAL (patparm)
9371             && DECL_NAME (parm) == DECL_NAME (patparm))
9372           break;
9373     }
9374   else
9375     {
9376       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9377       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9378       gcc_assert (DECL_PARM_INDEX (patparm)
9379                   == DECL_PARM_INDEX (parm));
9380     }
9381
9382   return patparm;
9383 }
9384
9385 /* Substitute ARGS into the vector or list of template arguments T.  */
9386
9387 static tree
9388 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9389 {
9390   tree orig_t = t;
9391   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9392   tree *elts;
9393
9394   if (t == error_mark_node)
9395     return error_mark_node;
9396
9397   len = TREE_VEC_LENGTH (t);
9398   elts = XALLOCAVEC (tree, len);
9399
9400   for (i = 0; i < len; i++)
9401     {
9402       tree orig_arg = TREE_VEC_ELT (t, i);
9403       tree new_arg;
9404
9405       if (TREE_CODE (orig_arg) == TREE_VEC)
9406         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9407       else if (PACK_EXPANSION_P (orig_arg))
9408         {
9409           /* Substitute into an expansion expression.  */
9410           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9411
9412           if (TREE_CODE (new_arg) == TREE_VEC)
9413             /* Add to the expanded length adjustment the number of
9414                expanded arguments. We subtract one from this
9415                measurement, because the argument pack expression
9416                itself is already counted as 1 in
9417                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9418                the argument pack is empty.  */
9419             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9420         }
9421       else if (ARGUMENT_PACK_P (orig_arg))
9422         {
9423           /* Substitute into each of the arguments.  */
9424           new_arg = TYPE_P (orig_arg)
9425             ? cxx_make_type (TREE_CODE (orig_arg))
9426             : make_node (TREE_CODE (orig_arg));
9427           
9428           SET_ARGUMENT_PACK_ARGS (
9429             new_arg,
9430             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9431                                   args, complain, in_decl));
9432
9433           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9434             new_arg = error_mark_node;
9435
9436           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9437             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9438                                           complain, in_decl);
9439             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9440
9441             if (TREE_TYPE (new_arg) == error_mark_node)
9442               new_arg = error_mark_node;
9443           }
9444         }
9445       else
9446         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9447
9448       if (new_arg == error_mark_node)
9449         return error_mark_node;
9450
9451       elts[i] = new_arg;
9452       if (new_arg != orig_arg)
9453         need_new = 1;
9454     }
9455
9456   if (!need_new)
9457     return t;
9458
9459   /* Make space for the expanded arguments coming from template
9460      argument packs.  */
9461   t = make_tree_vec (len + expanded_len_adjust);
9462   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9463      arguments for a member template.
9464      In that case each TREE_VEC in ORIG_T represents a level of template
9465      arguments, and ORIG_T won't carry any non defaulted argument count.
9466      It will rather be the nested TREE_VECs that will carry one.
9467      In other words, ORIG_T carries a non defaulted argument count only
9468      if it doesn't contain any nested TREE_VEC.  */
9469   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9470     {
9471       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9472       count += expanded_len_adjust;
9473       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9474     }
9475   for (i = 0, out = 0; i < len; i++)
9476     {
9477       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9478            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9479           && TREE_CODE (elts[i]) == TREE_VEC)
9480         {
9481           int idx;
9482
9483           /* Now expand the template argument pack "in place".  */
9484           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9485             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9486         }
9487       else
9488         {
9489           TREE_VEC_ELT (t, out) = elts[i];
9490           out++;
9491         }
9492     }
9493
9494   return t;
9495 }
9496
9497 /* Return the result of substituting ARGS into the template parameters
9498    given by PARMS.  If there are m levels of ARGS and m + n levels of
9499    PARMS, then the result will contain n levels of PARMS.  For
9500    example, if PARMS is `template <class T> template <class U>
9501    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9502    result will be `template <int*, double, class V>'.  */
9503
9504 static tree
9505 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9506 {
9507   tree r = NULL_TREE;
9508   tree* new_parms;
9509
9510   /* When substituting into a template, we must set
9511      PROCESSING_TEMPLATE_DECL as the template parameters may be
9512      dependent if they are based on one-another, and the dependency
9513      predicates are short-circuit outside of templates.  */
9514   ++processing_template_decl;
9515
9516   for (new_parms = &r;
9517        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9518        new_parms = &(TREE_CHAIN (*new_parms)),
9519          parms = TREE_CHAIN (parms))
9520     {
9521       tree new_vec =
9522         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9523       int i;
9524
9525       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9526         {
9527           tree tuple;
9528
9529           if (parms == error_mark_node)
9530             continue;
9531
9532           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9533
9534           if (tuple == error_mark_node)
9535             continue;
9536
9537           TREE_VEC_ELT (new_vec, i) =
9538             tsubst_template_parm (tuple, args, complain);
9539         }
9540
9541       *new_parms =
9542         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9543                              - TMPL_ARGS_DEPTH (args)),
9544                    new_vec, NULL_TREE);
9545     }
9546
9547   --processing_template_decl;
9548
9549   return r;
9550 }
9551
9552 /* Return the result of substituting ARGS into one template parameter
9553    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9554    parameter and which TREE_PURPOSE is the default argument of the
9555    template parameter.  */
9556
9557 static tree
9558 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9559 {
9560   tree default_value, parm_decl;
9561
9562   if (args == NULL_TREE
9563       || t == NULL_TREE
9564       || t == error_mark_node)
9565     return t;
9566
9567   gcc_assert (TREE_CODE (t) == TREE_LIST);
9568
9569   default_value = TREE_PURPOSE (t);
9570   parm_decl = TREE_VALUE (t);
9571
9572   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9573   if (TREE_CODE (parm_decl) == PARM_DECL
9574       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9575     parm_decl = error_mark_node;
9576   default_value = tsubst_template_arg (default_value, args,
9577                                        complain, NULL_TREE);
9578
9579   return build_tree_list (default_value, parm_decl);
9580 }
9581
9582 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9583    type T.  If T is not an aggregate or enumeration type, it is
9584    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9585    ENTERING_SCOPE is nonzero, T is the context for a template which
9586    we are presently tsubst'ing.  Return the substituted value.  */
9587
9588 static tree
9589 tsubst_aggr_type (tree t,
9590                   tree args,
9591                   tsubst_flags_t complain,
9592                   tree in_decl,
9593                   int entering_scope)
9594 {
9595   if (t == NULL_TREE)
9596     return NULL_TREE;
9597
9598   switch (TREE_CODE (t))
9599     {
9600     case RECORD_TYPE:
9601       if (TYPE_PTRMEMFUNC_P (t))
9602         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9603
9604       /* Else fall through.  */
9605     case ENUMERAL_TYPE:
9606     case UNION_TYPE:
9607       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9608         {
9609           tree argvec;
9610           tree context;
9611           tree r;
9612           int saved_unevaluated_operand;
9613           int saved_inhibit_evaluation_warnings;
9614
9615           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9616           saved_unevaluated_operand = cp_unevaluated_operand;
9617           cp_unevaluated_operand = 0;
9618           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9619           c_inhibit_evaluation_warnings = 0;
9620
9621           /* First, determine the context for the type we are looking
9622              up.  */
9623           context = TYPE_CONTEXT (t);
9624           if (context && TYPE_P (context))
9625             {
9626               context = tsubst_aggr_type (context, args, complain,
9627                                           in_decl, /*entering_scope=*/1);
9628               /* If context is a nested class inside a class template,
9629                  it may still need to be instantiated (c++/33959).  */
9630               context = complete_type (context);
9631             }
9632
9633           /* Then, figure out what arguments are appropriate for the
9634              type we are trying to find.  For example, given:
9635
9636                template <class T> struct S;
9637                template <class T, class U> void f(T, U) { S<U> su; }
9638
9639              and supposing that we are instantiating f<int, double>,
9640              then our ARGS will be {int, double}, but, when looking up
9641              S we only want {double}.  */
9642           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9643                                          complain, in_decl);
9644           if (argvec == error_mark_node)
9645             r = error_mark_node;
9646           else
9647             {
9648               r = lookup_template_class (t, argvec, in_decl, context,
9649                                          entering_scope, complain);
9650               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9651             }
9652
9653           cp_unevaluated_operand = saved_unevaluated_operand;
9654           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9655
9656           return r;
9657         }
9658       else
9659         /* This is not a template type, so there's nothing to do.  */
9660         return t;
9661
9662     default:
9663       return tsubst (t, args, complain, in_decl);
9664     }
9665 }
9666
9667 /* Substitute into the default argument ARG (a default argument for
9668    FN), which has the indicated TYPE.  */
9669
9670 tree
9671 tsubst_default_argument (tree fn, tree type, tree arg)
9672 {
9673   tree saved_class_ptr = NULL_TREE;
9674   tree saved_class_ref = NULL_TREE;
9675
9676   /* This can happen in invalid code.  */
9677   if (TREE_CODE (arg) == DEFAULT_ARG)
9678     return arg;
9679
9680   /* This default argument came from a template.  Instantiate the
9681      default argument here, not in tsubst.  In the case of
9682      something like:
9683
9684        template <class T>
9685        struct S {
9686          static T t();
9687          void f(T = t());
9688        };
9689
9690      we must be careful to do name lookup in the scope of S<T>,
9691      rather than in the current class.  */
9692   push_access_scope (fn);
9693   /* The "this" pointer is not valid in a default argument.  */
9694   if (cfun)
9695     {
9696       saved_class_ptr = current_class_ptr;
9697       cp_function_chain->x_current_class_ptr = NULL_TREE;
9698       saved_class_ref = current_class_ref;
9699       cp_function_chain->x_current_class_ref = NULL_TREE;
9700     }
9701
9702   push_deferring_access_checks(dk_no_deferred);
9703   /* The default argument expression may cause implicitly defined
9704      member functions to be synthesized, which will result in garbage
9705      collection.  We must treat this situation as if we were within
9706      the body of function so as to avoid collecting live data on the
9707      stack.  */
9708   ++function_depth;
9709   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9710                      tf_warning_or_error, NULL_TREE,
9711                      /*integral_constant_expression_p=*/false);
9712   --function_depth;
9713   pop_deferring_access_checks();
9714
9715   /* Restore the "this" pointer.  */
9716   if (cfun)
9717     {
9718       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9719       cp_function_chain->x_current_class_ref = saved_class_ref;
9720     }
9721
9722   /* Make sure the default argument is reasonable.  */
9723   arg = check_default_argument (type, arg);
9724
9725   pop_access_scope (fn);
9726
9727   return arg;
9728 }
9729
9730 /* Substitute into all the default arguments for FN.  */
9731
9732 static void
9733 tsubst_default_arguments (tree fn)
9734 {
9735   tree arg;
9736   tree tmpl_args;
9737
9738   tmpl_args = DECL_TI_ARGS (fn);
9739
9740   /* If this function is not yet instantiated, we certainly don't need
9741      its default arguments.  */
9742   if (uses_template_parms (tmpl_args))
9743     return;
9744   /* Don't do this again for clones.  */
9745   if (DECL_CLONED_FUNCTION_P (fn))
9746     return;
9747
9748   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9749        arg;
9750        arg = TREE_CHAIN (arg))
9751     if (TREE_PURPOSE (arg))
9752       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9753                                                     TREE_VALUE (arg),
9754                                                     TREE_PURPOSE (arg));
9755 }
9756
9757 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9758    result of the substitution.  Issue error and warning messages under
9759    control of COMPLAIN.  */
9760
9761 static tree
9762 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9763 {
9764 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9765   location_t saved_loc;
9766   tree r = NULL_TREE;
9767   tree in_decl = t;
9768   hashval_t hash = 0;
9769
9770   /* Set the filename and linenumber to improve error-reporting.  */
9771   saved_loc = input_location;
9772   input_location = DECL_SOURCE_LOCATION (t);
9773
9774   switch (TREE_CODE (t))
9775     {
9776     case TEMPLATE_DECL:
9777       {
9778         /* We can get here when processing a member function template,
9779            member class template, or template template parameter.  */
9780         tree decl = DECL_TEMPLATE_RESULT (t);
9781         tree spec;
9782         tree tmpl_args;
9783         tree full_args;
9784
9785         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9786           {
9787             /* Template template parameter is treated here.  */
9788             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9789             if (new_type == error_mark_node)
9790               RETURN (error_mark_node);
9791
9792             r = copy_decl (t);
9793             DECL_CHAIN (r) = NULL_TREE;
9794             TREE_TYPE (r) = new_type;
9795             DECL_TEMPLATE_RESULT (r)
9796               = build_decl (DECL_SOURCE_LOCATION (decl),
9797                             TYPE_DECL, DECL_NAME (decl), new_type);
9798             DECL_TEMPLATE_PARMS (r)
9799               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9800                                        complain);
9801             TYPE_NAME (new_type) = r;
9802             break;
9803           }
9804
9805         /* We might already have an instance of this template.
9806            The ARGS are for the surrounding class type, so the
9807            full args contain the tsubst'd args for the context,
9808            plus the innermost args from the template decl.  */
9809         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9810           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9811           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9812         /* Because this is a template, the arguments will still be
9813            dependent, even after substitution.  If
9814            PROCESSING_TEMPLATE_DECL is not set, the dependency
9815            predicates will short-circuit.  */
9816         ++processing_template_decl;
9817         full_args = tsubst_template_args (tmpl_args, args,
9818                                           complain, in_decl);
9819         --processing_template_decl;
9820         if (full_args == error_mark_node)
9821           RETURN (error_mark_node);
9822
9823         /* If this is a default template template argument,
9824            tsubst might not have changed anything.  */
9825         if (full_args == tmpl_args)
9826           RETURN (t);
9827
9828         hash = hash_tmpl_and_args (t, full_args);
9829         spec = retrieve_specialization (t, full_args, hash);
9830         if (spec != NULL_TREE)
9831           {
9832             r = spec;
9833             break;
9834           }
9835
9836         /* Make a new template decl.  It will be similar to the
9837            original, but will record the current template arguments.
9838            We also create a new function declaration, which is just
9839            like the old one, but points to this new template, rather
9840            than the old one.  */
9841         r = copy_decl (t);
9842         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9843         DECL_CHAIN (r) = NULL_TREE;
9844
9845         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9846
9847         if (TREE_CODE (decl) == TYPE_DECL)
9848           {
9849             tree new_type;
9850             ++processing_template_decl;
9851             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9852             --processing_template_decl;
9853             if (new_type == error_mark_node)
9854               RETURN (error_mark_node);
9855
9856             TREE_TYPE (r) = new_type;
9857             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9858             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9859             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9860             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9861           }
9862         else
9863           {
9864             tree new_decl;
9865             ++processing_template_decl;
9866             new_decl = tsubst (decl, args, complain, in_decl);
9867             --processing_template_decl;
9868             if (new_decl == error_mark_node)
9869               RETURN (error_mark_node);
9870
9871             DECL_TEMPLATE_RESULT (r) = new_decl;
9872             DECL_TI_TEMPLATE (new_decl) = r;
9873             TREE_TYPE (r) = TREE_TYPE (new_decl);
9874             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9875             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9876           }
9877
9878         SET_DECL_IMPLICIT_INSTANTIATION (r);
9879         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9880         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9881
9882         /* The template parameters for this new template are all the
9883            template parameters for the old template, except the
9884            outermost level of parameters.  */
9885         DECL_TEMPLATE_PARMS (r)
9886           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9887                                    complain);
9888
9889         if (PRIMARY_TEMPLATE_P (t))
9890           DECL_PRIMARY_TEMPLATE (r) = r;
9891
9892         if (TREE_CODE (decl) != TYPE_DECL)
9893           /* Record this non-type partial instantiation.  */
9894           register_specialization (r, t,
9895                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9896                                    false, hash);
9897       }
9898       break;
9899
9900     case FUNCTION_DECL:
9901       {
9902         tree ctx;
9903         tree argvec = NULL_TREE;
9904         tree *friends;
9905         tree gen_tmpl;
9906         tree type;
9907         int member;
9908         int args_depth;
9909         int parms_depth;
9910
9911         /* Nobody should be tsubst'ing into non-template functions.  */
9912         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9913
9914         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9915           {
9916             tree spec;
9917             bool dependent_p;
9918
9919             /* If T is not dependent, just return it.  We have to
9920                increment PROCESSING_TEMPLATE_DECL because
9921                value_dependent_expression_p assumes that nothing is
9922                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9923             ++processing_template_decl;
9924             dependent_p = value_dependent_expression_p (t);
9925             --processing_template_decl;
9926             if (!dependent_p)
9927               RETURN (t);
9928
9929             /* Calculate the most general template of which R is a
9930                specialization, and the complete set of arguments used to
9931                specialize R.  */
9932             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9933             argvec = tsubst_template_args (DECL_TI_ARGS
9934                                           (DECL_TEMPLATE_RESULT
9935                                                  (DECL_TI_TEMPLATE (t))),
9936                                            args, complain, in_decl);
9937             if (argvec == error_mark_node)
9938               RETURN (error_mark_node);
9939
9940             /* Check to see if we already have this specialization.  */
9941             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9942             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9943
9944             if (spec)
9945               {
9946                 r = spec;
9947                 break;
9948               }
9949
9950             /* We can see more levels of arguments than parameters if
9951                there was a specialization of a member template, like
9952                this:
9953
9954                  template <class T> struct S { template <class U> void f(); }
9955                  template <> template <class U> void S<int>::f(U);
9956
9957                Here, we'll be substituting into the specialization,
9958                because that's where we can find the code we actually
9959                want to generate, but we'll have enough arguments for
9960                the most general template.
9961
9962                We also deal with the peculiar case:
9963
9964                  template <class T> struct S {
9965                    template <class U> friend void f();
9966                  };
9967                  template <class U> void f() {}
9968                  template S<int>;
9969                  template void f<double>();
9970
9971                Here, the ARGS for the instantiation of will be {int,
9972                double}.  But, we only need as many ARGS as there are
9973                levels of template parameters in CODE_PATTERN.  We are
9974                careful not to get fooled into reducing the ARGS in
9975                situations like:
9976
9977                  template <class T> struct S { template <class U> void f(U); }
9978                  template <class T> template <> void S<T>::f(int) {}
9979
9980                which we can spot because the pattern will be a
9981                specialization in this case.  */
9982             args_depth = TMPL_ARGS_DEPTH (args);
9983             parms_depth =
9984               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9985             if (args_depth > parms_depth
9986                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9987               args = get_innermost_template_args (args, parms_depth);
9988           }
9989         else
9990           {
9991             /* This special case arises when we have something like this:
9992
9993                  template <class T> struct S {
9994                    friend void f<int>(int, double);
9995                  };
9996
9997                Here, the DECL_TI_TEMPLATE for the friend declaration
9998                will be an IDENTIFIER_NODE.  We are being called from
9999                tsubst_friend_function, and we want only to create a
10000                new decl (R) with appropriate types so that we can call
10001                determine_specialization.  */
10002             gen_tmpl = NULL_TREE;
10003           }
10004
10005         if (DECL_CLASS_SCOPE_P (t))
10006           {
10007             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10008               member = 2;
10009             else
10010               member = 1;
10011             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10012                                     complain, t, /*entering_scope=*/1);
10013           }
10014         else
10015           {
10016             member = 0;
10017             ctx = DECL_CONTEXT (t);
10018           }
10019         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10020         if (type == error_mark_node)
10021           RETURN (error_mark_node);
10022
10023         /* We do NOT check for matching decls pushed separately at this
10024            point, as they may not represent instantiations of this
10025            template, and in any case are considered separate under the
10026            discrete model.  */
10027         r = copy_decl (t);
10028         DECL_USE_TEMPLATE (r) = 0;
10029         TREE_TYPE (r) = type;
10030         /* Clear out the mangled name and RTL for the instantiation.  */
10031         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10032         SET_DECL_RTL (r, NULL);
10033         /* Leave DECL_INITIAL set on deleted instantiations.  */
10034         if (!DECL_DELETED_FN (r))
10035           DECL_INITIAL (r) = NULL_TREE;
10036         DECL_CONTEXT (r) = ctx;
10037
10038         if (member && DECL_CONV_FN_P (r))
10039           /* Type-conversion operator.  Reconstruct the name, in
10040              case it's the name of one of the template's parameters.  */
10041           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10042
10043         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10044                                      complain, t);
10045         DECL_RESULT (r) = NULL_TREE;
10046
10047         TREE_STATIC (r) = 0;
10048         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10049         DECL_EXTERNAL (r) = 1;
10050         /* If this is an instantiation of a function with internal
10051            linkage, we already know what object file linkage will be
10052            assigned to the instantiation.  */
10053         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10054         DECL_DEFER_OUTPUT (r) = 0;
10055         DECL_CHAIN (r) = NULL_TREE;
10056         DECL_PENDING_INLINE_INFO (r) = 0;
10057         DECL_PENDING_INLINE_P (r) = 0;
10058         DECL_SAVED_TREE (r) = NULL_TREE;
10059         DECL_STRUCT_FUNCTION (r) = NULL;
10060         TREE_USED (r) = 0;
10061         /* We'll re-clone as appropriate in instantiate_template.  */
10062         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10063
10064         /* If we aren't complaining now, return on error before we register
10065            the specialization so that we'll complain eventually.  */
10066         if ((complain & tf_error) == 0
10067             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10068             && !grok_op_properties (r, /*complain=*/false))
10069           RETURN (error_mark_node);
10070
10071         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10072            this in the special friend case mentioned above where
10073            GEN_TMPL is NULL.  */
10074         if (gen_tmpl)
10075           {
10076             DECL_TEMPLATE_INFO (r)
10077               = build_template_info (gen_tmpl, argvec);
10078             SET_DECL_IMPLICIT_INSTANTIATION (r);
10079             register_specialization (r, gen_tmpl, argvec, false, hash);
10080
10081             /* We're not supposed to instantiate default arguments
10082                until they are called, for a template.  But, for a
10083                declaration like:
10084
10085                  template <class T> void f ()
10086                  { extern void g(int i = T()); }
10087
10088                we should do the substitution when the template is
10089                instantiated.  We handle the member function case in
10090                instantiate_class_template since the default arguments
10091                might refer to other members of the class.  */
10092             if (!member
10093                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10094                 && !uses_template_parms (argvec))
10095               tsubst_default_arguments (r);
10096           }
10097         else
10098           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10099
10100         /* Copy the list of befriending classes.  */
10101         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10102              *friends;
10103              friends = &TREE_CHAIN (*friends))
10104           {
10105             *friends = copy_node (*friends);
10106             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10107                                             args, complain,
10108                                             in_decl);
10109           }
10110
10111         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10112           {
10113             maybe_retrofit_in_chrg (r);
10114             if (DECL_CONSTRUCTOR_P (r))
10115               grok_ctor_properties (ctx, r);
10116             /* If this is an instantiation of a member template, clone it.
10117                If it isn't, that'll be handled by
10118                clone_constructors_and_destructors.  */
10119             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10120               clone_function_decl (r, /*update_method_vec_p=*/0);
10121           }
10122         else if ((complain & tf_error) != 0
10123                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10124                  && !grok_op_properties (r, /*complain=*/true))
10125           RETURN (error_mark_node);
10126
10127         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10128           SET_DECL_FRIEND_CONTEXT (r,
10129                                    tsubst (DECL_FRIEND_CONTEXT (t),
10130                                             args, complain, in_decl));
10131
10132         /* Possibly limit visibility based on template args.  */
10133         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10134         if (DECL_VISIBILITY_SPECIFIED (t))
10135           {
10136             DECL_VISIBILITY_SPECIFIED (r) = 0;
10137             DECL_ATTRIBUTES (r)
10138               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10139           }
10140         determine_visibility (r);
10141         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10142             && !processing_template_decl)
10143           defaulted_late_check (r);
10144
10145         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10146                                         args, complain, in_decl);
10147       }
10148       break;
10149
10150     case PARM_DECL:
10151       {
10152         tree type = NULL_TREE;
10153         int i, len = 1;
10154         tree expanded_types = NULL_TREE;
10155         tree prev_r = NULL_TREE;
10156         tree first_r = NULL_TREE;
10157
10158         if (FUNCTION_PARAMETER_PACK_P (t))
10159           {
10160             /* If there is a local specialization that isn't a
10161                parameter pack, it means that we're doing a "simple"
10162                substitution from inside tsubst_pack_expansion. Just
10163                return the local specialization (which will be a single
10164                parm).  */
10165             tree spec = retrieve_local_specialization (t);
10166             if (spec 
10167                 && TREE_CODE (spec) == PARM_DECL
10168                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10169               RETURN (spec);
10170
10171             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10172                the parameters in this function parameter pack.  */
10173             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10174                                                     complain, in_decl);
10175             if (TREE_CODE (expanded_types) == TREE_VEC)
10176               {
10177                 len = TREE_VEC_LENGTH (expanded_types);
10178
10179                 /* Zero-length parameter packs are boring. Just substitute
10180                    into the chain.  */
10181                 if (len == 0)
10182                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10183                                   TREE_CHAIN (t)));
10184               }
10185             else
10186               {
10187                 /* All we did was update the type. Make a note of that.  */
10188                 type = expanded_types;
10189                 expanded_types = NULL_TREE;
10190               }
10191           }
10192
10193         /* Loop through all of the parameter's we'll build. When T is
10194            a function parameter pack, LEN is the number of expanded
10195            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10196         r = NULL_TREE;
10197         for (i = 0; i < len; ++i)
10198           {
10199             prev_r = r;
10200             r = copy_node (t);
10201             if (DECL_TEMPLATE_PARM_P (t))
10202               SET_DECL_TEMPLATE_PARM_P (r);
10203
10204             if (expanded_types)
10205               /* We're on the Ith parameter of the function parameter
10206                  pack.  */
10207               {
10208                 /* An argument of a function parameter pack is not a parameter
10209                    pack.  */
10210                 FUNCTION_PARAMETER_PACK_P (r) = false;
10211
10212                 /* Get the Ith type.  */
10213                 type = TREE_VEC_ELT (expanded_types, i);
10214
10215                 if (DECL_NAME (r))
10216                   /* Rename the parameter to include the index.  */
10217                   DECL_NAME (r) =
10218                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10219               }
10220             else if (!type)
10221               /* We're dealing with a normal parameter.  */
10222               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10223
10224             type = type_decays_to (type);
10225             TREE_TYPE (r) = type;
10226             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10227
10228             if (DECL_INITIAL (r))
10229               {
10230                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10231                   DECL_INITIAL (r) = TREE_TYPE (r);
10232                 else
10233                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10234                                              complain, in_decl);
10235               }
10236
10237             DECL_CONTEXT (r) = NULL_TREE;
10238
10239             if (!DECL_TEMPLATE_PARM_P (r))
10240               DECL_ARG_TYPE (r) = type_passed_as (type);
10241
10242             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10243                                             args, complain, in_decl);
10244
10245             /* Keep track of the first new parameter we
10246                generate. That's what will be returned to the
10247                caller.  */
10248             if (!first_r)
10249               first_r = r;
10250
10251             /* Build a proper chain of parameters when substituting
10252                into a function parameter pack.  */
10253             if (prev_r)
10254               DECL_CHAIN (prev_r) = r;
10255           }
10256
10257         if (DECL_CHAIN (t))
10258           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10259                                    complain, DECL_CHAIN (t));
10260
10261         /* FIRST_R contains the start of the chain we've built.  */
10262         r = first_r;
10263       }
10264       break;
10265
10266     case FIELD_DECL:
10267       {
10268         tree type;
10269
10270         r = copy_decl (t);
10271         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10272         if (type == error_mark_node)
10273           RETURN (error_mark_node);
10274         TREE_TYPE (r) = type;
10275         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10276
10277         if (DECL_C_BIT_FIELD (r))
10278           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10279              non-bit-fields DECL_INITIAL is a non-static data member
10280              initializer, which gets deferred instantiation.  */
10281           DECL_INITIAL (r)
10282             = tsubst_expr (DECL_INITIAL (t), args,
10283                            complain, in_decl,
10284                            /*integral_constant_expression_p=*/true);
10285         /* We don't have to set DECL_CONTEXT here; it is set by
10286            finish_member_declaration.  */
10287         DECL_CHAIN (r) = NULL_TREE;
10288         if (VOID_TYPE_P (type))
10289           error ("instantiation of %q+D as type %qT", r, type);
10290
10291         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10292                                         args, complain, in_decl);
10293       }
10294       break;
10295
10296     case USING_DECL:
10297       /* We reach here only for member using decls.  */
10298       if (DECL_DEPENDENT_P (t))
10299         {
10300           r = do_class_using_decl
10301             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10302              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10303           if (!r)
10304             r = error_mark_node;
10305           else
10306             {
10307               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10308               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10309             }
10310         }
10311       else
10312         {
10313           r = copy_node (t);
10314           DECL_CHAIN (r) = NULL_TREE;
10315         }
10316       break;
10317
10318     case TYPE_DECL:
10319     case VAR_DECL:
10320       {
10321         tree argvec = NULL_TREE;
10322         tree gen_tmpl = NULL_TREE;
10323         tree spec;
10324         tree tmpl = NULL_TREE;
10325         tree ctx;
10326         tree type = NULL_TREE;
10327         bool local_p;
10328
10329         if (TREE_CODE (t) == TYPE_DECL
10330             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10331           {
10332             /* If this is the canonical decl, we don't have to
10333                mess with instantiations, and often we can't (for
10334                typename, template type parms and such).  Note that
10335                TYPE_NAME is not correct for the above test if
10336                we've copied the type for a typedef.  */
10337             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10338             if (type == error_mark_node)
10339               RETURN (error_mark_node);
10340             r = TYPE_NAME (type);
10341             break;
10342           }
10343
10344         /* Check to see if we already have the specialization we
10345            need.  */
10346         spec = NULL_TREE;
10347         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10348           {
10349             /* T is a static data member or namespace-scope entity.
10350                We have to substitute into namespace-scope variables
10351                (even though such entities are never templates) because
10352                of cases like:
10353                
10354                  template <class T> void f() { extern T t; }
10355
10356                where the entity referenced is not known until
10357                instantiation time.  */
10358             local_p = false;
10359             ctx = DECL_CONTEXT (t);
10360             if (DECL_CLASS_SCOPE_P (t))
10361               {
10362                 ctx = tsubst_aggr_type (ctx, args,
10363                                         complain,
10364                                         in_decl, /*entering_scope=*/1);
10365                 /* If CTX is unchanged, then T is in fact the
10366                    specialization we want.  That situation occurs when
10367                    referencing a static data member within in its own
10368                    class.  We can use pointer equality, rather than
10369                    same_type_p, because DECL_CONTEXT is always
10370                    canonical.  */
10371                 if (ctx == DECL_CONTEXT (t))
10372                   spec = t;
10373               }
10374
10375             if (!spec)
10376               {
10377                 tmpl = DECL_TI_TEMPLATE (t);
10378                 gen_tmpl = most_general_template (tmpl);
10379                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10380                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10381                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10382               }
10383           }
10384         else
10385           {
10386             /* A local variable.  */
10387             local_p = true;
10388             /* Subsequent calls to pushdecl will fill this in.  */
10389             ctx = NULL_TREE;
10390             spec = retrieve_local_specialization (t);
10391           }
10392         /* If we already have the specialization we need, there is
10393            nothing more to do.  */ 
10394         if (spec)
10395           {
10396             r = spec;
10397             break;
10398           }
10399
10400         /* Create a new node for the specialization we need.  */
10401         r = copy_decl (t);
10402         if (type == NULL_TREE)
10403           {
10404             if (is_typedef_decl (t))
10405               type = DECL_ORIGINAL_TYPE (t);
10406             else
10407               type = TREE_TYPE (t);
10408             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10409               type = strip_array_domain (type);
10410             type = tsubst (type, args, complain, in_decl);
10411           }
10412         if (TREE_CODE (r) == VAR_DECL)
10413           {
10414             /* Even if the original location is out of scope, the
10415                newly substituted one is not.  */
10416             DECL_DEAD_FOR_LOCAL (r) = 0;
10417             DECL_INITIALIZED_P (r) = 0;
10418             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10419             if (type == error_mark_node)
10420               RETURN (error_mark_node);
10421             if (TREE_CODE (type) == FUNCTION_TYPE)
10422               {
10423                 /* It may seem that this case cannot occur, since:
10424
10425                      typedef void f();
10426                      void g() { f x; }
10427
10428                    declares a function, not a variable.  However:
10429       
10430                      typedef void f();
10431                      template <typename T> void g() { T t; }
10432                      template void g<f>();
10433
10434                    is an attempt to declare a variable with function
10435                    type.  */
10436                 error ("variable %qD has function type",
10437                        /* R is not yet sufficiently initialized, so we
10438                           just use its name.  */
10439                        DECL_NAME (r));
10440                 RETURN (error_mark_node);
10441               }
10442             type = complete_type (type);
10443             /* Wait until cp_finish_decl to set this again, to handle
10444                circular dependency (template/instantiate6.C). */
10445             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10446             type = check_var_type (DECL_NAME (r), type);
10447
10448             if (DECL_HAS_VALUE_EXPR_P (t))
10449               {
10450                 tree ve = DECL_VALUE_EXPR (t);
10451                 ve = tsubst_expr (ve, args, complain, in_decl,
10452                                   /*constant_expression_p=*/false);
10453                 if (REFERENCE_REF_P (ve))
10454                   {
10455                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10456                     ve = TREE_OPERAND (ve, 0);
10457                   }
10458                 SET_DECL_VALUE_EXPR (r, ve);
10459               }
10460           }
10461         else if (DECL_SELF_REFERENCE_P (t))
10462           SET_DECL_SELF_REFERENCE_P (r);
10463         TREE_TYPE (r) = type;
10464         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10465         DECL_CONTEXT (r) = ctx;
10466         /* Clear out the mangled name and RTL for the instantiation.  */
10467         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10468         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10469           SET_DECL_RTL (r, NULL);
10470         /* The initializer must not be expanded until it is required;
10471            see [temp.inst].  */
10472         DECL_INITIAL (r) = NULL_TREE;
10473         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10474           SET_DECL_RTL (r, NULL);
10475         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10476         if (TREE_CODE (r) == VAR_DECL)
10477           {
10478             /* Possibly limit visibility based on template args.  */
10479             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10480             if (DECL_VISIBILITY_SPECIFIED (t))
10481               {
10482                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10483                 DECL_ATTRIBUTES (r)
10484                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10485               }
10486             determine_visibility (r);
10487           }
10488
10489         if (!local_p)
10490           {
10491             /* A static data member declaration is always marked
10492                external when it is declared in-class, even if an
10493                initializer is present.  We mimic the non-template
10494                processing here.  */
10495             DECL_EXTERNAL (r) = 1;
10496
10497             register_specialization (r, gen_tmpl, argvec, false, hash);
10498             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10499             SET_DECL_IMPLICIT_INSTANTIATION (r);
10500           }
10501         else if (cp_unevaluated_operand)
10502           {
10503             /* We're substituting this var in a decltype outside of its
10504                scope, such as for a lambda return type.  Don't add it to
10505                local_specializations, do perform auto deduction.  */
10506             tree auto_node = type_uses_auto (type);
10507             if (auto_node)
10508               {
10509                 tree init
10510                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10511                                  /*constant_expression_p=*/false);
10512                 init = resolve_nondeduced_context (init);
10513                 TREE_TYPE (r) = type
10514                   = do_auto_deduction (type, init, auto_node);
10515               }
10516           }
10517         else
10518           register_local_specialization (r, t);
10519
10520         DECL_CHAIN (r) = NULL_TREE;
10521
10522         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10523                                         /*flags=*/0,
10524                                         args, complain, in_decl);
10525
10526         /* Preserve a typedef that names a type.  */
10527         if (is_typedef_decl (r))
10528           {
10529             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10530             set_underlying_type (r);
10531           }
10532
10533         layout_decl (r, 0);
10534       }
10535       break;
10536
10537     default:
10538       gcc_unreachable ();
10539     }
10540 #undef RETURN
10541
10542  out:
10543   /* Restore the file and line information.  */
10544   input_location = saved_loc;
10545
10546   return r;
10547 }
10548
10549 /* Substitute into the ARG_TYPES of a function type.  */
10550
10551 static tree
10552 tsubst_arg_types (tree arg_types,
10553                   tree args,
10554                   tsubst_flags_t complain,
10555                   tree in_decl)
10556 {
10557   tree remaining_arg_types;
10558   tree type = NULL_TREE;
10559   int i = 1;
10560   tree expanded_args = NULL_TREE;
10561   tree default_arg;
10562
10563   if (!arg_types || arg_types == void_list_node)
10564     return arg_types;
10565
10566   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10567                                           args, complain, in_decl);
10568   if (remaining_arg_types == error_mark_node)
10569     return error_mark_node;
10570
10571   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10572     {
10573       /* For a pack expansion, perform substitution on the
10574          entire expression. Later on, we'll handle the arguments
10575          one-by-one.  */
10576       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10577                                             args, complain, in_decl);
10578
10579       if (TREE_CODE (expanded_args) == TREE_VEC)
10580         /* So that we'll spin through the parameters, one by one.  */
10581         i = TREE_VEC_LENGTH (expanded_args);
10582       else
10583         {
10584           /* We only partially substituted into the parameter
10585              pack. Our type is TYPE_PACK_EXPANSION.  */
10586           type = expanded_args;
10587           expanded_args = NULL_TREE;
10588         }
10589     }
10590
10591   while (i > 0) {
10592     --i;
10593     
10594     if (expanded_args)
10595       type = TREE_VEC_ELT (expanded_args, i);
10596     else if (!type)
10597       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10598
10599     if (type == error_mark_node)
10600       return error_mark_node;
10601     if (VOID_TYPE_P (type))
10602       {
10603         if (complain & tf_error)
10604           {
10605             error ("invalid parameter type %qT", type);
10606             if (in_decl)
10607               error ("in declaration %q+D", in_decl);
10608           }
10609         return error_mark_node;
10610     }
10611     
10612     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10613        top-level qualifiers as required.  */
10614     type = cv_unqualified (type_decays_to (type));
10615
10616     /* We do not substitute into default arguments here.  The standard
10617        mandates that they be instantiated only when needed, which is
10618        done in build_over_call.  */
10619     default_arg = TREE_PURPOSE (arg_types);
10620
10621     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10622       {
10623         /* We've instantiated a template before its default arguments
10624            have been parsed.  This can happen for a nested template
10625            class, and is not an error unless we require the default
10626            argument in a call of this function.  */
10627         remaining_arg_types = 
10628           tree_cons (default_arg, type, remaining_arg_types);
10629         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10630                        remaining_arg_types);
10631       }
10632     else
10633       remaining_arg_types = 
10634         hash_tree_cons (default_arg, type, remaining_arg_types);
10635   }
10636         
10637   return remaining_arg_types;
10638 }
10639
10640 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10641    *not* handle the exception-specification for FNTYPE, because the
10642    initial substitution of explicitly provided template parameters
10643    during argument deduction forbids substitution into the
10644    exception-specification:
10645
10646      [temp.deduct]
10647
10648      All references in the function type of the function template to  the
10649      corresponding template parameters are replaced by the specified tem-
10650      plate argument values.  If a substitution in a template parameter or
10651      in  the function type of the function template results in an invalid
10652      type, type deduction fails.  [Note: The equivalent  substitution  in
10653      exception specifications is done only when the function is instanti-
10654      ated, at which point a program is  ill-formed  if  the  substitution
10655      results in an invalid type.]  */
10656
10657 static tree
10658 tsubst_function_type (tree t,
10659                       tree args,
10660                       tsubst_flags_t complain,
10661                       tree in_decl)
10662 {
10663   tree return_type;
10664   tree arg_types;
10665   tree fntype;
10666
10667   /* The TYPE_CONTEXT is not used for function/method types.  */
10668   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10669
10670   /* Substitute the return type.  */
10671   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10672   if (return_type == error_mark_node)
10673     return error_mark_node;
10674   /* The standard does not presently indicate that creation of a
10675      function type with an invalid return type is a deduction failure.
10676      However, that is clearly analogous to creating an array of "void"
10677      or a reference to a reference.  This is core issue #486.  */
10678   if (TREE_CODE (return_type) == ARRAY_TYPE
10679       || TREE_CODE (return_type) == FUNCTION_TYPE)
10680     {
10681       if (complain & tf_error)
10682         {
10683           if (TREE_CODE (return_type) == ARRAY_TYPE)
10684             error ("function returning an array");
10685           else
10686             error ("function returning a function");
10687         }
10688       return error_mark_node;
10689     }
10690
10691   /* Substitute the argument types.  */
10692   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10693                                 complain, in_decl);
10694   if (arg_types == error_mark_node)
10695     return error_mark_node;
10696
10697   /* Construct a new type node and return it.  */
10698   if (TREE_CODE (t) == FUNCTION_TYPE)
10699     {
10700       fntype = build_function_type (return_type, arg_types);
10701       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10702     }
10703   else
10704     {
10705       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10706       if (! MAYBE_CLASS_TYPE_P (r))
10707         {
10708           /* [temp.deduct]
10709
10710              Type deduction may fail for any of the following
10711              reasons:
10712
10713              -- Attempting to create "pointer to member of T" when T
10714              is not a class type.  */
10715           if (complain & tf_error)
10716             error ("creating pointer to member function of non-class type %qT",
10717                       r);
10718           return error_mark_node;
10719         }
10720
10721       fntype = build_method_type_directly (r, return_type,
10722                                            TREE_CHAIN (arg_types));
10723     }
10724   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10725
10726   return fntype;
10727 }
10728
10729 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10730    ARGS into that specification, and return the substituted
10731    specification.  If there is no specification, return NULL_TREE.  */
10732
10733 static tree
10734 tsubst_exception_specification (tree fntype,
10735                                 tree args,
10736                                 tsubst_flags_t complain,
10737                                 tree in_decl,
10738                                 bool defer_ok)
10739 {
10740   tree specs;
10741   tree new_specs;
10742
10743   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10744   new_specs = NULL_TREE;
10745   if (specs && TREE_PURPOSE (specs))
10746     {
10747       /* A noexcept-specifier.  */
10748       tree expr = TREE_PURPOSE (specs);
10749       if (expr == boolean_true_node || expr == boolean_false_node)
10750         new_specs = expr;
10751       else if (defer_ok)
10752         {
10753           /* Defer instantiation of noexcept-specifiers to avoid
10754              excessive instantiations (c++/49107).  */
10755           new_specs = make_node (DEFERRED_NOEXCEPT);
10756           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10757             {
10758               /* We already partially instantiated this member template,
10759                  so combine the new args with the old.  */
10760               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10761                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10762               DEFERRED_NOEXCEPT_ARGS (new_specs)
10763                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10764             }
10765           else
10766             {
10767               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10768               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10769             }
10770         }
10771       else
10772         new_specs = tsubst_copy_and_build
10773           (expr, args, complain, in_decl, /*function_p=*/false,
10774            /*integral_constant_expression_p=*/true);
10775       new_specs = build_noexcept_spec (new_specs, complain);
10776     }
10777   else if (specs)
10778     {
10779       if (! TREE_VALUE (specs))
10780         new_specs = specs;
10781       else
10782         while (specs)
10783           {
10784             tree spec;
10785             int i, len = 1;
10786             tree expanded_specs = NULL_TREE;
10787
10788             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10789               {
10790                 /* Expand the pack expansion type.  */
10791                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10792                                                        args, complain,
10793                                                        in_decl);
10794
10795                 if (expanded_specs == error_mark_node)
10796                   return error_mark_node;
10797                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10798                   len = TREE_VEC_LENGTH (expanded_specs);
10799                 else
10800                   {
10801                     /* We're substituting into a member template, so
10802                        we got a TYPE_PACK_EXPANSION back.  Add that
10803                        expansion and move on.  */
10804                     gcc_assert (TREE_CODE (expanded_specs) 
10805                                 == TYPE_PACK_EXPANSION);
10806                     new_specs = add_exception_specifier (new_specs,
10807                                                          expanded_specs,
10808                                                          complain);
10809                     specs = TREE_CHAIN (specs);
10810                     continue;
10811                   }
10812               }
10813
10814             for (i = 0; i < len; ++i)
10815               {
10816                 if (expanded_specs)
10817                   spec = TREE_VEC_ELT (expanded_specs, i);
10818                 else
10819                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10820                 if (spec == error_mark_node)
10821                   return spec;
10822                 new_specs = add_exception_specifier (new_specs, spec, 
10823                                                      complain);
10824               }
10825
10826             specs = TREE_CHAIN (specs);
10827           }
10828     }
10829   return new_specs;
10830 }
10831
10832 /* Take the tree structure T and replace template parameters used
10833    therein with the argument vector ARGS.  IN_DECL is an associated
10834    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10835    Issue error and warning messages under control of COMPLAIN.  Note
10836    that we must be relatively non-tolerant of extensions here, in
10837    order to preserve conformance; if we allow substitutions that
10838    should not be allowed, we may allow argument deductions that should
10839    not succeed, and therefore report ambiguous overload situations
10840    where there are none.  In theory, we could allow the substitution,
10841    but indicate that it should have failed, and allow our caller to
10842    make sure that the right thing happens, but we don't try to do this
10843    yet.
10844
10845    This function is used for dealing with types, decls and the like;
10846    for expressions, use tsubst_expr or tsubst_copy.  */
10847
10848 tree
10849 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10850 {
10851   enum tree_code code;
10852   tree type, r;
10853
10854   if (t == NULL_TREE || t == error_mark_node
10855       || t == integer_type_node
10856       || t == void_type_node
10857       || t == char_type_node
10858       || t == unknown_type_node
10859       || TREE_CODE (t) == NAMESPACE_DECL
10860       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10861     return t;
10862
10863   if (DECL_P (t))
10864     return tsubst_decl (t, args, complain);
10865
10866   if (args == NULL_TREE)
10867     return t;
10868
10869   code = TREE_CODE (t);
10870
10871   if (code == IDENTIFIER_NODE)
10872     type = IDENTIFIER_TYPE_VALUE (t);
10873   else
10874     type = TREE_TYPE (t);
10875
10876   gcc_assert (type != unknown_type_node);
10877
10878   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10879      such as attribute aligned.  */
10880   if (TYPE_P (t)
10881       && typedef_variant_p (t))
10882     {
10883       tree decl = TYPE_NAME (t);
10884       
10885       if (DECL_CLASS_SCOPE_P (decl)
10886           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10887           && uses_template_parms (DECL_CONTEXT (decl)))
10888         {
10889           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10890           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10891           r = retrieve_specialization (tmpl, gen_args, 0);
10892         }
10893       else if (DECL_FUNCTION_SCOPE_P (decl)
10894                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10895                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10896         r = retrieve_local_specialization (decl);
10897       else
10898         /* The typedef is from a non-template context.  */
10899         return t;
10900
10901       if (r)
10902         {
10903           r = TREE_TYPE (r);
10904           r = cp_build_qualified_type_real
10905             (r, cp_type_quals (t) | cp_type_quals (r),
10906              complain | tf_ignore_bad_quals);
10907           return r;
10908         }
10909       /* Else we must be instantiating the typedef, so fall through.  */
10910     }
10911
10912   if (type
10913       && code != TYPENAME_TYPE
10914       && code != TEMPLATE_TYPE_PARM
10915       && code != IDENTIFIER_NODE
10916       && code != FUNCTION_TYPE
10917       && code != METHOD_TYPE)
10918     type = tsubst (type, args, complain, in_decl);
10919   if (type == error_mark_node)
10920     return error_mark_node;
10921
10922   switch (code)
10923     {
10924     case RECORD_TYPE:
10925     case UNION_TYPE:
10926     case ENUMERAL_TYPE:
10927       return tsubst_aggr_type (t, args, complain, in_decl,
10928                                /*entering_scope=*/0);
10929
10930     case ERROR_MARK:
10931     case IDENTIFIER_NODE:
10932     case VOID_TYPE:
10933     case REAL_TYPE:
10934     case COMPLEX_TYPE:
10935     case VECTOR_TYPE:
10936     case BOOLEAN_TYPE:
10937     case NULLPTR_TYPE:
10938     case LANG_TYPE:
10939       return t;
10940
10941     case INTEGER_TYPE:
10942       if (t == integer_type_node)
10943         return t;
10944
10945       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10946           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10947         return t;
10948
10949       {
10950         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10951
10952         max = tsubst_expr (omax, args, complain, in_decl,
10953                            /*integral_constant_expression_p=*/false);
10954
10955         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10956            needed.  */
10957         if (TREE_CODE (max) == NOP_EXPR
10958             && TREE_SIDE_EFFECTS (omax)
10959             && !TREE_TYPE (max))
10960           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10961
10962         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10963            with TREE_SIDE_EFFECTS that indicates this is not an integral
10964            constant expression.  */
10965         if (processing_template_decl
10966             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10967           {
10968             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10969             TREE_SIDE_EFFECTS (max) = 1;
10970           }
10971
10972         return compute_array_index_type (NULL_TREE, max, complain);
10973       }
10974
10975     case TEMPLATE_TYPE_PARM:
10976     case TEMPLATE_TEMPLATE_PARM:
10977     case BOUND_TEMPLATE_TEMPLATE_PARM:
10978     case TEMPLATE_PARM_INDEX:
10979       {
10980         int idx;
10981         int level;
10982         int levels;
10983         tree arg = NULL_TREE;
10984
10985         r = NULL_TREE;
10986
10987         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10988         template_parm_level_and_index (t, &level, &idx); 
10989
10990         levels = TMPL_ARGS_DEPTH (args);
10991         if (level <= levels)
10992           {
10993             arg = TMPL_ARG (args, level, idx);
10994
10995             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10996               /* See through ARGUMENT_PACK_SELECT arguments. */
10997               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10998           }
10999
11000         if (arg == error_mark_node)
11001           return error_mark_node;
11002         else if (arg != NULL_TREE)
11003           {
11004             if (ARGUMENT_PACK_P (arg))
11005               /* If ARG is an argument pack, we don't actually want to
11006                  perform a substitution here, because substitutions
11007                  for argument packs are only done
11008                  element-by-element. We can get to this point when
11009                  substituting the type of a non-type template
11010                  parameter pack, when that type actually contains
11011                  template parameter packs from an outer template, e.g.,
11012
11013                  template<typename... Types> struct A {
11014                    template<Types... Values> struct B { };
11015                  };  */
11016               return t;
11017
11018             if (code == TEMPLATE_TYPE_PARM)
11019               {
11020                 int quals;
11021                 gcc_assert (TYPE_P (arg));
11022
11023                 quals = cp_type_quals (arg) | cp_type_quals (t);
11024                   
11025                 return cp_build_qualified_type_real
11026                   (arg, quals, complain | tf_ignore_bad_quals);
11027               }
11028             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11029               {
11030                 /* We are processing a type constructed from a
11031                    template template parameter.  */
11032                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11033                                       args, complain, in_decl);
11034                 if (argvec == error_mark_node)
11035                   return error_mark_node;
11036
11037                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11038                    are resolving nested-types in the signature of a
11039                    member function templates.  Otherwise ARG is a
11040                    TEMPLATE_DECL and is the real template to be
11041                    instantiated.  */
11042                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11043                   arg = TYPE_NAME (arg);
11044
11045                 r = lookup_template_class (arg,
11046                                            argvec, in_decl,
11047                                            DECL_CONTEXT (arg),
11048                                             /*entering_scope=*/0,
11049                                            complain);
11050                 return cp_build_qualified_type_real
11051                   (r, cp_type_quals (t), complain);
11052               }
11053             else
11054               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11055               return convert_from_reference (unshare_expr (arg));
11056           }
11057
11058         if (level == 1)
11059           /* This can happen during the attempted tsubst'ing in
11060              unify.  This means that we don't yet have any information
11061              about the template parameter in question.  */
11062           return t;
11063
11064         /* If we get here, we must have been looking at a parm for a
11065            more deeply nested template.  Make a new version of this
11066            template parameter, but with a lower level.  */
11067         switch (code)
11068           {
11069           case TEMPLATE_TYPE_PARM:
11070           case TEMPLATE_TEMPLATE_PARM:
11071           case BOUND_TEMPLATE_TEMPLATE_PARM:
11072             if (cp_type_quals (t))
11073               {
11074                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11075                 r = cp_build_qualified_type_real
11076                   (r, cp_type_quals (t),
11077                    complain | (code == TEMPLATE_TYPE_PARM
11078                                ? tf_ignore_bad_quals : 0));
11079               }
11080             else
11081               {
11082                 r = copy_type (t);
11083                 TEMPLATE_TYPE_PARM_INDEX (r)
11084                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11085                                                 r, levels, args, complain);
11086                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11087                 TYPE_MAIN_VARIANT (r) = r;
11088                 TYPE_POINTER_TO (r) = NULL_TREE;
11089                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11090
11091                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11092                   /* We have reduced the level of the template
11093                      template parameter, but not the levels of its
11094                      template parameters, so canonical_type_parameter
11095                      will not be able to find the canonical template
11096                      template parameter for this level. Thus, we
11097                      require structural equality checking to compare
11098                      TEMPLATE_TEMPLATE_PARMs. */
11099                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11100                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11101                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11102                 else
11103                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11104
11105                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11106                   {
11107                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11108                                           complain, in_decl);
11109                     if (argvec == error_mark_node)
11110                       return error_mark_node;
11111
11112                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11113                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11114                   }
11115               }
11116             break;
11117
11118           case TEMPLATE_PARM_INDEX:
11119             r = reduce_template_parm_level (t, type, levels, args, complain);
11120             break;
11121
11122           default:
11123             gcc_unreachable ();
11124           }
11125
11126         return r;
11127       }
11128
11129     case TREE_LIST:
11130       {
11131         tree purpose, value, chain;
11132
11133         if (t == void_list_node)
11134           return t;
11135
11136         purpose = TREE_PURPOSE (t);
11137         if (purpose)
11138           {
11139             purpose = tsubst (purpose, args, complain, in_decl);
11140             if (purpose == error_mark_node)
11141               return error_mark_node;
11142           }
11143         value = TREE_VALUE (t);
11144         if (value)
11145           {
11146             value = tsubst (value, args, complain, in_decl);
11147             if (value == error_mark_node)
11148               return error_mark_node;
11149           }
11150         chain = TREE_CHAIN (t);
11151         if (chain && chain != void_type_node)
11152           {
11153             chain = tsubst (chain, args, complain, in_decl);
11154             if (chain == error_mark_node)
11155               return error_mark_node;
11156           }
11157         if (purpose == TREE_PURPOSE (t)
11158             && value == TREE_VALUE (t)
11159             && chain == TREE_CHAIN (t))
11160           return t;
11161         return hash_tree_cons (purpose, value, chain);
11162       }
11163
11164     case TREE_BINFO:
11165       /* We should never be tsubsting a binfo.  */
11166       gcc_unreachable ();
11167
11168     case TREE_VEC:
11169       /* A vector of template arguments.  */
11170       gcc_assert (!type);
11171       return tsubst_template_args (t, args, complain, in_decl);
11172
11173     case POINTER_TYPE:
11174     case REFERENCE_TYPE:
11175       {
11176         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11177           return t;
11178
11179         /* [temp.deduct]
11180
11181            Type deduction may fail for any of the following
11182            reasons:
11183
11184            -- Attempting to create a pointer to reference type.
11185            -- Attempting to create a reference to a reference type or
11186               a reference to void.
11187
11188           Core issue 106 says that creating a reference to a reference
11189           during instantiation is no longer a cause for failure. We
11190           only enforce this check in strict C++98 mode.  */
11191         if ((TREE_CODE (type) == REFERENCE_TYPE
11192              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11193             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11194           {
11195             static location_t last_loc;
11196
11197             /* We keep track of the last time we issued this error
11198                message to avoid spewing a ton of messages during a
11199                single bad template instantiation.  */
11200             if (complain & tf_error
11201                 && last_loc != input_location)
11202               {
11203                 if (TREE_CODE (type) == VOID_TYPE)
11204                   error ("forming reference to void");
11205                else if (code == POINTER_TYPE)
11206                  error ("forming pointer to reference type %qT", type);
11207                else
11208                   error ("forming reference to reference type %qT", type);
11209                 last_loc = input_location;
11210               }
11211
11212             return error_mark_node;
11213           }
11214         else if (code == POINTER_TYPE)
11215           {
11216             r = build_pointer_type (type);
11217             if (TREE_CODE (type) == METHOD_TYPE)
11218               r = build_ptrmemfunc_type (r);
11219           }
11220         else if (TREE_CODE (type) == REFERENCE_TYPE)
11221           /* In C++0x, during template argument substitution, when there is an
11222              attempt to create a reference to a reference type, reference
11223              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11224
11225              "If a template-argument for a template-parameter T names a type
11226              that is a reference to a type A, an attempt to create the type
11227              'lvalue reference to cv T' creates the type 'lvalue reference to
11228              A,' while an attempt to create the type type rvalue reference to
11229              cv T' creates the type T"
11230           */
11231           r = cp_build_reference_type
11232               (TREE_TYPE (type),
11233                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11234         else
11235           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11236         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11237
11238         if (r != error_mark_node)
11239           /* Will this ever be needed for TYPE_..._TO values?  */
11240           layout_type (r);
11241
11242         return r;
11243       }
11244     case OFFSET_TYPE:
11245       {
11246         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11247         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11248           {
11249             /* [temp.deduct]
11250
11251                Type deduction may fail for any of the following
11252                reasons:
11253
11254                -- Attempting to create "pointer to member of T" when T
11255                   is not a class type.  */
11256             if (complain & tf_error)
11257               error ("creating pointer to member of non-class type %qT", r);
11258             return error_mark_node;
11259           }
11260         if (TREE_CODE (type) == REFERENCE_TYPE)
11261           {
11262             if (complain & tf_error)
11263               error ("creating pointer to member reference type %qT", type);
11264             return error_mark_node;
11265           }
11266         if (TREE_CODE (type) == VOID_TYPE)
11267           {
11268             if (complain & tf_error)
11269               error ("creating pointer to member of type void");
11270             return error_mark_node;
11271           }
11272         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11273         if (TREE_CODE (type) == FUNCTION_TYPE)
11274           {
11275             /* The type of the implicit object parameter gets its
11276                cv-qualifiers from the FUNCTION_TYPE. */
11277             tree memptr;
11278             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11279             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11280             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11281                                                  complain);
11282           }
11283         else
11284           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11285                                                cp_type_quals (t),
11286                                                complain);
11287       }
11288     case FUNCTION_TYPE:
11289     case METHOD_TYPE:
11290       {
11291         tree fntype;
11292         tree specs;
11293         fntype = tsubst_function_type (t, args, complain, in_decl);
11294         if (fntype == error_mark_node)
11295           return error_mark_node;
11296
11297         /* Substitute the exception specification.  */
11298         specs = tsubst_exception_specification (t, args, complain,
11299                                                 in_decl, /*defer_ok*/true);
11300         if (specs == error_mark_node)
11301           return error_mark_node;
11302         if (specs)
11303           fntype = build_exception_variant (fntype, specs);
11304         return fntype;
11305       }
11306     case ARRAY_TYPE:
11307       {
11308         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11309         if (domain == error_mark_node)
11310           return error_mark_node;
11311
11312         /* As an optimization, we avoid regenerating the array type if
11313            it will obviously be the same as T.  */
11314         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11315           return t;
11316
11317         /* These checks should match the ones in grokdeclarator.
11318
11319            [temp.deduct]
11320
11321            The deduction may fail for any of the following reasons:
11322
11323            -- Attempting to create an array with an element type that
11324               is void, a function type, or a reference type, or [DR337]
11325               an abstract class type.  */
11326         if (TREE_CODE (type) == VOID_TYPE
11327             || TREE_CODE (type) == FUNCTION_TYPE
11328             || TREE_CODE (type) == REFERENCE_TYPE)
11329           {
11330             if (complain & tf_error)
11331               error ("creating array of %qT", type);
11332             return error_mark_node;
11333           }
11334         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11335           {
11336             if (complain & tf_error)
11337               error ("creating array of %qT, which is an abstract class type",
11338                      type);
11339             return error_mark_node;
11340           }
11341
11342         r = build_cplus_array_type (type, domain);
11343
11344         if (TYPE_USER_ALIGN (t))
11345           {
11346             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11347             TYPE_USER_ALIGN (r) = 1;
11348           }
11349
11350         return r;
11351       }
11352
11353     case TYPENAME_TYPE:
11354       {
11355         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11356                                      in_decl, /*entering_scope=*/1);
11357         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11358                               complain, in_decl);
11359
11360         if (ctx == error_mark_node || f == error_mark_node)
11361           return error_mark_node;
11362
11363         if (!MAYBE_CLASS_TYPE_P (ctx))
11364           {
11365             if (complain & tf_error)
11366               error ("%qT is not a class, struct, or union type", ctx);
11367             return error_mark_node;
11368           }
11369         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11370           {
11371             /* Normally, make_typename_type does not require that the CTX
11372                have complete type in order to allow things like:
11373
11374                  template <class T> struct S { typename S<T>::X Y; };
11375
11376                But, such constructs have already been resolved by this
11377                point, so here CTX really should have complete type, unless
11378                it's a partial instantiation.  */
11379             ctx = complete_type (ctx);
11380             if (!COMPLETE_TYPE_P (ctx))
11381               {
11382                 if (complain & tf_error)
11383                   cxx_incomplete_type_error (NULL_TREE, ctx);
11384                 return error_mark_node;
11385               }
11386           }
11387
11388         f = make_typename_type (ctx, f, typename_type,
11389                                 (complain & tf_error) | tf_keep_type_decl);
11390         if (f == error_mark_node)
11391           return f;
11392         if (TREE_CODE (f) == TYPE_DECL)
11393           {
11394             complain |= tf_ignore_bad_quals;
11395             f = TREE_TYPE (f);
11396           }
11397
11398         if (TREE_CODE (f) != TYPENAME_TYPE)
11399           {
11400             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11401               {
11402                 if (complain & tf_error)
11403                   error ("%qT resolves to %qT, which is not an enumeration type",
11404                          t, f);
11405                 else
11406                   return error_mark_node;
11407               }
11408             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11409               {
11410                 if (complain & tf_error)
11411                   error ("%qT resolves to %qT, which is is not a class type",
11412                          t, f);
11413                 else
11414                   return error_mark_node;
11415               }
11416           }
11417
11418         return cp_build_qualified_type_real
11419           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11420       }
11421
11422     case UNBOUND_CLASS_TEMPLATE:
11423       {
11424         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11425                                      in_decl, /*entering_scope=*/1);
11426         tree name = TYPE_IDENTIFIER (t);
11427         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11428
11429         if (ctx == error_mark_node || name == error_mark_node)
11430           return error_mark_node;
11431
11432         if (parm_list)
11433           parm_list = tsubst_template_parms (parm_list, args, complain);
11434         return make_unbound_class_template (ctx, name, parm_list, complain);
11435       }
11436
11437     case TYPEOF_TYPE:
11438       {
11439         tree type;
11440
11441         ++cp_unevaluated_operand;
11442         ++c_inhibit_evaluation_warnings;
11443
11444         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11445                             complain, in_decl,
11446                             /*integral_constant_expression_p=*/false);
11447
11448         --cp_unevaluated_operand;
11449         --c_inhibit_evaluation_warnings;
11450
11451         type = finish_typeof (type);
11452         return cp_build_qualified_type_real (type,
11453                                              cp_type_quals (t)
11454                                              | cp_type_quals (type),
11455                                              complain);
11456       }
11457
11458     case DECLTYPE_TYPE:
11459       {
11460         tree type;
11461
11462         ++cp_unevaluated_operand;
11463         ++c_inhibit_evaluation_warnings;
11464
11465         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11466                             complain, in_decl,
11467                             /*integral_constant_expression_p=*/false);
11468
11469         --cp_unevaluated_operand;
11470         --c_inhibit_evaluation_warnings;
11471
11472         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11473           type = lambda_capture_field_type (type);
11474         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11475           type = lambda_proxy_type (type);
11476         else
11477           type = finish_decltype_type
11478             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11479         return cp_build_qualified_type_real (type,
11480                                              cp_type_quals (t)
11481                                              | cp_type_quals (type),
11482                                              complain);
11483       }
11484
11485     case UNDERLYING_TYPE:
11486       {
11487         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11488                             complain, in_decl);
11489         return finish_underlying_type (type);
11490       }
11491
11492     case TYPE_ARGUMENT_PACK:
11493     case NONTYPE_ARGUMENT_PACK:
11494       {
11495         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11496         tree packed_out = 
11497           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11498                                 args,
11499                                 complain,
11500                                 in_decl);
11501         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11502
11503         /* For template nontype argument packs, also substitute into
11504            the type.  */
11505         if (code == NONTYPE_ARGUMENT_PACK)
11506           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11507
11508         return r;
11509       }
11510       break;
11511
11512     case INTEGER_CST:
11513     case REAL_CST:
11514     case STRING_CST:
11515     case PLUS_EXPR:
11516     case MINUS_EXPR:
11517     case NEGATE_EXPR:
11518     case NOP_EXPR:
11519     case INDIRECT_REF:
11520     case ADDR_EXPR:
11521     case CALL_EXPR:
11522     case ARRAY_REF:
11523     case SCOPE_REF:
11524       /* We should use one of the expression tsubsts for these codes.  */
11525       gcc_unreachable ();
11526
11527     default:
11528       sorry ("use of %qs in template", tree_code_name [(int) code]);
11529       return error_mark_node;
11530     }
11531 }
11532
11533 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11534    type of the expression on the left-hand side of the "." or "->"
11535    operator.  */
11536
11537 static tree
11538 tsubst_baselink (tree baselink, tree object_type,
11539                  tree args, tsubst_flags_t complain, tree in_decl)
11540 {
11541     tree name;
11542     tree qualifying_scope;
11543     tree fns;
11544     tree optype;
11545     tree template_args = 0;
11546     bool template_id_p = false;
11547
11548     /* A baselink indicates a function from a base class.  Both the
11549        BASELINK_ACCESS_BINFO and the base class referenced may
11550        indicate bases of the template class, rather than the
11551        instantiated class.  In addition, lookups that were not
11552        ambiguous before may be ambiguous now.  Therefore, we perform
11553        the lookup again.  */
11554     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11555     qualifying_scope = tsubst (qualifying_scope, args,
11556                                complain, in_decl);
11557     fns = BASELINK_FUNCTIONS (baselink);
11558     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11559     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11560       {
11561         template_id_p = true;
11562         template_args = TREE_OPERAND (fns, 1);
11563         fns = TREE_OPERAND (fns, 0);
11564         if (template_args)
11565           template_args = tsubst_template_args (template_args, args,
11566                                                 complain, in_decl);
11567       }
11568     name = DECL_NAME (get_first_fn (fns));
11569     if (IDENTIFIER_TYPENAME_P (name))
11570       name = mangle_conv_op_name_for_type (optype);
11571     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11572     if (!baselink)
11573       return error_mark_node;
11574
11575     /* If lookup found a single function, mark it as used at this
11576        point.  (If it lookup found multiple functions the one selected
11577        later by overload resolution will be marked as used at that
11578        point.)  */
11579     if (BASELINK_P (baselink))
11580       fns = BASELINK_FUNCTIONS (baselink);
11581     if (!template_id_p && !really_overloaded_fn (fns))
11582       mark_used (OVL_CURRENT (fns));
11583
11584     /* Add back the template arguments, if present.  */
11585     if (BASELINK_P (baselink) && template_id_p)
11586       BASELINK_FUNCTIONS (baselink)
11587         = build_nt (TEMPLATE_ID_EXPR,
11588                     BASELINK_FUNCTIONS (baselink),
11589                     template_args);
11590     /* Update the conversion operator type.  */
11591     BASELINK_OPTYPE (baselink) = optype;
11592
11593     if (!object_type)
11594       object_type = current_class_type;
11595     return adjust_result_of_qualified_name_lookup (baselink,
11596                                                    qualifying_scope,
11597                                                    object_type);
11598 }
11599
11600 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11601    true if the qualified-id will be a postfix-expression in-and-of
11602    itself; false if more of the postfix-expression follows the
11603    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11604    of "&".  */
11605
11606 static tree
11607 tsubst_qualified_id (tree qualified_id, tree args,
11608                      tsubst_flags_t complain, tree in_decl,
11609                      bool done, bool address_p)
11610 {
11611   tree expr;
11612   tree scope;
11613   tree name;
11614   bool is_template;
11615   tree template_args;
11616
11617   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11618
11619   /* Figure out what name to look up.  */
11620   name = TREE_OPERAND (qualified_id, 1);
11621   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11622     {
11623       is_template = true;
11624       template_args = TREE_OPERAND (name, 1);
11625       if (template_args)
11626         template_args = tsubst_template_args (template_args, args,
11627                                               complain, in_decl);
11628       name = TREE_OPERAND (name, 0);
11629     }
11630   else
11631     {
11632       is_template = false;
11633       template_args = NULL_TREE;
11634     }
11635
11636   /* Substitute into the qualifying scope.  When there are no ARGS, we
11637      are just trying to simplify a non-dependent expression.  In that
11638      case the qualifying scope may be dependent, and, in any case,
11639      substituting will not help.  */
11640   scope = TREE_OPERAND (qualified_id, 0);
11641   if (args)
11642     {
11643       scope = tsubst (scope, args, complain, in_decl);
11644       expr = tsubst_copy (name, args, complain, in_decl);
11645     }
11646   else
11647     expr = name;
11648
11649   if (dependent_scope_p (scope))
11650     {
11651       if (is_template)
11652         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11653       return build_qualified_name (NULL_TREE, scope, expr,
11654                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11655     }
11656
11657   if (!BASELINK_P (name) && !DECL_P (expr))
11658     {
11659       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11660         {
11661           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11662           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11663             {
11664               error ("qualifying type %qT does not match destructor name ~%qT",
11665                      scope, TREE_OPERAND (expr, 0));
11666               expr = error_mark_node;
11667             }
11668           else
11669             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11670                                           /*is_type_p=*/0, false);
11671         }
11672       else
11673         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11674       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11675                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11676         {
11677           if (complain & tf_error)
11678             {
11679               error ("dependent-name %qE is parsed as a non-type, but "
11680                      "instantiation yields a type", qualified_id);
11681               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11682             }
11683           return error_mark_node;
11684         }
11685     }
11686
11687   if (DECL_P (expr))
11688     {
11689       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11690                                            scope);
11691       /* Remember that there was a reference to this entity.  */
11692       mark_used (expr);
11693     }
11694
11695   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11696     {
11697       if (complain & tf_error)
11698         qualified_name_lookup_error (scope,
11699                                      TREE_OPERAND (qualified_id, 1),
11700                                      expr, input_location);
11701       return error_mark_node;
11702     }
11703
11704   if (is_template)
11705     expr = lookup_template_function (expr, template_args);
11706
11707   if (expr == error_mark_node && complain & tf_error)
11708     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11709                                  expr, input_location);
11710   else if (TYPE_P (scope))
11711     {
11712       expr = (adjust_result_of_qualified_name_lookup
11713               (expr, scope, current_class_type));
11714       expr = (finish_qualified_id_expr
11715               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11716                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11717                /*template_arg_p=*/false));
11718     }
11719
11720   /* Expressions do not generally have reference type.  */
11721   if (TREE_CODE (expr) != SCOPE_REF
11722       /* However, if we're about to form a pointer-to-member, we just
11723          want the referenced member referenced.  */
11724       && TREE_CODE (expr) != OFFSET_REF)
11725     expr = convert_from_reference (expr);
11726
11727   return expr;
11728 }
11729
11730 /* Like tsubst, but deals with expressions.  This function just replaces
11731    template parms; to finish processing the resultant expression, use
11732    tsubst_expr.  */
11733
11734 static tree
11735 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11736 {
11737   enum tree_code code;
11738   tree r;
11739
11740   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11741     return t;
11742
11743   code = TREE_CODE (t);
11744
11745   switch (code)
11746     {
11747     case PARM_DECL:
11748       r = retrieve_local_specialization (t);
11749
11750       if (r == NULL)
11751         {
11752           tree c;
11753           /* This can happen for a parameter name used later in a function
11754              declaration (such as in a late-specified return type).  Just
11755              make a dummy decl, since it's only used for its type.  */
11756           gcc_assert (cp_unevaluated_operand != 0);
11757           /* We copy T because want to tsubst the PARM_DECL only,
11758              not the following PARM_DECLs that are chained to T.  */
11759           c = copy_node (t);
11760           r = tsubst_decl (c, args, complain);
11761           /* Give it the template pattern as its context; its true context
11762              hasn't been instantiated yet and this is good enough for
11763              mangling.  */
11764           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11765         }
11766       
11767       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11768         r = ARGUMENT_PACK_SELECT_ARG (r);
11769       mark_used (r);
11770       return r;
11771
11772     case CONST_DECL:
11773       {
11774         tree enum_type;
11775         tree v;
11776
11777         if (DECL_TEMPLATE_PARM_P (t))
11778           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11779         /* There is no need to substitute into namespace-scope
11780            enumerators.  */
11781         if (DECL_NAMESPACE_SCOPE_P (t))
11782           return t;
11783         /* If ARGS is NULL, then T is known to be non-dependent.  */
11784         if (args == NULL_TREE)
11785           return integral_constant_value (t);
11786
11787         /* Unfortunately, we cannot just call lookup_name here.
11788            Consider:
11789
11790              template <int I> int f() {
11791              enum E { a = I };
11792              struct S { void g() { E e = a; } };
11793              };
11794
11795            When we instantiate f<7>::S::g(), say, lookup_name is not
11796            clever enough to find f<7>::a.  */
11797         enum_type
11798           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11799                               /*entering_scope=*/0);
11800
11801         for (v = TYPE_VALUES (enum_type);
11802              v != NULL_TREE;
11803              v = TREE_CHAIN (v))
11804           if (TREE_PURPOSE (v) == DECL_NAME (t))
11805             return TREE_VALUE (v);
11806
11807           /* We didn't find the name.  That should never happen; if
11808              name-lookup found it during preliminary parsing, we
11809              should find it again here during instantiation.  */
11810         gcc_unreachable ();
11811       }
11812       return t;
11813
11814     case FIELD_DECL:
11815       if (DECL_CONTEXT (t))
11816         {
11817           tree ctx;
11818
11819           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11820                                   /*entering_scope=*/1);
11821           if (ctx != DECL_CONTEXT (t))
11822             {
11823               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11824               if (!r)
11825                 {
11826                   if (complain & tf_error)
11827                     error ("using invalid field %qD", t);
11828                   return error_mark_node;
11829                 }
11830               return r;
11831             }
11832         }
11833
11834       return t;
11835
11836     case VAR_DECL:
11837     case FUNCTION_DECL:
11838       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11839           || local_variable_p (t))
11840         t = tsubst (t, args, complain, in_decl);
11841       mark_used (t);
11842       return t;
11843
11844     case OVERLOAD:
11845       /* An OVERLOAD will always be a non-dependent overload set; an
11846          overload set from function scope will just be represented with an
11847          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11848       gcc_assert (!uses_template_parms (t));
11849       return t;
11850
11851     case BASELINK:
11852       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11853
11854     case TEMPLATE_DECL:
11855       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11856         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11857                        args, complain, in_decl);
11858       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11859         return tsubst (t, args, complain, in_decl);
11860       else if (DECL_CLASS_SCOPE_P (t)
11861                && uses_template_parms (DECL_CONTEXT (t)))
11862         {
11863           /* Template template argument like the following example need
11864              special treatment:
11865
11866                template <template <class> class TT> struct C {};
11867                template <class T> struct D {
11868                  template <class U> struct E {};
11869                  C<E> c;                                // #1
11870                };
11871                D<int> d;                                // #2
11872
11873              We are processing the template argument `E' in #1 for
11874              the template instantiation #2.  Originally, `E' is a
11875              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11876              have to substitute this with one having context `D<int>'.  */
11877
11878           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11879           return lookup_field (context, DECL_NAME(t), 0, false);
11880         }
11881       else
11882         /* Ordinary template template argument.  */
11883         return t;
11884
11885     case CAST_EXPR:
11886     case REINTERPRET_CAST_EXPR:
11887     case CONST_CAST_EXPR:
11888     case STATIC_CAST_EXPR:
11889     case DYNAMIC_CAST_EXPR:
11890     case NOP_EXPR:
11891       return build1
11892         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11893          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11894
11895     case SIZEOF_EXPR:
11896       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11897         {
11898
11899           tree expanded;
11900           int len = 0;
11901
11902           ++cp_unevaluated_operand;
11903           ++c_inhibit_evaluation_warnings;
11904           /* We only want to compute the number of arguments.  */
11905           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11906                                             complain, in_decl);
11907           --cp_unevaluated_operand;
11908           --c_inhibit_evaluation_warnings;
11909
11910           if (TREE_CODE (expanded) == TREE_VEC)
11911             len = TREE_VEC_LENGTH (expanded);
11912
11913           if (expanded == error_mark_node)
11914             return error_mark_node;
11915           else if (PACK_EXPANSION_P (expanded)
11916                    || (TREE_CODE (expanded) == TREE_VEC
11917                        && len > 0
11918                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11919             {
11920               if (TREE_CODE (expanded) == TREE_VEC)
11921                 expanded = TREE_VEC_ELT (expanded, len - 1);
11922
11923               if (TYPE_P (expanded))
11924                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11925                                                    complain & tf_error);
11926               else
11927                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11928                                                    complain & tf_error);
11929             }
11930           else
11931             return build_int_cst (size_type_node, len);
11932         }
11933       /* Fall through */
11934
11935     case INDIRECT_REF:
11936     case NEGATE_EXPR:
11937     case TRUTH_NOT_EXPR:
11938     case BIT_NOT_EXPR:
11939     case ADDR_EXPR:
11940     case UNARY_PLUS_EXPR:      /* Unary + */
11941     case ALIGNOF_EXPR:
11942     case AT_ENCODE_EXPR:
11943     case ARROW_EXPR:
11944     case THROW_EXPR:
11945     case TYPEID_EXPR:
11946     case REALPART_EXPR:
11947     case IMAGPART_EXPR:
11948       return build1
11949         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11950          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11951
11952     case COMPONENT_REF:
11953       {
11954         tree object;
11955         tree name;
11956
11957         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11958         name = TREE_OPERAND (t, 1);
11959         if (TREE_CODE (name) == BIT_NOT_EXPR)
11960           {
11961             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11962                                 complain, in_decl);
11963             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11964           }
11965         else if (TREE_CODE (name) == SCOPE_REF
11966                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11967           {
11968             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11969                                      complain, in_decl);
11970             name = TREE_OPERAND (name, 1);
11971             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11972                                 complain, in_decl);
11973             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11974             name = build_qualified_name (/*type=*/NULL_TREE,
11975                                          base, name,
11976                                          /*template_p=*/false);
11977           }
11978         else if (TREE_CODE (name) == BASELINK)
11979           name = tsubst_baselink (name,
11980                                   non_reference (TREE_TYPE (object)),
11981                                   args, complain,
11982                                   in_decl);
11983         else
11984           name = tsubst_copy (name, args, complain, in_decl);
11985         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11986       }
11987
11988     case PLUS_EXPR:
11989     case MINUS_EXPR:
11990     case MULT_EXPR:
11991     case TRUNC_DIV_EXPR:
11992     case CEIL_DIV_EXPR:
11993     case FLOOR_DIV_EXPR:
11994     case ROUND_DIV_EXPR:
11995     case EXACT_DIV_EXPR:
11996     case BIT_AND_EXPR:
11997     case BIT_IOR_EXPR:
11998     case BIT_XOR_EXPR:
11999     case TRUNC_MOD_EXPR:
12000     case FLOOR_MOD_EXPR:
12001     case TRUTH_ANDIF_EXPR:
12002     case TRUTH_ORIF_EXPR:
12003     case TRUTH_AND_EXPR:
12004     case TRUTH_OR_EXPR:
12005     case RSHIFT_EXPR:
12006     case LSHIFT_EXPR:
12007     case RROTATE_EXPR:
12008     case LROTATE_EXPR:
12009     case EQ_EXPR:
12010     case NE_EXPR:
12011     case MAX_EXPR:
12012     case MIN_EXPR:
12013     case LE_EXPR:
12014     case GE_EXPR:
12015     case LT_EXPR:
12016     case GT_EXPR:
12017     case COMPOUND_EXPR:
12018     case DOTSTAR_EXPR:
12019     case MEMBER_REF:
12020     case PREDECREMENT_EXPR:
12021     case PREINCREMENT_EXPR:
12022     case POSTDECREMENT_EXPR:
12023     case POSTINCREMENT_EXPR:
12024       return build_nt
12025         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12026          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12027
12028     case SCOPE_REF:
12029       return build_qualified_name (/*type=*/NULL_TREE,
12030                                    tsubst_copy (TREE_OPERAND (t, 0),
12031                                                 args, complain, in_decl),
12032                                    tsubst_copy (TREE_OPERAND (t, 1),
12033                                                 args, complain, in_decl),
12034                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12035
12036     case ARRAY_REF:
12037       return build_nt
12038         (ARRAY_REF,
12039          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12040          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12041          NULL_TREE, NULL_TREE);
12042
12043     case CALL_EXPR:
12044       {
12045         int n = VL_EXP_OPERAND_LENGTH (t);
12046         tree result = build_vl_exp (CALL_EXPR, n);
12047         int i;
12048         for (i = 0; i < n; i++)
12049           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12050                                              complain, in_decl);
12051         return result;
12052       }
12053
12054     case COND_EXPR:
12055     case MODOP_EXPR:
12056     case PSEUDO_DTOR_EXPR:
12057       {
12058         r = build_nt
12059           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12060            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12061            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12062         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12063         return r;
12064       }
12065
12066     case NEW_EXPR:
12067       {
12068         r = build_nt
12069         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12070          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12071          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12072         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12073         return r;
12074       }
12075
12076     case DELETE_EXPR:
12077       {
12078         r = build_nt
12079         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12080          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12081         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12082         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12083         return r;
12084       }
12085
12086     case TEMPLATE_ID_EXPR:
12087       {
12088         /* Substituted template arguments */
12089         tree fn = TREE_OPERAND (t, 0);
12090         tree targs = TREE_OPERAND (t, 1);
12091
12092         fn = tsubst_copy (fn, args, complain, in_decl);
12093         if (targs)
12094           targs = tsubst_template_args (targs, args, complain, in_decl);
12095
12096         return lookup_template_function (fn, targs);
12097       }
12098
12099     case TREE_LIST:
12100       {
12101         tree purpose, value, chain;
12102
12103         if (t == void_list_node)
12104           return t;
12105
12106         purpose = TREE_PURPOSE (t);
12107         if (purpose)
12108           purpose = tsubst_copy (purpose, args, complain, in_decl);
12109         value = TREE_VALUE (t);
12110         if (value)
12111           value = tsubst_copy (value, args, complain, in_decl);
12112         chain = TREE_CHAIN (t);
12113         if (chain && chain != void_type_node)
12114           chain = tsubst_copy (chain, args, complain, in_decl);
12115         if (purpose == TREE_PURPOSE (t)
12116             && value == TREE_VALUE (t)
12117             && chain == TREE_CHAIN (t))
12118           return t;
12119         return tree_cons (purpose, value, chain);
12120       }
12121
12122     case RECORD_TYPE:
12123     case UNION_TYPE:
12124     case ENUMERAL_TYPE:
12125     case INTEGER_TYPE:
12126     case TEMPLATE_TYPE_PARM:
12127     case TEMPLATE_TEMPLATE_PARM:
12128     case BOUND_TEMPLATE_TEMPLATE_PARM:
12129     case TEMPLATE_PARM_INDEX:
12130     case POINTER_TYPE:
12131     case REFERENCE_TYPE:
12132     case OFFSET_TYPE:
12133     case FUNCTION_TYPE:
12134     case METHOD_TYPE:
12135     case ARRAY_TYPE:
12136     case TYPENAME_TYPE:
12137     case UNBOUND_CLASS_TEMPLATE:
12138     case TYPEOF_TYPE:
12139     case DECLTYPE_TYPE:
12140     case TYPE_DECL:
12141       return tsubst (t, args, complain, in_decl);
12142
12143     case IDENTIFIER_NODE:
12144       if (IDENTIFIER_TYPENAME_P (t))
12145         {
12146           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12147           return mangle_conv_op_name_for_type (new_type);
12148         }
12149       else
12150         return t;
12151
12152     case CONSTRUCTOR:
12153       /* This is handled by tsubst_copy_and_build.  */
12154       gcc_unreachable ();
12155
12156     case VA_ARG_EXPR:
12157       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12158                                           in_decl),
12159                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12160
12161     case CLEANUP_POINT_EXPR:
12162       /* We shouldn't have built any of these during initial template
12163          generation.  Instead, they should be built during instantiation
12164          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12165       gcc_unreachable ();
12166
12167     case OFFSET_REF:
12168       r = build2
12169         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12170          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12171          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12172       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12173       mark_used (TREE_OPERAND (r, 1));
12174       return r;
12175
12176     case EXPR_PACK_EXPANSION:
12177       error ("invalid use of pack expansion expression");
12178       return error_mark_node;
12179
12180     case NONTYPE_ARGUMENT_PACK:
12181       error ("use %<...%> to expand argument pack");
12182       return error_mark_node;
12183
12184     case INTEGER_CST:
12185     case REAL_CST:
12186     case STRING_CST:
12187     case COMPLEX_CST:
12188       {
12189         /* Instantiate any typedefs in the type.  */
12190         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12191         r = fold_convert (type, t);
12192         gcc_assert (TREE_CODE (r) == code);
12193         return r;
12194       }
12195
12196     case PTRMEM_CST:
12197       /* These can sometimes show up in a partial instantiation, but never
12198          involve template parms.  */
12199       gcc_assert (!uses_template_parms (t));
12200       return t;
12201
12202     default:
12203       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12204       gcc_checking_assert (false);
12205       return t;
12206     }
12207 }
12208
12209 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12210
12211 static tree
12212 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12213                     tree in_decl)
12214 {
12215   tree new_clauses = NULL, nc, oc;
12216
12217   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12218     {
12219       nc = copy_node (oc);
12220       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12221       new_clauses = nc;
12222
12223       switch (OMP_CLAUSE_CODE (nc))
12224         {
12225         case OMP_CLAUSE_LASTPRIVATE:
12226           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12227             {
12228               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12229               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12230                            in_decl, /*integral_constant_expression_p=*/false);
12231               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12232                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12233             }
12234           /* FALLTHRU */
12235         case OMP_CLAUSE_PRIVATE:
12236         case OMP_CLAUSE_SHARED:
12237         case OMP_CLAUSE_FIRSTPRIVATE:
12238         case OMP_CLAUSE_REDUCTION:
12239         case OMP_CLAUSE_COPYIN:
12240         case OMP_CLAUSE_COPYPRIVATE:
12241         case OMP_CLAUSE_IF:
12242         case OMP_CLAUSE_NUM_THREADS:
12243         case OMP_CLAUSE_SCHEDULE:
12244         case OMP_CLAUSE_COLLAPSE:
12245         case OMP_CLAUSE_FINAL:
12246           OMP_CLAUSE_OPERAND (nc, 0)
12247             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12248                            in_decl, /*integral_constant_expression_p=*/false);
12249           break;
12250         case OMP_CLAUSE_NOWAIT:
12251         case OMP_CLAUSE_ORDERED:
12252         case OMP_CLAUSE_DEFAULT:
12253         case OMP_CLAUSE_UNTIED:
12254         case OMP_CLAUSE_MERGEABLE:
12255           break;
12256         default:
12257           gcc_unreachable ();
12258         }
12259     }
12260
12261   return finish_omp_clauses (nreverse (new_clauses));
12262 }
12263
12264 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12265
12266 static tree
12267 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12268                           tree in_decl)
12269 {
12270 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12271
12272   tree purpose, value, chain;
12273
12274   if (t == NULL)
12275     return t;
12276
12277   if (TREE_CODE (t) != TREE_LIST)
12278     return tsubst_copy_and_build (t, args, complain, in_decl,
12279                                   /*function_p=*/false,
12280                                   /*integral_constant_expression_p=*/false);
12281
12282   if (t == void_list_node)
12283     return t;
12284
12285   purpose = TREE_PURPOSE (t);
12286   if (purpose)
12287     purpose = RECUR (purpose);
12288   value = TREE_VALUE (t);
12289   if (value && TREE_CODE (value) != LABEL_DECL)
12290     value = RECUR (value);
12291   chain = TREE_CHAIN (t);
12292   if (chain && chain != void_type_node)
12293     chain = RECUR (chain);
12294   return tree_cons (purpose, value, chain);
12295 #undef RECUR
12296 }
12297
12298 /* Substitute one OMP_FOR iterator.  */
12299
12300 static void
12301 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12302                          tree condv, tree incrv, tree *clauses,
12303                          tree args, tsubst_flags_t complain, tree in_decl,
12304                          bool integral_constant_expression_p)
12305 {
12306 #define RECUR(NODE)                             \
12307   tsubst_expr ((NODE), args, complain, in_decl, \
12308                integral_constant_expression_p)
12309   tree decl, init, cond, incr, auto_node;
12310
12311   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12312   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12313   decl = RECUR (TREE_OPERAND (init, 0));
12314   init = TREE_OPERAND (init, 1);
12315   auto_node = type_uses_auto (TREE_TYPE (decl));
12316   if (auto_node && init)
12317     {
12318       tree init_expr = init;
12319       if (TREE_CODE (init_expr) == DECL_EXPR)
12320         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12321       init_expr = RECUR (init_expr);
12322       TREE_TYPE (decl)
12323         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12324     }
12325   gcc_assert (!type_dependent_expression_p (decl));
12326
12327   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12328     {
12329       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12330       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12331       if (TREE_CODE (incr) == MODIFY_EXPR)
12332         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12333                                     RECUR (TREE_OPERAND (incr, 1)),
12334                                     complain);
12335       else
12336         incr = RECUR (incr);
12337       TREE_VEC_ELT (declv, i) = decl;
12338       TREE_VEC_ELT (initv, i) = init;
12339       TREE_VEC_ELT (condv, i) = cond;
12340       TREE_VEC_ELT (incrv, i) = incr;
12341       return;
12342     }
12343
12344   if (init && TREE_CODE (init) != DECL_EXPR)
12345     {
12346       tree c;
12347       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12348         {
12349           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12350                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12351               && OMP_CLAUSE_DECL (c) == decl)
12352             break;
12353           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12354                    && OMP_CLAUSE_DECL (c) == decl)
12355             error ("iteration variable %qD should not be firstprivate", decl);
12356           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12357                    && OMP_CLAUSE_DECL (c) == decl)
12358             error ("iteration variable %qD should not be reduction", decl);
12359         }
12360       if (c == NULL)
12361         {
12362           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12363           OMP_CLAUSE_DECL (c) = decl;
12364           c = finish_omp_clauses (c);
12365           if (c)
12366             {
12367               OMP_CLAUSE_CHAIN (c) = *clauses;
12368               *clauses = c;
12369             }
12370         }
12371     }
12372   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12373   if (COMPARISON_CLASS_P (cond))
12374     cond = build2 (TREE_CODE (cond), boolean_type_node,
12375                    RECUR (TREE_OPERAND (cond, 0)),
12376                    RECUR (TREE_OPERAND (cond, 1)));
12377   else
12378     cond = RECUR (cond);
12379   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12380   switch (TREE_CODE (incr))
12381     {
12382     case PREINCREMENT_EXPR:
12383     case PREDECREMENT_EXPR:
12384     case POSTINCREMENT_EXPR:
12385     case POSTDECREMENT_EXPR:
12386       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12387                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12388       break;
12389     case MODIFY_EXPR:
12390       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12391           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12392         {
12393           tree rhs = TREE_OPERAND (incr, 1);
12394           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12395                          RECUR (TREE_OPERAND (incr, 0)),
12396                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12397                                  RECUR (TREE_OPERAND (rhs, 0)),
12398                                  RECUR (TREE_OPERAND (rhs, 1))));
12399         }
12400       else
12401         incr = RECUR (incr);
12402       break;
12403     case MODOP_EXPR:
12404       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12405           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12406         {
12407           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12408           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12409                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12410                                  TREE_TYPE (decl), lhs,
12411                                  RECUR (TREE_OPERAND (incr, 2))));
12412         }
12413       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12414                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12415                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12416         {
12417           tree rhs = TREE_OPERAND (incr, 2);
12418           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12419                          RECUR (TREE_OPERAND (incr, 0)),
12420                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12421                                  RECUR (TREE_OPERAND (rhs, 0)),
12422                                  RECUR (TREE_OPERAND (rhs, 1))));
12423         }
12424       else
12425         incr = RECUR (incr);
12426       break;
12427     default:
12428       incr = RECUR (incr);
12429       break;
12430     }
12431
12432   TREE_VEC_ELT (declv, i) = decl;
12433   TREE_VEC_ELT (initv, i) = init;
12434   TREE_VEC_ELT (condv, i) = cond;
12435   TREE_VEC_ELT (incrv, i) = incr;
12436 #undef RECUR
12437 }
12438
12439 /* Like tsubst_copy for expressions, etc. but also does semantic
12440    processing.  */
12441
12442 static tree
12443 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12444              bool integral_constant_expression_p)
12445 {
12446 #define RECUR(NODE)                             \
12447   tsubst_expr ((NODE), args, complain, in_decl, \
12448                integral_constant_expression_p)
12449
12450   tree stmt, tmp;
12451
12452   if (t == NULL_TREE || t == error_mark_node)
12453     return t;
12454
12455   if (EXPR_HAS_LOCATION (t))
12456     input_location = EXPR_LOCATION (t);
12457   if (STATEMENT_CODE_P (TREE_CODE (t)))
12458     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12459
12460   switch (TREE_CODE (t))
12461     {
12462     case STATEMENT_LIST:
12463       {
12464         tree_stmt_iterator i;
12465         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12466           RECUR (tsi_stmt (i));
12467         break;
12468       }
12469
12470     case CTOR_INITIALIZER:
12471       finish_mem_initializers (tsubst_initializer_list
12472                                (TREE_OPERAND (t, 0), args));
12473       break;
12474
12475     case RETURN_EXPR:
12476       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12477       break;
12478
12479     case EXPR_STMT:
12480       tmp = RECUR (EXPR_STMT_EXPR (t));
12481       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12482         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12483       else
12484         finish_expr_stmt (tmp);
12485       break;
12486
12487     case USING_STMT:
12488       do_using_directive (USING_STMT_NAMESPACE (t));
12489       break;
12490
12491     case DECL_EXPR:
12492       {
12493         tree decl, pattern_decl;
12494         tree init;
12495
12496         pattern_decl = decl = DECL_EXPR_DECL (t);
12497         if (TREE_CODE (decl) == LABEL_DECL)
12498           finish_label_decl (DECL_NAME (decl));
12499         else if (TREE_CODE (decl) == USING_DECL)
12500           {
12501             tree scope = USING_DECL_SCOPE (decl);
12502             tree name = DECL_NAME (decl);
12503             tree decl;
12504
12505             scope = tsubst (scope, args, complain, in_decl);
12506             decl = lookup_qualified_name (scope, name,
12507                                           /*is_type_p=*/false,
12508                                           /*complain=*/false);
12509             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12510               qualified_name_lookup_error (scope, name, decl, input_location);
12511             else
12512               do_local_using_decl (decl, scope, name);
12513           }
12514         else
12515           {
12516             init = DECL_INITIAL (decl);
12517             decl = tsubst (decl, args, complain, in_decl);
12518             if (decl != error_mark_node)
12519               {
12520                 /* By marking the declaration as instantiated, we avoid
12521                    trying to instantiate it.  Since instantiate_decl can't
12522                    handle local variables, and since we've already done
12523                    all that needs to be done, that's the right thing to
12524                    do.  */
12525                 if (TREE_CODE (decl) == VAR_DECL)
12526                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12527                 if (TREE_CODE (decl) == VAR_DECL
12528                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12529                   /* Anonymous aggregates are a special case.  */
12530                   finish_anon_union (decl);
12531                 else
12532                   {
12533                     int const_init = false;
12534                     maybe_push_decl (decl);
12535                     if (TREE_CODE (decl) == VAR_DECL
12536                         && DECL_PRETTY_FUNCTION_P (decl))
12537                       {
12538                         /* For __PRETTY_FUNCTION__ we have to adjust the
12539                            initializer.  */
12540                         const char *const name
12541                           = cxx_printable_name (current_function_decl, 2);
12542                         init = cp_fname_init (name, &TREE_TYPE (decl));
12543                       }
12544                     else
12545                       {
12546                         tree t = RECUR (init);
12547
12548                         if (init && !t)
12549                           {
12550                             /* If we had an initializer but it
12551                                instantiated to nothing,
12552                                value-initialize the object.  This will
12553                                only occur when the initializer was a
12554                                pack expansion where the parameter packs
12555                                used in that expansion were of length
12556                                zero.  */
12557                             init = build_value_init (TREE_TYPE (decl),
12558                                                      complain);
12559                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12560                               init = get_target_expr_sfinae (init, complain);
12561                           }
12562                         else
12563                           init = t;
12564                       }
12565
12566                     if (TREE_CODE (decl) == VAR_DECL)
12567                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12568                                     (pattern_decl));
12569                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12570                   }
12571               }
12572           }
12573
12574         /* A DECL_EXPR can also be used as an expression, in the condition
12575            clause of an if/for/while construct.  */
12576         return decl;
12577       }
12578
12579     case FOR_STMT:
12580       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12581       RECUR (FOR_INIT_STMT (t));
12582       finish_for_init_stmt (stmt);
12583       tmp = RECUR (FOR_COND (t));
12584       finish_for_cond (tmp, stmt);
12585       tmp = RECUR (FOR_EXPR (t));
12586       finish_for_expr (tmp, stmt);
12587       RECUR (FOR_BODY (t));
12588       finish_for_stmt (stmt);
12589       break;
12590
12591     case RANGE_FOR_STMT:
12592       {
12593         tree decl, expr;
12594         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12595         decl = RANGE_FOR_DECL (t);
12596         decl = tsubst (decl, args, complain, in_decl);
12597         maybe_push_decl (decl);
12598         expr = RECUR (RANGE_FOR_EXPR (t));
12599         stmt = cp_convert_range_for (stmt, decl, expr);
12600         RECUR (RANGE_FOR_BODY (t));
12601         finish_for_stmt (stmt);
12602       }
12603       break;
12604
12605     case WHILE_STMT:
12606       stmt = begin_while_stmt ();
12607       tmp = RECUR (WHILE_COND (t));
12608       finish_while_stmt_cond (tmp, stmt);
12609       RECUR (WHILE_BODY (t));
12610       finish_while_stmt (stmt);
12611       break;
12612
12613     case DO_STMT:
12614       stmt = begin_do_stmt ();
12615       RECUR (DO_BODY (t));
12616       finish_do_body (stmt);
12617       tmp = RECUR (DO_COND (t));
12618       finish_do_stmt (tmp, stmt);
12619       break;
12620
12621     case IF_STMT:
12622       stmt = begin_if_stmt ();
12623       tmp = RECUR (IF_COND (t));
12624       finish_if_stmt_cond (tmp, stmt);
12625       RECUR (THEN_CLAUSE (t));
12626       finish_then_clause (stmt);
12627
12628       if (ELSE_CLAUSE (t))
12629         {
12630           begin_else_clause (stmt);
12631           RECUR (ELSE_CLAUSE (t));
12632           finish_else_clause (stmt);
12633         }
12634
12635       finish_if_stmt (stmt);
12636       break;
12637
12638     case BIND_EXPR:
12639       if (BIND_EXPR_BODY_BLOCK (t))
12640         stmt = begin_function_body ();
12641       else
12642         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12643                                     ? BCS_TRY_BLOCK : 0);
12644
12645       RECUR (BIND_EXPR_BODY (t));
12646
12647       if (BIND_EXPR_BODY_BLOCK (t))
12648         finish_function_body (stmt);
12649       else
12650         finish_compound_stmt (stmt);
12651       break;
12652
12653     case BREAK_STMT:
12654       finish_break_stmt ();
12655       break;
12656
12657     case CONTINUE_STMT:
12658       finish_continue_stmt ();
12659       break;
12660
12661     case SWITCH_STMT:
12662       stmt = begin_switch_stmt ();
12663       tmp = RECUR (SWITCH_STMT_COND (t));
12664       finish_switch_cond (tmp, stmt);
12665       RECUR (SWITCH_STMT_BODY (t));
12666       finish_switch_stmt (stmt);
12667       break;
12668
12669     case CASE_LABEL_EXPR:
12670       finish_case_label (EXPR_LOCATION (t),
12671                          RECUR (CASE_LOW (t)),
12672                          RECUR (CASE_HIGH (t)));
12673       break;
12674
12675     case LABEL_EXPR:
12676       {
12677         tree decl = LABEL_EXPR_LABEL (t);
12678         tree label;
12679
12680         label = finish_label_stmt (DECL_NAME (decl));
12681         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12682           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12683       }
12684       break;
12685
12686     case GOTO_EXPR:
12687       tmp = GOTO_DESTINATION (t);
12688       if (TREE_CODE (tmp) != LABEL_DECL)
12689         /* Computed goto's must be tsubst'd into.  On the other hand,
12690            non-computed gotos must not be; the identifier in question
12691            will have no binding.  */
12692         tmp = RECUR (tmp);
12693       else
12694         tmp = DECL_NAME (tmp);
12695       finish_goto_stmt (tmp);
12696       break;
12697
12698     case ASM_EXPR:
12699       tmp = finish_asm_stmt
12700         (ASM_VOLATILE_P (t),
12701          RECUR (ASM_STRING (t)),
12702          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12703          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12704          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12705          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12706       {
12707         tree asm_expr = tmp;
12708         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12709           asm_expr = TREE_OPERAND (asm_expr, 0);
12710         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12711       }
12712       break;
12713
12714     case TRY_BLOCK:
12715       if (CLEANUP_P (t))
12716         {
12717           stmt = begin_try_block ();
12718           RECUR (TRY_STMTS (t));
12719           finish_cleanup_try_block (stmt);
12720           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12721         }
12722       else
12723         {
12724           tree compound_stmt = NULL_TREE;
12725
12726           if (FN_TRY_BLOCK_P (t))
12727             stmt = begin_function_try_block (&compound_stmt);
12728           else
12729             stmt = begin_try_block ();
12730
12731           RECUR (TRY_STMTS (t));
12732
12733           if (FN_TRY_BLOCK_P (t))
12734             finish_function_try_block (stmt);
12735           else
12736             finish_try_block (stmt);
12737
12738           RECUR (TRY_HANDLERS (t));
12739           if (FN_TRY_BLOCK_P (t))
12740             finish_function_handler_sequence (stmt, compound_stmt);
12741           else
12742             finish_handler_sequence (stmt);
12743         }
12744       break;
12745
12746     case HANDLER:
12747       {
12748         tree decl = HANDLER_PARMS (t);
12749
12750         if (decl)
12751           {
12752             decl = tsubst (decl, args, complain, in_decl);
12753             /* Prevent instantiate_decl from trying to instantiate
12754                this variable.  We've already done all that needs to be
12755                done.  */
12756             if (decl != error_mark_node)
12757               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12758           }
12759         stmt = begin_handler ();
12760         finish_handler_parms (decl, stmt);
12761         RECUR (HANDLER_BODY (t));
12762         finish_handler (stmt);
12763       }
12764       break;
12765
12766     case TAG_DEFN:
12767       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12768       break;
12769
12770     case STATIC_ASSERT:
12771       {
12772         tree condition = 
12773           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12774                        args,
12775                        complain, in_decl,
12776                        /*integral_constant_expression_p=*/true);
12777         finish_static_assert (condition,
12778                               STATIC_ASSERT_MESSAGE (t),
12779                               STATIC_ASSERT_SOURCE_LOCATION (t),
12780                               /*member_p=*/false);
12781       }
12782       break;
12783
12784     case OMP_PARALLEL:
12785       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12786                                 args, complain, in_decl);
12787       stmt = begin_omp_parallel ();
12788       RECUR (OMP_PARALLEL_BODY (t));
12789       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12790         = OMP_PARALLEL_COMBINED (t);
12791       break;
12792
12793     case OMP_TASK:
12794       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12795                                 args, complain, in_decl);
12796       stmt = begin_omp_task ();
12797       RECUR (OMP_TASK_BODY (t));
12798       finish_omp_task (tmp, stmt);
12799       break;
12800
12801     case OMP_FOR:
12802       {
12803         tree clauses, body, pre_body;
12804         tree declv, initv, condv, incrv;
12805         int i;
12806
12807         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12808                                       args, complain, in_decl);
12809         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12810         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12811         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12812         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12813
12814         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12815           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12816                                    &clauses, args, complain, in_decl,
12817                                    integral_constant_expression_p);
12818
12819         stmt = begin_omp_structured_block ();
12820
12821         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12822           if (TREE_VEC_ELT (initv, i) == NULL
12823               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12824             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12825           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12826             {
12827               tree init = RECUR (TREE_VEC_ELT (initv, i));
12828               gcc_assert (init == TREE_VEC_ELT (declv, i));
12829               TREE_VEC_ELT (initv, i) = NULL_TREE;
12830             }
12831           else
12832             {
12833               tree decl_expr = TREE_VEC_ELT (initv, i);
12834               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12835               gcc_assert (init != NULL);
12836               TREE_VEC_ELT (initv, i) = RECUR (init);
12837               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12838               RECUR (decl_expr);
12839               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12840             }
12841
12842         pre_body = push_stmt_list ();
12843         RECUR (OMP_FOR_PRE_BODY (t));
12844         pre_body = pop_stmt_list (pre_body);
12845
12846         body = push_stmt_list ();
12847         RECUR (OMP_FOR_BODY (t));
12848         body = pop_stmt_list (body);
12849
12850         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12851                             body, pre_body, clauses);
12852
12853         add_stmt (finish_omp_structured_block (stmt));
12854       }
12855       break;
12856
12857     case OMP_SECTIONS:
12858     case OMP_SINGLE:
12859       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12860       stmt = push_stmt_list ();
12861       RECUR (OMP_BODY (t));
12862       stmt = pop_stmt_list (stmt);
12863
12864       t = copy_node (t);
12865       OMP_BODY (t) = stmt;
12866       OMP_CLAUSES (t) = tmp;
12867       add_stmt (t);
12868       break;
12869
12870     case OMP_SECTION:
12871     case OMP_CRITICAL:
12872     case OMP_MASTER:
12873     case OMP_ORDERED:
12874       stmt = push_stmt_list ();
12875       RECUR (OMP_BODY (t));
12876       stmt = pop_stmt_list (stmt);
12877
12878       t = copy_node (t);
12879       OMP_BODY (t) = stmt;
12880       add_stmt (t);
12881       break;
12882
12883     case OMP_ATOMIC:
12884       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12885       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12886         {
12887           tree op1 = TREE_OPERAND (t, 1);
12888           tree rhs1 = NULL_TREE;
12889           tree lhs, rhs;
12890           if (TREE_CODE (op1) == COMPOUND_EXPR)
12891             {
12892               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12893               op1 = TREE_OPERAND (op1, 1);
12894             }
12895           lhs = RECUR (TREE_OPERAND (op1, 0));
12896           rhs = RECUR (TREE_OPERAND (op1, 1));
12897           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12898                              NULL_TREE, NULL_TREE, rhs1);
12899         }
12900       else
12901         {
12902           tree op1 = TREE_OPERAND (t, 1);
12903           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12904           tree rhs1 = NULL_TREE;
12905           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12906           enum tree_code opcode = NOP_EXPR;
12907           if (code == OMP_ATOMIC_READ)
12908             {
12909               v = RECUR (TREE_OPERAND (op1, 0));
12910               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12911             }
12912           else if (code == OMP_ATOMIC_CAPTURE_OLD
12913                    || code == OMP_ATOMIC_CAPTURE_NEW)
12914             {
12915               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12916               v = RECUR (TREE_OPERAND (op1, 0));
12917               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12918               if (TREE_CODE (op11) == COMPOUND_EXPR)
12919                 {
12920                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12921                   op11 = TREE_OPERAND (op11, 1);
12922                 }
12923               lhs = RECUR (TREE_OPERAND (op11, 0));
12924               rhs = RECUR (TREE_OPERAND (op11, 1));
12925               opcode = TREE_CODE (op11);
12926             }
12927           else
12928             {
12929               code = OMP_ATOMIC;
12930               lhs = RECUR (TREE_OPERAND (op1, 0));
12931               rhs = RECUR (TREE_OPERAND (op1, 1));
12932             }
12933           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12934         }
12935       break;
12936
12937     case EXPR_PACK_EXPANSION:
12938       error ("invalid use of pack expansion expression");
12939       return error_mark_node;
12940
12941     case NONTYPE_ARGUMENT_PACK:
12942       error ("use %<...%> to expand argument pack");
12943       return error_mark_node;
12944
12945     default:
12946       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12947
12948       return tsubst_copy_and_build (t, args, complain, in_decl,
12949                                     /*function_p=*/false,
12950                                     integral_constant_expression_p);
12951     }
12952
12953   return NULL_TREE;
12954 #undef RECUR
12955 }
12956
12957 /* T is a postfix-expression that is not being used in a function
12958    call.  Return the substituted version of T.  */
12959
12960 static tree
12961 tsubst_non_call_postfix_expression (tree t, tree args,
12962                                     tsubst_flags_t complain,
12963                                     tree in_decl)
12964 {
12965   if (TREE_CODE (t) == SCOPE_REF)
12966     t = tsubst_qualified_id (t, args, complain, in_decl,
12967                              /*done=*/false, /*address_p=*/false);
12968   else
12969     t = tsubst_copy_and_build (t, args, complain, in_decl,
12970                                /*function_p=*/false,
12971                                /*integral_constant_expression_p=*/false);
12972
12973   return t;
12974 }
12975
12976 /* Like tsubst but deals with expressions and performs semantic
12977    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12978
12979 tree
12980 tsubst_copy_and_build (tree t,
12981                        tree args,
12982                        tsubst_flags_t complain,
12983                        tree in_decl,
12984                        bool function_p,
12985                        bool integral_constant_expression_p)
12986 {
12987 #define RECUR(NODE)                                             \
12988   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12989                          /*function_p=*/false,                  \
12990                          integral_constant_expression_p)
12991
12992   tree op1;
12993
12994   if (t == NULL_TREE || t == error_mark_node)
12995     return t;
12996
12997   switch (TREE_CODE (t))
12998     {
12999     case USING_DECL:
13000       t = DECL_NAME (t);
13001       /* Fall through.  */
13002     case IDENTIFIER_NODE:
13003       {
13004         tree decl;
13005         cp_id_kind idk;
13006         bool non_integral_constant_expression_p;
13007         const char *error_msg;
13008
13009         if (IDENTIFIER_TYPENAME_P (t))
13010           {
13011             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13012             t = mangle_conv_op_name_for_type (new_type);
13013           }
13014
13015         /* Look up the name.  */
13016         decl = lookup_name (t);
13017
13018         /* By convention, expressions use ERROR_MARK_NODE to indicate
13019            failure, not NULL_TREE.  */
13020         if (decl == NULL_TREE)
13021           decl = error_mark_node;
13022
13023         decl = finish_id_expression (t, decl, NULL_TREE,
13024                                      &idk,
13025                                      integral_constant_expression_p,
13026                                      /*allow_non_integral_constant_expression_p=*/false,
13027                                      &non_integral_constant_expression_p,
13028                                      /*template_p=*/false,
13029                                      /*done=*/true,
13030                                      /*address_p=*/false,
13031                                      /*template_arg_p=*/false,
13032                                      &error_msg,
13033                                      input_location);
13034         if (error_msg)
13035           error (error_msg);
13036         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13037           decl = unqualified_name_lookup_error (decl);
13038         return decl;
13039       }
13040
13041     case TEMPLATE_ID_EXPR:
13042       {
13043         tree object;
13044         tree templ = RECUR (TREE_OPERAND (t, 0));
13045         tree targs = TREE_OPERAND (t, 1);
13046
13047         if (targs)
13048           targs = tsubst_template_args (targs, args, complain, in_decl);
13049
13050         if (TREE_CODE (templ) == COMPONENT_REF)
13051           {
13052             object = TREE_OPERAND (templ, 0);
13053             templ = TREE_OPERAND (templ, 1);
13054           }
13055         else
13056           object = NULL_TREE;
13057         templ = lookup_template_function (templ, targs);
13058
13059         if (object)
13060           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13061                          object, templ, NULL_TREE);
13062         else
13063           return baselink_for_fns (templ);
13064       }
13065
13066     case INDIRECT_REF:
13067       {
13068         tree r = RECUR (TREE_OPERAND (t, 0));
13069
13070         if (REFERENCE_REF_P (t))
13071           {
13072             /* A type conversion to reference type will be enclosed in
13073                such an indirect ref, but the substitution of the cast
13074                will have also added such an indirect ref.  */
13075             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13076               r = convert_from_reference (r);
13077           }
13078         else
13079           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13080         return r;
13081       }
13082
13083     case NOP_EXPR:
13084       return build_nop
13085         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13086          RECUR (TREE_OPERAND (t, 0)));
13087
13088     case CAST_EXPR:
13089     case REINTERPRET_CAST_EXPR:
13090     case CONST_CAST_EXPR:
13091     case DYNAMIC_CAST_EXPR:
13092     case STATIC_CAST_EXPR:
13093       {
13094         tree type;
13095         tree op;
13096
13097         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13098         if (integral_constant_expression_p
13099             && !cast_valid_in_integral_constant_expression_p (type))
13100           {
13101             if (complain & tf_error)
13102               error ("a cast to a type other than an integral or "
13103                      "enumeration type cannot appear in a constant-expression");
13104             return error_mark_node; 
13105           }
13106
13107         op = RECUR (TREE_OPERAND (t, 0));
13108
13109         switch (TREE_CODE (t))
13110           {
13111           case CAST_EXPR:
13112             return build_functional_cast (type, op, complain);
13113           case REINTERPRET_CAST_EXPR:
13114             return build_reinterpret_cast (type, op, complain);
13115           case CONST_CAST_EXPR:
13116             return build_const_cast (type, op, complain);
13117           case DYNAMIC_CAST_EXPR:
13118             return build_dynamic_cast (type, op, complain);
13119           case STATIC_CAST_EXPR:
13120             return build_static_cast (type, op, complain);
13121           default:
13122             gcc_unreachable ();
13123           }
13124       }
13125
13126     case POSTDECREMENT_EXPR:
13127     case POSTINCREMENT_EXPR:
13128       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13129                                                 args, complain, in_decl);
13130       return build_x_unary_op (TREE_CODE (t), op1, complain);
13131
13132     case PREDECREMENT_EXPR:
13133     case PREINCREMENT_EXPR:
13134     case NEGATE_EXPR:
13135     case BIT_NOT_EXPR:
13136     case ABS_EXPR:
13137     case TRUTH_NOT_EXPR:
13138     case UNARY_PLUS_EXPR:  /* Unary + */
13139     case REALPART_EXPR:
13140     case IMAGPART_EXPR:
13141       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13142                                complain);
13143
13144     case ADDR_EXPR:
13145       op1 = TREE_OPERAND (t, 0);
13146       if (TREE_CODE (op1) == LABEL_DECL)
13147         return finish_label_address_expr (DECL_NAME (op1),
13148                                           EXPR_LOCATION (op1));
13149       if (TREE_CODE (op1) == SCOPE_REF)
13150         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13151                                    /*done=*/true, /*address_p=*/true);
13152       else
13153         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13154                                                   in_decl);
13155       return build_x_unary_op (ADDR_EXPR, op1, complain);
13156
13157     case PLUS_EXPR:
13158     case MINUS_EXPR:
13159     case MULT_EXPR:
13160     case TRUNC_DIV_EXPR:
13161     case CEIL_DIV_EXPR:
13162     case FLOOR_DIV_EXPR:
13163     case ROUND_DIV_EXPR:
13164     case EXACT_DIV_EXPR:
13165     case BIT_AND_EXPR:
13166     case BIT_IOR_EXPR:
13167     case BIT_XOR_EXPR:
13168     case TRUNC_MOD_EXPR:
13169     case FLOOR_MOD_EXPR:
13170     case TRUTH_ANDIF_EXPR:
13171     case TRUTH_ORIF_EXPR:
13172     case TRUTH_AND_EXPR:
13173     case TRUTH_OR_EXPR:
13174     case RSHIFT_EXPR:
13175     case LSHIFT_EXPR:
13176     case RROTATE_EXPR:
13177     case LROTATE_EXPR:
13178     case EQ_EXPR:
13179     case NE_EXPR:
13180     case MAX_EXPR:
13181     case MIN_EXPR:
13182     case LE_EXPR:
13183     case GE_EXPR:
13184     case LT_EXPR:
13185     case GT_EXPR:
13186     case MEMBER_REF:
13187     case DOTSTAR_EXPR:
13188       return build_x_binary_op
13189         (TREE_CODE (t),
13190          RECUR (TREE_OPERAND (t, 0)),
13191          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13192           ? ERROR_MARK
13193           : TREE_CODE (TREE_OPERAND (t, 0))),
13194          RECUR (TREE_OPERAND (t, 1)),
13195          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13196           ? ERROR_MARK
13197           : TREE_CODE (TREE_OPERAND (t, 1))),
13198          /*overload=*/NULL,
13199          complain);
13200
13201     case SCOPE_REF:
13202       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13203                                   /*address_p=*/false);
13204     case ARRAY_REF:
13205       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13206                                                 args, complain, in_decl);
13207       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13208
13209     case SIZEOF_EXPR:
13210       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13211         return tsubst_copy (t, args, complain, in_decl);
13212       /* Fall through */
13213       
13214     case ALIGNOF_EXPR:
13215       op1 = TREE_OPERAND (t, 0);
13216       if (!args)
13217         {
13218           /* When there are no ARGS, we are trying to evaluate a
13219              non-dependent expression from the parser.  Trying to do
13220              the substitutions may not work.  */
13221           if (!TYPE_P (op1))
13222             op1 = TREE_TYPE (op1);
13223         }
13224       else
13225         {
13226           ++cp_unevaluated_operand;
13227           ++c_inhibit_evaluation_warnings;
13228           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13229                                        /*function_p=*/false,
13230                                        /*integral_constant_expression_p=*/false);
13231           --cp_unevaluated_operand;
13232           --c_inhibit_evaluation_warnings;
13233         }
13234       if (TYPE_P (op1))
13235         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13236                                            complain & tf_error);
13237       else
13238         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13239                                            complain & tf_error);
13240
13241     case AT_ENCODE_EXPR:
13242       {
13243         op1 = TREE_OPERAND (t, 0);
13244         ++cp_unevaluated_operand;
13245         ++c_inhibit_evaluation_warnings;
13246         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13247                                      /*function_p=*/false,
13248                                      /*integral_constant_expression_p=*/false);
13249         --cp_unevaluated_operand;
13250         --c_inhibit_evaluation_warnings;
13251         return objc_build_encode_expr (op1);
13252       }
13253
13254     case NOEXCEPT_EXPR:
13255       op1 = TREE_OPERAND (t, 0);
13256       ++cp_unevaluated_operand;
13257       ++c_inhibit_evaluation_warnings;
13258       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13259                                    /*function_p=*/false,
13260                                    /*integral_constant_expression_p=*/false);
13261       --cp_unevaluated_operand;
13262       --c_inhibit_evaluation_warnings;
13263       return finish_noexcept_expr (op1, complain);
13264
13265     case MODOP_EXPR:
13266       {
13267         tree r = build_x_modify_expr
13268           (RECUR (TREE_OPERAND (t, 0)),
13269            TREE_CODE (TREE_OPERAND (t, 1)),
13270            RECUR (TREE_OPERAND (t, 2)),
13271            complain);
13272         /* TREE_NO_WARNING must be set if either the expression was
13273            parenthesized or it uses an operator such as >>= rather
13274            than plain assignment.  In the former case, it was already
13275            set and must be copied.  In the latter case,
13276            build_x_modify_expr sets it and it must not be reset
13277            here.  */
13278         if (TREE_NO_WARNING (t))
13279           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13280         return r;
13281       }
13282
13283     case ARROW_EXPR:
13284       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13285                                                 args, complain, in_decl);
13286       /* Remember that there was a reference to this entity.  */
13287       if (DECL_P (op1))
13288         mark_used (op1);
13289       return build_x_arrow (op1);
13290
13291     case NEW_EXPR:
13292       {
13293         tree placement = RECUR (TREE_OPERAND (t, 0));
13294         tree init = RECUR (TREE_OPERAND (t, 3));
13295         VEC(tree,gc) *placement_vec;
13296         VEC(tree,gc) *init_vec;
13297         tree ret;
13298
13299         if (placement == NULL_TREE)
13300           placement_vec = NULL;
13301         else
13302           {
13303             placement_vec = make_tree_vector ();
13304             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13305               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13306           }
13307
13308         /* If there was an initializer in the original tree, but it
13309            instantiated to an empty list, then we should pass a
13310            non-NULL empty vector to tell build_new that it was an
13311            empty initializer() rather than no initializer.  This can
13312            only happen when the initializer is a pack expansion whose
13313            parameter packs are of length zero.  */
13314         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13315           init_vec = NULL;
13316         else
13317           {
13318             init_vec = make_tree_vector ();
13319             if (init == void_zero_node)
13320               gcc_assert (init_vec != NULL);
13321             else
13322               {
13323                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13324                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13325               }
13326           }
13327
13328         ret = build_new (&placement_vec,
13329                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13330                          RECUR (TREE_OPERAND (t, 2)),
13331                          &init_vec,
13332                          NEW_EXPR_USE_GLOBAL (t),
13333                          complain);
13334
13335         if (placement_vec != NULL)
13336           release_tree_vector (placement_vec);
13337         if (init_vec != NULL)
13338           release_tree_vector (init_vec);
13339
13340         return ret;
13341       }
13342
13343     case DELETE_EXPR:
13344      return delete_sanity
13345        (RECUR (TREE_OPERAND (t, 0)),
13346         RECUR (TREE_OPERAND (t, 1)),
13347         DELETE_EXPR_USE_VEC (t),
13348         DELETE_EXPR_USE_GLOBAL (t),
13349         complain);
13350
13351     case COMPOUND_EXPR:
13352       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13353                                     RECUR (TREE_OPERAND (t, 1)),
13354                                     complain);
13355
13356     case CALL_EXPR:
13357       {
13358         tree function;
13359         VEC(tree,gc) *call_args;
13360         unsigned int nargs, i;
13361         bool qualified_p;
13362         bool koenig_p;
13363         tree ret;
13364
13365         function = CALL_EXPR_FN (t);
13366         /* When we parsed the expression,  we determined whether or
13367            not Koenig lookup should be performed.  */
13368         koenig_p = KOENIG_LOOKUP_P (t);
13369         if (TREE_CODE (function) == SCOPE_REF)
13370           {
13371             qualified_p = true;
13372             function = tsubst_qualified_id (function, args, complain, in_decl,
13373                                             /*done=*/false,
13374                                             /*address_p=*/false);
13375           }
13376         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13377           {
13378             /* Do nothing; calling tsubst_copy_and_build on an identifier
13379                would incorrectly perform unqualified lookup again.
13380
13381                Note that we can also have an IDENTIFIER_NODE if the earlier
13382                unqualified lookup found a member function; in that case
13383                koenig_p will be false and we do want to do the lookup
13384                again to find the instantiated member function.
13385
13386                FIXME but doing that causes c++/15272, so we need to stop
13387                using IDENTIFIER_NODE in that situation.  */
13388             qualified_p = false;
13389           }
13390         else
13391           {
13392             if (TREE_CODE (function) == COMPONENT_REF)
13393               {
13394                 tree op = TREE_OPERAND (function, 1);
13395
13396                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13397                                || (BASELINK_P (op)
13398                                    && BASELINK_QUALIFIED_P (op)));
13399               }
13400             else
13401               qualified_p = false;
13402
13403             function = tsubst_copy_and_build (function, args, complain,
13404                                               in_decl,
13405                                               !qualified_p,
13406                                               integral_constant_expression_p);
13407
13408             if (BASELINK_P (function))
13409               qualified_p = true;
13410           }
13411
13412         nargs = call_expr_nargs (t);
13413         call_args = make_tree_vector ();
13414         for (i = 0; i < nargs; ++i)
13415           {
13416             tree arg = CALL_EXPR_ARG (t, i);
13417
13418             if (!PACK_EXPANSION_P (arg))
13419               VEC_safe_push (tree, gc, call_args,
13420                              RECUR (CALL_EXPR_ARG (t, i)));
13421             else
13422               {
13423                 /* Expand the pack expansion and push each entry onto
13424                    CALL_ARGS.  */
13425                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13426                 if (TREE_CODE (arg) == TREE_VEC)
13427                   {
13428                     unsigned int len, j;
13429
13430                     len = TREE_VEC_LENGTH (arg);
13431                     for (j = 0; j < len; ++j)
13432                       {
13433                         tree value = TREE_VEC_ELT (arg, j);
13434                         if (value != NULL_TREE)
13435                           value = convert_from_reference (value);
13436                         VEC_safe_push (tree, gc, call_args, value);
13437                       }
13438                   }
13439                 else
13440                   {
13441                     /* A partial substitution.  Add one entry.  */
13442                     VEC_safe_push (tree, gc, call_args, arg);
13443                   }
13444               }
13445           }
13446
13447         /* We do not perform argument-dependent lookup if normal
13448            lookup finds a non-function, in accordance with the
13449            expected resolution of DR 218.  */
13450         if (koenig_p
13451             && ((is_overloaded_fn (function)
13452                  /* If lookup found a member function, the Koenig lookup is
13453                     not appropriate, even if an unqualified-name was used
13454                     to denote the function.  */
13455                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13456                 || TREE_CODE (function) == IDENTIFIER_NODE)
13457             /* Only do this when substitution turns a dependent call
13458                into a non-dependent call.  */
13459             && type_dependent_expression_p_push (t)
13460             && !any_type_dependent_arguments_p (call_args))
13461           function = perform_koenig_lookup (function, call_args, false,
13462                                             tf_none);
13463
13464         if (TREE_CODE (function) == IDENTIFIER_NODE
13465             && !any_type_dependent_arguments_p (call_args))
13466           {
13467             if (koenig_p && (complain & tf_warning_or_error))
13468               {
13469                 /* For backwards compatibility and good diagnostics, try
13470                    the unqualified lookup again if we aren't in SFINAE
13471                    context.  */
13472                 tree unq = (tsubst_copy_and_build
13473                             (function, args, complain, in_decl, true,
13474                              integral_constant_expression_p));
13475                 if (unq != function)
13476                   {
13477                     tree fn = unq;
13478                     if (TREE_CODE (fn) == COMPONENT_REF)
13479                       fn = TREE_OPERAND (fn, 1);
13480                     if (is_overloaded_fn (fn))
13481                       fn = get_first_fn (fn);
13482                     permerror (EXPR_LOC_OR_HERE (t),
13483                                "%qD was not declared in this scope, "
13484                                "and no declarations were found by "
13485                                "argument-dependent lookup at the point "
13486                                "of instantiation", function);
13487                     if (DECL_CLASS_SCOPE_P (fn))
13488                       {
13489                         inform (EXPR_LOC_OR_HERE (t),
13490                                 "declarations in dependent base %qT are "
13491                                 "not found by unqualified lookup",
13492                                 DECL_CLASS_CONTEXT (fn));
13493                         if (current_class_ptr)
13494                           inform (EXPR_LOC_OR_HERE (t),
13495                                   "use %<this->%D%> instead", function);
13496                         else
13497                           inform (EXPR_LOC_OR_HERE (t),
13498                                   "use %<%T::%D%> instead",
13499                                   current_class_name, function);
13500                       }
13501                     else
13502                       inform (0, "%q+D declared here, later in the "
13503                                 "translation unit", fn);
13504                     function = unq;
13505                   }
13506               }
13507             if (TREE_CODE (function) == IDENTIFIER_NODE)
13508               {
13509                 unqualified_name_lookup_error (function);
13510                 release_tree_vector (call_args);
13511                 return error_mark_node;
13512               }
13513           }
13514
13515         /* Remember that there was a reference to this entity.  */
13516         if (DECL_P (function))
13517           mark_used (function);
13518
13519         if (TREE_CODE (function) == OFFSET_REF)
13520           ret = build_offset_ref_call_from_tree (function, &call_args);
13521         else if (TREE_CODE (function) == COMPONENT_REF)
13522           {
13523             tree instance = TREE_OPERAND (function, 0);
13524             tree fn = TREE_OPERAND (function, 1);
13525
13526             if (processing_template_decl
13527                 && (type_dependent_expression_p (instance)
13528                     || (!BASELINK_P (fn)
13529                         && TREE_CODE (fn) != FIELD_DECL)
13530                     || type_dependent_expression_p (fn)
13531                     || any_type_dependent_arguments_p (call_args)))
13532               ret = build_nt_call_vec (function, call_args);
13533             else if (!BASELINK_P (fn))
13534               ret = finish_call_expr (function, &call_args,
13535                                        /*disallow_virtual=*/false,
13536                                        /*koenig_p=*/false,
13537                                        complain);
13538             else
13539               ret = (build_new_method_call
13540                       (instance, fn,
13541                        &call_args, NULL_TREE,
13542                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13543                        /*fn_p=*/NULL,
13544                        complain));
13545           }
13546         else
13547           ret = finish_call_expr (function, &call_args,
13548                                   /*disallow_virtual=*/qualified_p,
13549                                   koenig_p,
13550                                   complain);
13551
13552         release_tree_vector (call_args);
13553
13554         return ret;
13555       }
13556
13557     case COND_EXPR:
13558       return build_x_conditional_expr
13559         (RECUR (TREE_OPERAND (t, 0)),
13560          RECUR (TREE_OPERAND (t, 1)),
13561          RECUR (TREE_OPERAND (t, 2)),
13562          complain);
13563
13564     case PSEUDO_DTOR_EXPR:
13565       return finish_pseudo_destructor_expr
13566         (RECUR (TREE_OPERAND (t, 0)),
13567          RECUR (TREE_OPERAND (t, 1)),
13568          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13569
13570     case TREE_LIST:
13571       {
13572         tree purpose, value, chain;
13573
13574         if (t == void_list_node)
13575           return t;
13576
13577         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13578             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13579           {
13580             /* We have pack expansions, so expand those and
13581                create a new list out of it.  */
13582             tree purposevec = NULL_TREE;
13583             tree valuevec = NULL_TREE;
13584             tree chain;
13585             int i, len = -1;
13586
13587             /* Expand the argument expressions.  */
13588             if (TREE_PURPOSE (t))
13589               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13590                                                  complain, in_decl);
13591             if (TREE_VALUE (t))
13592               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13593                                                complain, in_decl);
13594
13595             /* Build the rest of the list.  */
13596             chain = TREE_CHAIN (t);
13597             if (chain && chain != void_type_node)
13598               chain = RECUR (chain);
13599
13600             /* Determine the number of arguments.  */
13601             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13602               {
13603                 len = TREE_VEC_LENGTH (purposevec);
13604                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13605               }
13606             else if (TREE_CODE (valuevec) == TREE_VEC)
13607               len = TREE_VEC_LENGTH (valuevec);
13608             else
13609               {
13610                 /* Since we only performed a partial substitution into
13611                    the argument pack, we only return a single list
13612                    node.  */
13613                 if (purposevec == TREE_PURPOSE (t)
13614                     && valuevec == TREE_VALUE (t)
13615                     && chain == TREE_CHAIN (t))
13616                   return t;
13617
13618                 return tree_cons (purposevec, valuevec, chain);
13619               }
13620             
13621             /* Convert the argument vectors into a TREE_LIST */
13622             i = len;
13623             while (i > 0)
13624               {
13625                 /* Grab the Ith values.  */
13626                 i--;
13627                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13628                                      : NULL_TREE;
13629                 value 
13630                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13631                              : NULL_TREE;
13632
13633                 /* Build the list (backwards).  */
13634                 chain = tree_cons (purpose, value, chain);
13635               }
13636
13637             return chain;
13638           }
13639
13640         purpose = TREE_PURPOSE (t);
13641         if (purpose)
13642           purpose = RECUR (purpose);
13643         value = TREE_VALUE (t);
13644         if (value)
13645           value = RECUR (value);
13646         chain = TREE_CHAIN (t);
13647         if (chain && chain != void_type_node)
13648           chain = RECUR (chain);
13649         if (purpose == TREE_PURPOSE (t)
13650             && value == TREE_VALUE (t)
13651             && chain == TREE_CHAIN (t))
13652           return t;
13653         return tree_cons (purpose, value, chain);
13654       }
13655
13656     case COMPONENT_REF:
13657       {
13658         tree object;
13659         tree object_type;
13660         tree member;
13661
13662         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13663                                                      args, complain, in_decl);
13664         /* Remember that there was a reference to this entity.  */
13665         if (DECL_P (object))
13666           mark_used (object);
13667         object_type = TREE_TYPE (object);
13668
13669         member = TREE_OPERAND (t, 1);
13670         if (BASELINK_P (member))
13671           member = tsubst_baselink (member,
13672                                     non_reference (TREE_TYPE (object)),
13673                                     args, complain, in_decl);
13674         else
13675           member = tsubst_copy (member, args, complain, in_decl);
13676         if (member == error_mark_node)
13677           return error_mark_node;
13678
13679         if (object_type && !CLASS_TYPE_P (object_type))
13680           {
13681             if (SCALAR_TYPE_P (object_type))
13682               {
13683                 tree s = NULL_TREE;
13684                 tree dtor = member;
13685
13686                 if (TREE_CODE (dtor) == SCOPE_REF)
13687                   {
13688                     s = TREE_OPERAND (dtor, 0);
13689                     dtor = TREE_OPERAND (dtor, 1);
13690                   }
13691                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13692                   {
13693                     dtor = TREE_OPERAND (dtor, 0);
13694                     if (TYPE_P (dtor))
13695                       return finish_pseudo_destructor_expr (object, s, dtor);
13696                   }
13697               }
13698           }
13699         else if (TREE_CODE (member) == SCOPE_REF
13700                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13701           {
13702             tree tmpl;
13703             tree args;
13704
13705             /* Lookup the template functions now that we know what the
13706                scope is.  */
13707             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13708             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13709             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13710                                             /*is_type_p=*/false,
13711                                             /*complain=*/false);
13712             if (BASELINK_P (member))
13713               {
13714                 BASELINK_FUNCTIONS (member)
13715                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13716                               args);
13717                 member = (adjust_result_of_qualified_name_lookup
13718                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13719                            object_type));
13720               }
13721             else
13722               {
13723                 qualified_name_lookup_error (object_type, tmpl, member,
13724                                              input_location);
13725                 return error_mark_node;
13726               }
13727           }
13728         else if (TREE_CODE (member) == SCOPE_REF
13729                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13730                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13731           {
13732             if (complain & tf_error)
13733               {
13734                 if (TYPE_P (TREE_OPERAND (member, 0)))
13735                   error ("%qT is not a class or namespace",
13736                          TREE_OPERAND (member, 0));
13737                 else
13738                   error ("%qD is not a class or namespace",
13739                          TREE_OPERAND (member, 0));
13740               }
13741             return error_mark_node;
13742           }
13743         else if (TREE_CODE (member) == FIELD_DECL)
13744           return finish_non_static_data_member (member, object, NULL_TREE);
13745
13746         return finish_class_member_access_expr (object, member,
13747                                                 /*template_p=*/false,
13748                                                 complain);
13749       }
13750
13751     case THROW_EXPR:
13752       return build_throw
13753         (RECUR (TREE_OPERAND (t, 0)));
13754
13755     case CONSTRUCTOR:
13756       {
13757         VEC(constructor_elt,gc) *n;
13758         constructor_elt *ce;
13759         unsigned HOST_WIDE_INT idx;
13760         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13761         bool process_index_p;
13762         int newlen;
13763         bool need_copy_p = false;
13764         tree r;
13765
13766         if (type == error_mark_node)
13767           return error_mark_node;
13768
13769         /* digest_init will do the wrong thing if we let it.  */
13770         if (type && TYPE_PTRMEMFUNC_P (type))
13771           return t;
13772
13773         /* We do not want to process the index of aggregate
13774            initializers as they are identifier nodes which will be
13775            looked up by digest_init.  */
13776         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13777
13778         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13779         newlen = VEC_length (constructor_elt, n);
13780         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13781           {
13782             if (ce->index && process_index_p)
13783               ce->index = RECUR (ce->index);
13784
13785             if (PACK_EXPANSION_P (ce->value))
13786               {
13787                 /* Substitute into the pack expansion.  */
13788                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13789                                                   in_decl);
13790
13791                 if (ce->value == error_mark_node
13792                     || PACK_EXPANSION_P (ce->value))
13793                   ;
13794                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13795                   /* Just move the argument into place.  */
13796                   ce->value = TREE_VEC_ELT (ce->value, 0);
13797                 else
13798                   {
13799                     /* Update the length of the final CONSTRUCTOR
13800                        arguments vector, and note that we will need to
13801                        copy.*/
13802                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13803                     need_copy_p = true;
13804                   }
13805               }
13806             else
13807               ce->value = RECUR (ce->value);
13808           }
13809
13810         if (need_copy_p)
13811           {
13812             VEC(constructor_elt,gc) *old_n = n;
13813
13814             n = VEC_alloc (constructor_elt, gc, newlen);
13815             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13816               {
13817                 if (TREE_CODE (ce->value) == TREE_VEC)
13818                   {
13819                     int i, len = TREE_VEC_LENGTH (ce->value);
13820                     for (i = 0; i < len; ++i)
13821                       CONSTRUCTOR_APPEND_ELT (n, 0,
13822                                               TREE_VEC_ELT (ce->value, i));
13823                   }
13824                 else
13825                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13826               }
13827           }
13828
13829         r = build_constructor (init_list_type_node, n);
13830         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13831
13832         if (TREE_HAS_CONSTRUCTOR (t))
13833           return finish_compound_literal (type, r, complain);
13834
13835         TREE_TYPE (r) = type;
13836         return r;
13837       }
13838
13839     case TYPEID_EXPR:
13840       {
13841         tree operand_0 = TREE_OPERAND (t, 0);
13842         if (TYPE_P (operand_0))
13843           {
13844             operand_0 = tsubst (operand_0, args, complain, in_decl);
13845             return get_typeid (operand_0);
13846           }
13847         else
13848           {
13849             operand_0 = RECUR (operand_0);
13850             return build_typeid (operand_0);
13851           }
13852       }
13853
13854     case VAR_DECL:
13855       if (!args)
13856         return t;
13857       /* Fall through */
13858
13859     case PARM_DECL:
13860       {
13861         tree r = tsubst_copy (t, args, complain, in_decl);
13862
13863         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13864           /* If the original type was a reference, we'll be wrapped in
13865              the appropriate INDIRECT_REF.  */
13866           r = convert_from_reference (r);
13867         return r;
13868       }
13869
13870     case VA_ARG_EXPR:
13871       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13872                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13873
13874     case OFFSETOF_EXPR:
13875       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13876
13877     case TRAIT_EXPR:
13878       {
13879         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13880                                   complain, in_decl);
13881
13882         tree type2 = TRAIT_EXPR_TYPE2 (t);
13883         if (type2)
13884           type2 = tsubst_copy (type2, args, complain, in_decl);
13885         
13886         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13887       }
13888
13889     case STMT_EXPR:
13890       {
13891         tree old_stmt_expr = cur_stmt_expr;
13892         tree stmt_expr = begin_stmt_expr ();
13893
13894         cur_stmt_expr = stmt_expr;
13895         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13896                      integral_constant_expression_p);
13897         stmt_expr = finish_stmt_expr (stmt_expr, false);
13898         cur_stmt_expr = old_stmt_expr;
13899
13900         /* If the resulting list of expression statement is empty,
13901            fold it further into void_zero_node.  */
13902         if (empty_expr_stmt_p (stmt_expr))
13903           stmt_expr = void_zero_node;
13904
13905         return stmt_expr;
13906       }
13907
13908     case CONST_DECL:
13909       t = tsubst_copy (t, args, complain, in_decl);
13910       /* As in finish_id_expression, we resolve enumeration constants
13911          to their underlying values.  */
13912       if (TREE_CODE (t) == CONST_DECL)
13913         {
13914           used_types_insert (TREE_TYPE (t));
13915           return DECL_INITIAL (t);
13916         }
13917       return t;
13918
13919     case LAMBDA_EXPR:
13920       {
13921         tree r = build_lambda_expr ();
13922
13923         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13924         TREE_TYPE (r) = type;
13925         CLASSTYPE_LAMBDA_EXPR (type) = r;
13926
13927         LAMBDA_EXPR_LOCATION (r)
13928           = LAMBDA_EXPR_LOCATION (t);
13929         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13930           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13931         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13932         LAMBDA_EXPR_DISCRIMINATOR (r)
13933           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13934         LAMBDA_EXPR_EXTRA_SCOPE (r)
13935           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13936         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
13937           {
13938             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
13939             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
13940           }
13941         else
13942           LAMBDA_EXPR_RETURN_TYPE (r)
13943             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13944
13945         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13946                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13947
13948         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13949         determine_visibility (TYPE_NAME (type));
13950         /* Now that we know visibility, instantiate the type so we have a
13951            declaration of the op() for later calls to lambda_function.  */
13952         complete_type (type);
13953
13954         /* The capture list refers to closure members, so this needs to
13955            wait until after we finish instantiating the type.  */
13956         LAMBDA_EXPR_CAPTURE_LIST (r)
13957           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13958
13959         return build_lambda_object (r);
13960       }
13961
13962     case TARGET_EXPR:
13963       /* We can get here for a constant initializer of non-dependent type.
13964          FIXME stop folding in cp_parser_initializer_clause.  */
13965       gcc_assert (TREE_CONSTANT (t));
13966       {
13967         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13968         TREE_CONSTANT (r) = true;
13969         return r;
13970       }
13971
13972     default:
13973       /* Handle Objective-C++ constructs, if appropriate.  */
13974       {
13975         tree subst
13976           = objcp_tsubst_copy_and_build (t, args, complain,
13977                                          in_decl, /*function_p=*/false);
13978         if (subst)
13979           return subst;
13980       }
13981       return tsubst_copy (t, args, complain, in_decl);
13982     }
13983
13984 #undef RECUR
13985 }
13986
13987 /* Verify that the instantiated ARGS are valid. For type arguments,
13988    make sure that the type's linkage is ok. For non-type arguments,
13989    make sure they are constants if they are integral or enumerations.
13990    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13991
13992 static bool
13993 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13994 {
13995   if (ARGUMENT_PACK_P (t))
13996     {
13997       tree vec = ARGUMENT_PACK_ARGS (t);
13998       int len = TREE_VEC_LENGTH (vec);
13999       bool result = false;
14000       int i;
14001
14002       for (i = 0; i < len; ++i)
14003         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14004           result = true;
14005       return result;
14006     }
14007   else if (TYPE_P (t))
14008     {
14009       /* [basic.link]: A name with no linkage (notably, the name
14010          of a class or enumeration declared in a local scope)
14011          shall not be used to declare an entity with linkage.
14012          This implies that names with no linkage cannot be used as
14013          template arguments
14014
14015          DR 757 relaxes this restriction for C++0x.  */
14016       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14017                  : no_linkage_check (t, /*relaxed_p=*/false));
14018
14019       if (nt)
14020         {
14021           /* DR 488 makes use of a type with no linkage cause
14022              type deduction to fail.  */
14023           if (complain & tf_error)
14024             {
14025               if (TYPE_ANONYMOUS_P (nt))
14026                 error ("%qT is/uses anonymous type", t);
14027               else
14028                 error ("template argument for %qD uses local type %qT",
14029                        tmpl, t);
14030             }
14031           return true;
14032         }
14033       /* In order to avoid all sorts of complications, we do not
14034          allow variably-modified types as template arguments.  */
14035       else if (variably_modified_type_p (t, NULL_TREE))
14036         {
14037           if (complain & tf_error)
14038             error ("%qT is a variably modified type", t);
14039           return true;
14040         }
14041     }
14042   /* A non-type argument of integral or enumerated type must be a
14043      constant.  */
14044   else if (TREE_TYPE (t)
14045            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14046            && !TREE_CONSTANT (t))
14047     {
14048       if (complain & tf_error)
14049         error ("integral expression %qE is not constant", t);
14050       return true;
14051     }
14052   return false;
14053 }
14054
14055 static bool
14056 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14057 {
14058   int ix, len = DECL_NTPARMS (tmpl);
14059   bool result = false;
14060
14061   for (ix = 0; ix != len; ix++)
14062     {
14063       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14064         result = true;
14065     }
14066   if (result && (complain & tf_error))
14067     error ("  trying to instantiate %qD", tmpl);
14068   return result;
14069 }
14070
14071 /* In C++0x, it's possible to have a function template whose type depends
14072    on itself recursively.  This is most obvious with decltype, but can also
14073    occur with enumeration scope (c++/48969).  So we need to catch infinite
14074    recursion and reject the substitution at deduction time; this function
14075    will return error_mark_node for any repeated substitution.
14076
14077    This also catches excessive recursion such as when f<N> depends on
14078    f<N-1> across all integers, and returns error_mark_node for all the
14079    substitutions back up to the initial one.
14080
14081    This is, of course, not reentrant.  */
14082
14083 static tree
14084 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14085 {
14086   static bool excessive_deduction_depth;
14087   static int deduction_depth;
14088   struct pending_template *old_last_pend = last_pending_template;
14089   struct tinst_level *old_error_tinst = last_error_tinst_level;
14090
14091   tree fntype = TREE_TYPE (fn);
14092   tree tinst;
14093   tree r;
14094
14095   if (excessive_deduction_depth)
14096     return error_mark_node;
14097
14098   tinst = build_tree_list (fn, targs);
14099   if (!push_tinst_level (tinst))
14100     {
14101       excessive_deduction_depth = true;
14102       ggc_free (tinst);
14103       return error_mark_node;
14104     }
14105
14106   input_location = DECL_SOURCE_LOCATION (fn);
14107   ++deduction_depth;
14108   push_deduction_access_scope (fn);
14109   r = tsubst (fntype, targs, complain, NULL_TREE);
14110   pop_deduction_access_scope (fn);
14111   --deduction_depth;
14112
14113   if (excessive_deduction_depth)
14114     {
14115       r = error_mark_node;
14116       if (deduction_depth == 0)
14117         /* Reset once we're all the way out.  */
14118         excessive_deduction_depth = false;
14119     }
14120
14121   pop_tinst_level ();
14122   /* We can't free this if a pending_template entry or last_error_tinst_level
14123      is pointing at it.  */
14124   if (last_pending_template == old_last_pend
14125       && last_error_tinst_level == old_error_tinst)
14126     ggc_free (tinst);
14127   return r;
14128 }
14129
14130 /* Instantiate the indicated variable or function template TMPL with
14131    the template arguments in TARG_PTR.  */
14132
14133 static tree
14134 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14135 {
14136   tree targ_ptr = orig_args;
14137   tree fndecl;
14138   tree gen_tmpl;
14139   tree spec;
14140   HOST_WIDE_INT saved_processing_template_decl;
14141
14142   if (tmpl == error_mark_node)
14143     return error_mark_node;
14144
14145   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14146
14147   /* If this function is a clone, handle it specially.  */
14148   if (DECL_CLONED_FUNCTION_P (tmpl))
14149     {
14150       tree spec;
14151       tree clone;
14152
14153       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14154          DECL_CLONED_FUNCTION.  */
14155       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14156                                    targ_ptr, complain);
14157       if (spec == error_mark_node)
14158         return error_mark_node;
14159
14160       /* Look for the clone.  */
14161       FOR_EACH_CLONE (clone, spec)
14162         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14163           return clone;
14164       /* We should always have found the clone by now.  */
14165       gcc_unreachable ();
14166       return NULL_TREE;
14167     }
14168
14169   /* Check to see if we already have this specialization.  */
14170   gen_tmpl = most_general_template (tmpl);
14171   if (tmpl != gen_tmpl)
14172     /* The TMPL is a partial instantiation.  To get a full set of
14173        arguments we must add the arguments used to perform the
14174        partial instantiation.  */
14175     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14176                                             targ_ptr);
14177
14178   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14179      but it doesn't seem to be on the hot path.  */
14180   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14181
14182   gcc_assert (tmpl == gen_tmpl
14183               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14184                   == spec)
14185               || fndecl == NULL_TREE);
14186
14187   if (spec != NULL_TREE)
14188     return spec;
14189
14190   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14191                                complain))
14192     return error_mark_node;
14193
14194   /* We are building a FUNCTION_DECL, during which the access of its
14195      parameters and return types have to be checked.  However this
14196      FUNCTION_DECL which is the desired context for access checking
14197      is not built yet.  We solve this chicken-and-egg problem by
14198      deferring all checks until we have the FUNCTION_DECL.  */
14199   push_deferring_access_checks (dk_deferred);
14200
14201   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14202      (because, for example, we have encountered a non-dependent
14203      function call in the body of a template function and must now
14204      determine which of several overloaded functions will be called),
14205      within the instantiation itself we are not processing a
14206      template.  */  
14207   saved_processing_template_decl = processing_template_decl;
14208   processing_template_decl = 0;
14209   /* Substitute template parameters to obtain the specialization.  */
14210   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14211                    targ_ptr, complain, gen_tmpl);
14212   processing_template_decl = saved_processing_template_decl;
14213   if (fndecl == error_mark_node)
14214     return error_mark_node;
14215
14216   /* Now we know the specialization, compute access previously
14217      deferred.  */
14218   push_access_scope (fndecl);
14219
14220   /* Some typedefs referenced from within the template code need to be access
14221      checked at template instantiation time, i.e now. These types were
14222      added to the template at parsing time. Let's get those and perfom
14223      the acces checks then.  */
14224   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14225   perform_deferred_access_checks ();
14226   pop_access_scope (fndecl);
14227   pop_deferring_access_checks ();
14228
14229   /* The DECL_TI_TEMPLATE should always be the immediate parent
14230      template, not the most general template.  */
14231   DECL_TI_TEMPLATE (fndecl) = tmpl;
14232
14233   /* If we've just instantiated the main entry point for a function,
14234      instantiate all the alternate entry points as well.  We do this
14235      by cloning the instantiation of the main entry point, not by
14236      instantiating the template clones.  */
14237   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14238     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14239
14240   return fndecl;
14241 }
14242
14243 /* Wrapper for instantiate_template_1.  */
14244
14245 tree
14246 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14247 {
14248   tree ret;
14249   timevar_push (TV_TEMPLATE_INST);
14250   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14251   timevar_pop (TV_TEMPLATE_INST);
14252   return ret;
14253 }
14254
14255 /* We're going to do deduction substitution on the type of TMPL, a function
14256    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14257    disable access checking.  */
14258
14259 static void
14260 push_deduction_access_scope (tree tmpl)
14261 {
14262   if (cxx_dialect >= cxx0x)
14263     {
14264       int ptd = processing_template_decl;
14265       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14266       /* Preserve processing_template_decl across push_to_top_level.  */
14267       if (ptd && !processing_template_decl)
14268         ++processing_template_decl;
14269     }
14270   else
14271     push_deferring_access_checks (dk_no_check);
14272 }
14273
14274 /* And pop back out.  */
14275
14276 static void
14277 pop_deduction_access_scope (tree tmpl)
14278 {
14279   if (cxx_dialect >= cxx0x)
14280     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14281   else
14282     pop_deferring_access_checks ();
14283 }
14284
14285 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14286    NARGS elements of the arguments that are being used when calling
14287    it.  TARGS is a vector into which the deduced template arguments
14288    are placed.
14289
14290    Return zero for success, 2 for an incomplete match that doesn't resolve
14291    all the types, and 1 for complete failure.  An error message will be
14292    printed only for an incomplete match.
14293
14294    If FN is a conversion operator, or we are trying to produce a specific
14295    specialization, RETURN_TYPE is the return type desired.
14296
14297    The EXPLICIT_TARGS are explicit template arguments provided via a
14298    template-id.
14299
14300    The parameter STRICT is one of:
14301
14302    DEDUCE_CALL:
14303      We are deducing arguments for a function call, as in
14304      [temp.deduct.call].
14305
14306    DEDUCE_CONV:
14307      We are deducing arguments for a conversion function, as in
14308      [temp.deduct.conv].
14309
14310    DEDUCE_EXACT:
14311      We are deducing arguments when doing an explicit instantiation
14312      as in [temp.explicit], when determining an explicit specialization
14313      as in [temp.expl.spec], or when taking the address of a function
14314      template, as in [temp.deduct.funcaddr].  */
14315
14316 int
14317 fn_type_unification (tree fn,
14318                      tree explicit_targs,
14319                      tree targs,
14320                      const tree *args,
14321                      unsigned int nargs,
14322                      tree return_type,
14323                      unification_kind_t strict,
14324                      int flags,
14325                      bool explain_p)
14326 {
14327   tree parms;
14328   tree fntype;
14329   int result;
14330   bool incomplete_argument_packs_p = false;
14331
14332   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14333
14334   fntype = TREE_TYPE (fn);
14335   if (explicit_targs)
14336     {
14337       /* [temp.deduct]
14338
14339          The specified template arguments must match the template
14340          parameters in kind (i.e., type, nontype, template), and there
14341          must not be more arguments than there are parameters;
14342          otherwise type deduction fails.
14343
14344          Nontype arguments must match the types of the corresponding
14345          nontype template parameters, or must be convertible to the
14346          types of the corresponding nontype parameters as specified in
14347          _temp.arg.nontype_, otherwise type deduction fails.
14348
14349          All references in the function type of the function template
14350          to the corresponding template parameters are replaced by the
14351          specified template argument values.  If a substitution in a
14352          template parameter or in the function type of the function
14353          template results in an invalid type, type deduction fails.  */
14354       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14355       int i, len = TREE_VEC_LENGTH (tparms);
14356       tree converted_args;
14357       bool incomplete = false;
14358
14359       if (explicit_targs == error_mark_node)
14360         return unify_invalid (explain_p);
14361
14362       converted_args
14363         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14364                                   (explain_p
14365                                    ? tf_warning_or_error
14366                                    : tf_none),
14367                                    /*require_all_args=*/false,
14368                                    /*use_default_args=*/false));
14369       if (converted_args == error_mark_node)
14370         return 1;
14371
14372       /* Substitute the explicit args into the function type.  This is
14373          necessary so that, for instance, explicitly declared function
14374          arguments can match null pointed constants.  If we were given
14375          an incomplete set of explicit args, we must not do semantic
14376          processing during substitution as we could create partial
14377          instantiations.  */
14378       for (i = 0; i < len; i++)
14379         {
14380           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14381           bool parameter_pack = false;
14382
14383           /* Dig out the actual parm.  */
14384           if (TREE_CODE (parm) == TYPE_DECL
14385               || TREE_CODE (parm) == TEMPLATE_DECL)
14386             {
14387               parm = TREE_TYPE (parm);
14388               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14389             }
14390           else if (TREE_CODE (parm) == PARM_DECL)
14391             {
14392               parm = DECL_INITIAL (parm);
14393               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14394             }
14395
14396           if (parameter_pack)
14397             {
14398               int level, idx;
14399               tree targ;
14400               template_parm_level_and_index (parm, &level, &idx);
14401
14402               /* Mark the argument pack as "incomplete". We could
14403                  still deduce more arguments during unification.
14404                  We remove this mark in type_unification_real.  */
14405               targ = TMPL_ARG (converted_args, level, idx);
14406               if (targ)
14407                 {
14408                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14409                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14410                     = ARGUMENT_PACK_ARGS (targ);
14411                 }
14412
14413               /* We have some incomplete argument packs.  */
14414               incomplete_argument_packs_p = true;
14415             }
14416         }
14417
14418       if (incomplete_argument_packs_p)
14419         /* Any substitution is guaranteed to be incomplete if there
14420            are incomplete argument packs, because we can still deduce
14421            more arguments.  */
14422         incomplete = 1;
14423       else
14424         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
14425
14426       processing_template_decl += incomplete;
14427       fntype = deduction_tsubst_fntype (fn, converted_args,
14428                                         (explain_p
14429                                          ? tf_warning_or_error
14430                                          : tf_none));
14431       processing_template_decl -= incomplete;
14432
14433       if (fntype == error_mark_node)
14434         return 1;
14435
14436       /* Place the explicitly specified arguments in TARGS.  */
14437       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14438         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14439     }
14440
14441   /* Never do unification on the 'this' parameter.  */
14442   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14443
14444   if (return_type)
14445     {
14446       tree *new_args;
14447
14448       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14449       new_args = XALLOCAVEC (tree, nargs + 1);
14450       new_args[0] = return_type;
14451       memcpy (new_args + 1, args, nargs * sizeof (tree));
14452       args = new_args;
14453       ++nargs;
14454     }
14455
14456   /* We allow incomplete unification without an error message here
14457      because the standard doesn't seem to explicitly prohibit it.  Our
14458      callers must be ready to deal with unification failures in any
14459      event.  */
14460   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14461                                   targs, parms, args, nargs, /*subr=*/0,
14462                                   strict, flags, explain_p);
14463
14464   /* Now that we have bindings for all of the template arguments,
14465      ensure that the arguments deduced for the template template
14466      parameters have compatible template parameter lists.  We cannot
14467      check this property before we have deduced all template
14468      arguments, because the template parameter types of a template
14469      template parameter might depend on prior template parameters
14470      deduced after the template template parameter.  The following
14471      ill-formed example illustrates this issue:
14472
14473        template<typename T, template<T> class C> void f(C<5>, T);
14474
14475        template<int N> struct X {};
14476
14477        void g() {
14478          f(X<5>(), 5l); // error: template argument deduction fails
14479        }
14480
14481      The template parameter list of 'C' depends on the template type
14482      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14483      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14484      time that we deduce 'C'.  */
14485   if (result == 0
14486       && !template_template_parm_bindings_ok_p 
14487            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14488     return unify_inconsistent_template_template_parameters (explain_p);
14489
14490   if (result == 0)
14491     /* All is well so far.  Now, check:
14492
14493        [temp.deduct]
14494
14495        When all template arguments have been deduced, all uses of
14496        template parameters in nondeduced contexts are replaced with
14497        the corresponding deduced argument values.  If the
14498        substitution results in an invalid type, as described above,
14499        type deduction fails.  */
14500     {
14501       tree substed = deduction_tsubst_fntype (fn, targs,
14502                                               (explain_p
14503                                                ? tf_warning_or_error
14504                                                : tf_none));
14505       if (substed == error_mark_node)
14506         return 1;
14507
14508       /* If we're looking for an exact match, check that what we got
14509          is indeed an exact match.  It might not be if some template
14510          parameters are used in non-deduced contexts.  */
14511       if (strict == DEDUCE_EXACT)
14512         {
14513           unsigned int i;
14514
14515           tree sarg
14516             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14517           if (return_type)
14518             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14519           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14520             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14521               return unify_type_mismatch (explain_p, args[i],
14522                                           TREE_VALUE (sarg));
14523         }
14524     }
14525
14526   return result;
14527 }
14528
14529 /* Adjust types before performing type deduction, as described in
14530    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14531    sections are symmetric.  PARM is the type of a function parameter
14532    or the return type of the conversion function.  ARG is the type of
14533    the argument passed to the call, or the type of the value
14534    initialized with the result of the conversion function.
14535    ARG_EXPR is the original argument expression, which may be null.  */
14536
14537 static int
14538 maybe_adjust_types_for_deduction (unification_kind_t strict,
14539                                   tree* parm,
14540                                   tree* arg,
14541                                   tree arg_expr)
14542 {
14543   int result = 0;
14544
14545   switch (strict)
14546     {
14547     case DEDUCE_CALL:
14548       break;
14549
14550     case DEDUCE_CONV:
14551       {
14552         /* Swap PARM and ARG throughout the remainder of this
14553            function; the handling is precisely symmetric since PARM
14554            will initialize ARG rather than vice versa.  */
14555         tree* temp = parm;
14556         parm = arg;
14557         arg = temp;
14558         break;
14559       }
14560
14561     case DEDUCE_EXACT:
14562       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14563          too, but here handle it by stripping the reference from PARM
14564          rather than by adding it to ARG.  */
14565       if (TREE_CODE (*parm) == REFERENCE_TYPE
14566           && TYPE_REF_IS_RVALUE (*parm)
14567           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14568           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14569           && TREE_CODE (*arg) == REFERENCE_TYPE
14570           && !TYPE_REF_IS_RVALUE (*arg))
14571         *parm = TREE_TYPE (*parm);
14572       /* Nothing else to do in this case.  */
14573       return 0;
14574
14575     default:
14576       gcc_unreachable ();
14577     }
14578
14579   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14580     {
14581       /* [temp.deduct.call]
14582
14583          If P is not a reference type:
14584
14585          --If A is an array type, the pointer type produced by the
14586          array-to-pointer standard conversion (_conv.array_) is
14587          used in place of A for type deduction; otherwise,
14588
14589          --If A is a function type, the pointer type produced by
14590          the function-to-pointer standard conversion
14591          (_conv.func_) is used in place of A for type deduction;
14592          otherwise,
14593
14594          --If A is a cv-qualified type, the top level
14595          cv-qualifiers of A's type are ignored for type
14596          deduction.  */
14597       if (TREE_CODE (*arg) == ARRAY_TYPE)
14598         *arg = build_pointer_type (TREE_TYPE (*arg));
14599       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14600         *arg = build_pointer_type (*arg);
14601       else
14602         *arg = TYPE_MAIN_VARIANT (*arg);
14603     }
14604
14605   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14606      of the form T&&, where T is a template parameter, and the argument
14607      is an lvalue, T is deduced as A& */
14608   if (TREE_CODE (*parm) == REFERENCE_TYPE
14609       && TYPE_REF_IS_RVALUE (*parm)
14610       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14611       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14612       && (arg_expr ? real_lvalue_p (arg_expr)
14613           /* try_one_overload doesn't provide an arg_expr, but
14614              functions are always lvalues.  */
14615           : TREE_CODE (*arg) == FUNCTION_TYPE))
14616     *arg = build_reference_type (*arg);
14617
14618   /* [temp.deduct.call]
14619
14620      If P is a cv-qualified type, the top level cv-qualifiers
14621      of P's type are ignored for type deduction.  If P is a
14622      reference type, the type referred to by P is used for
14623      type deduction.  */
14624   *parm = TYPE_MAIN_VARIANT (*parm);
14625   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14626     {
14627       *parm = TREE_TYPE (*parm);
14628       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14629     }
14630
14631   /* DR 322. For conversion deduction, remove a reference type on parm
14632      too (which has been swapped into ARG).  */
14633   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14634     *arg = TREE_TYPE (*arg);
14635
14636   return result;
14637 }
14638
14639 /* Most parms like fn_type_unification.
14640
14641    If SUBR is 1, we're being called recursively (to unify the
14642    arguments of a function or method parameter of a function
14643    template). */
14644
14645 static int
14646 type_unification_real (tree tparms,
14647                        tree targs,
14648                        tree xparms,
14649                        const tree *xargs,
14650                        unsigned int xnargs,
14651                        int subr,
14652                        unification_kind_t strict,
14653                        int flags,
14654                        bool explain_p)
14655 {
14656   tree parm, arg, arg_expr;
14657   int i;
14658   int ntparms = TREE_VEC_LENGTH (tparms);
14659   int sub_strict;
14660   int saw_undeduced = 0;
14661   tree parms;
14662   const tree *args;
14663   unsigned int nargs;
14664   unsigned int ia;
14665
14666   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14667   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14668   gcc_assert (ntparms > 0);
14669
14670   /* Reset the number of non-defaulted template arguments contained
14671      in TARGS.  */
14672   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14673
14674   switch (strict)
14675     {
14676     case DEDUCE_CALL:
14677       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14678                     | UNIFY_ALLOW_DERIVED);
14679       break;
14680
14681     case DEDUCE_CONV:
14682       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14683       break;
14684
14685     case DEDUCE_EXACT:
14686       sub_strict = UNIFY_ALLOW_NONE;
14687       break;
14688
14689     default:
14690       gcc_unreachable ();
14691     }
14692
14693  again:
14694   parms = xparms;
14695   args = xargs;
14696   nargs = xnargs;
14697
14698   ia = 0;
14699   while (parms && parms != void_list_node
14700          && ia < nargs)
14701     {
14702       parm = TREE_VALUE (parms);
14703
14704       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14705           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14706         /* For a function parameter pack that occurs at the end of the
14707            parameter-declaration-list, the type A of each remaining
14708            argument of the call is compared with the type P of the
14709            declarator-id of the function parameter pack.  */
14710         break;
14711
14712       parms = TREE_CHAIN (parms);
14713
14714       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14715         /* For a function parameter pack that does not occur at the
14716            end of the parameter-declaration-list, the type of the
14717            parameter pack is a non-deduced context.  */
14718         continue;
14719
14720       arg = args[ia];
14721       ++ia;
14722       arg_expr = NULL;
14723
14724       if (arg == error_mark_node)
14725         return unify_invalid (explain_p);
14726       if (arg == unknown_type_node)
14727         /* We can't deduce anything from this, but we might get all the
14728            template args from other function args.  */
14729         continue;
14730
14731       /* Conversions will be performed on a function argument that
14732          corresponds with a function parameter that contains only
14733          non-deducible template parameters and explicitly specified
14734          template parameters.  */
14735       if (!uses_template_parms (parm))
14736         {
14737           tree type;
14738
14739           if (!TYPE_P (arg))
14740             type = TREE_TYPE (arg);
14741           else
14742             type = arg;
14743
14744           if (same_type_p (parm, type))
14745             continue;
14746           if (strict == DEDUCE_CONV)
14747             {
14748               if (can_convert_arg (type, parm, NULL_TREE, flags))
14749                 continue;
14750             }
14751           else if (strict != DEDUCE_EXACT)
14752             {
14753               if (can_convert_arg (parm, type,
14754                                    TYPE_P (arg) ? NULL_TREE : arg,
14755                                    flags))
14756                 continue;
14757             }
14758
14759           if (strict == DEDUCE_EXACT)
14760             return unify_type_mismatch (explain_p, parm, arg);
14761           else
14762             return unify_arg_conversion (explain_p, parm, type, arg);
14763         }
14764
14765       if (!TYPE_P (arg))
14766         {
14767           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14768           if (type_unknown_p (arg))
14769             {
14770               /* [temp.deduct.type] 
14771
14772                  A template-argument can be deduced from a pointer to
14773                  function or pointer to member function argument if
14774                  the set of overloaded functions does not contain
14775                  function templates and at most one of a set of
14776                  overloaded functions provides a unique match.  */
14777               if (resolve_overloaded_unification
14778                   (tparms, targs, parm, arg, strict, sub_strict, explain_p))
14779                 continue;
14780
14781               return unify_overload_resolution_failure (explain_p, arg);
14782             }
14783           arg_expr = arg;
14784           arg = unlowered_expr_type (arg);
14785           if (arg == error_mark_node)
14786             return unify_invalid (explain_p);
14787         }
14788
14789       {
14790         int arg_strict = sub_strict;
14791
14792         if (!subr)
14793           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14794                                                           arg_expr);
14795
14796         if (arg == init_list_type_node && arg_expr)
14797           arg = arg_expr;
14798         if (unify (tparms, targs, parm, arg, arg_strict, explain_p))
14799           /* If unification failed, the recursive call will have updated
14800              UI appropriately.  */
14801           return 1;
14802       }
14803     }
14804
14805
14806   if (parms 
14807       && parms != void_list_node
14808       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14809     {
14810       /* Unify the remaining arguments with the pack expansion type.  */
14811       tree argvec;
14812       tree parmvec = make_tree_vec (1);
14813
14814       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14815       argvec = make_tree_vec (nargs - ia);
14816       for (i = 0; ia < nargs; ++ia, ++i)
14817         TREE_VEC_ELT (argvec, i) = args[ia];
14818
14819       /* Copy the parameter into parmvec.  */
14820       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14821       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14822                                 /*call_args_p=*/true, /*subr=*/subr, explain_p))
14823         return 1;
14824
14825       /* Advance to the end of the list of parameters.  */
14826       parms = TREE_CHAIN (parms);
14827     }
14828
14829   /* Fail if we've reached the end of the parm list, and more args
14830      are present, and the parm list isn't variadic.  */
14831   if (ia < nargs && parms == void_list_node)
14832     return unify_too_many_arguments (explain_p, nargs, ia);
14833   /* Fail if parms are left and they don't have default values.  */
14834   if (parms && parms != void_list_node
14835       && TREE_PURPOSE (parms) == NULL_TREE)
14836     {
14837       unsigned int count = nargs;
14838       tree p = parms;
14839       while (p && p != void_list_node)
14840         {
14841           count++;
14842           p = TREE_CHAIN (p);
14843         }
14844       return unify_too_few_arguments (explain_p, ia, count);
14845     }
14846
14847   if (!subr)
14848     {
14849       tsubst_flags_t complain = (explain_p
14850                                  ? tf_warning_or_error
14851                                  : tf_none);
14852
14853       /* Check to see if we need another pass before we start clearing
14854          ARGUMENT_PACK_INCOMPLETE_P.  */
14855       for (i = 0; i < ntparms; i++)
14856         {
14857           tree targ = TREE_VEC_ELT (targs, i);
14858           tree tparm = TREE_VEC_ELT (tparms, i);
14859
14860           if (targ || tparm == error_mark_node)
14861             continue;
14862           tparm = TREE_VALUE (tparm);
14863
14864           /* If this is an undeduced nontype parameter that depends on
14865              a type parameter, try another pass; its type may have been
14866              deduced from a later argument than the one from which
14867              this parameter can be deduced.  */
14868           if (TREE_CODE (tparm) == PARM_DECL
14869               && uses_template_parms (TREE_TYPE (tparm))
14870               && !saw_undeduced++)
14871             goto again;
14872         }
14873
14874       for (i = 0; i < ntparms; i++)
14875         {
14876           tree targ = TREE_VEC_ELT (targs, i);
14877           tree tparm = TREE_VEC_ELT (tparms, i);
14878
14879           /* Clear the "incomplete" flags on all argument packs now so that
14880              substituting them into later default arguments works.  */
14881           if (targ && ARGUMENT_PACK_P (targ))
14882             {
14883               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14884               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14885             }
14886
14887           if (targ || tparm == error_mark_node)
14888             continue;
14889           tparm = TREE_VALUE (tparm);
14890
14891           /* Core issue #226 (C++0x) [temp.deduct]:
14892
14893              If a template argument has not been deduced, its
14894              default template argument, if any, is used. 
14895
14896              When we are in C++98 mode, TREE_PURPOSE will either
14897              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14898              to explicitly check cxx_dialect here.  */
14899           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14900             {
14901               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14902               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14903               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
14904               arg = convert_template_argument (parm, arg, targs, complain,
14905                                                i, NULL_TREE);
14906               if (arg == error_mark_node)
14907                 return 1;
14908               else
14909                 {
14910                   TREE_VEC_ELT (targs, i) = arg;
14911                   /* The position of the first default template argument,
14912                      is also the number of non-defaulted arguments in TARGS.
14913                      Record that.  */
14914                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14915                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14916                   continue;
14917                 }
14918             }
14919
14920           /* If the type parameter is a parameter pack, then it will
14921              be deduced to an empty parameter pack.  */
14922           if (template_parameter_pack_p (tparm))
14923             {
14924               tree arg;
14925
14926               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14927                 {
14928                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14929                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14930                   TREE_CONSTANT (arg) = 1;
14931                 }
14932               else
14933                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14934
14935               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14936
14937               TREE_VEC_ELT (targs, i) = arg;
14938               continue;
14939             }
14940
14941           return unify_parameter_deduction_failure (explain_p, tparm);
14942         }
14943     }
14944 #ifdef ENABLE_CHECKING
14945   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14946     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14947 #endif
14948
14949   return unify_success (explain_p);
14950 }
14951
14952 /* Subroutine of type_unification_real.  Args are like the variables
14953    at the call site.  ARG is an overloaded function (or template-id);
14954    we try deducing template args from each of the overloads, and if
14955    only one succeeds, we go with that.  Modifies TARGS and returns
14956    true on success.  */
14957
14958 static bool
14959 resolve_overloaded_unification (tree tparms,
14960                                 tree targs,
14961                                 tree parm,
14962                                 tree arg,
14963                                 unification_kind_t strict,
14964                                 int sub_strict,
14965                                 bool explain_p)
14966 {
14967   tree tempargs = copy_node (targs);
14968   int good = 0;
14969   tree goodfn = NULL_TREE;
14970   bool addr_p;
14971
14972   if (TREE_CODE (arg) == ADDR_EXPR)
14973     {
14974       arg = TREE_OPERAND (arg, 0);
14975       addr_p = true;
14976     }
14977   else
14978     addr_p = false;
14979
14980   if (TREE_CODE (arg) == COMPONENT_REF)
14981     /* Handle `&x' where `x' is some static or non-static member
14982        function name.  */
14983     arg = TREE_OPERAND (arg, 1);
14984
14985   if (TREE_CODE (arg) == OFFSET_REF)
14986     arg = TREE_OPERAND (arg, 1);
14987
14988   /* Strip baselink information.  */
14989   if (BASELINK_P (arg))
14990     arg = BASELINK_FUNCTIONS (arg);
14991
14992   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14993     {
14994       /* If we got some explicit template args, we need to plug them into
14995          the affected templates before we try to unify, in case the
14996          explicit args will completely resolve the templates in question.  */
14997
14998       int ok = 0;
14999       tree expl_subargs = TREE_OPERAND (arg, 1);
15000       arg = TREE_OPERAND (arg, 0);
15001
15002       for (; arg; arg = OVL_NEXT (arg))
15003         {
15004           tree fn = OVL_CURRENT (arg);
15005           tree subargs, elem;
15006
15007           if (TREE_CODE (fn) != TEMPLATE_DECL)
15008             continue;
15009
15010           ++processing_template_decl;
15011           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15012                                   expl_subargs, /*check_ret=*/false);
15013           if (subargs && !any_dependent_template_arguments_p (subargs))
15014             {
15015               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15016               if (try_one_overload (tparms, targs, tempargs, parm,
15017                                     elem, strict, sub_strict, addr_p, explain_p)
15018                   && (!goodfn || !decls_match (goodfn, elem)))
15019                 {
15020                   goodfn = elem;
15021                   ++good;
15022                 }
15023             }
15024           else if (subargs)
15025             ++ok;
15026           --processing_template_decl;
15027         }
15028       /* If no templates (or more than one) are fully resolved by the
15029          explicit arguments, this template-id is a non-deduced context; it
15030          could still be OK if we deduce all template arguments for the
15031          enclosing call through other arguments.  */
15032       if (good != 1)
15033         good = ok;
15034     }
15035   else if (TREE_CODE (arg) != OVERLOAD
15036            && TREE_CODE (arg) != FUNCTION_DECL)
15037     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15038        -- but the deduction does not succeed because the expression is
15039        not just the function on its own.  */
15040     return false;
15041   else
15042     for (; arg; arg = OVL_NEXT (arg))
15043       if (try_one_overload (tparms, targs, tempargs, parm,
15044                             TREE_TYPE (OVL_CURRENT (arg)),
15045                             strict, sub_strict, addr_p, explain_p)
15046           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15047         {
15048           goodfn = OVL_CURRENT (arg);
15049           ++good;
15050         }
15051
15052   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15053      to function or pointer to member function argument if the set of
15054      overloaded functions does not contain function templates and at most
15055      one of a set of overloaded functions provides a unique match.
15056
15057      So if we found multiple possibilities, we return success but don't
15058      deduce anything.  */
15059
15060   if (good == 1)
15061     {
15062       int i = TREE_VEC_LENGTH (targs);
15063       for (; i--; )
15064         if (TREE_VEC_ELT (tempargs, i))
15065           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15066     }
15067   if (good)
15068     return true;
15069
15070   return false;
15071 }
15072
15073 /* Core DR 115: In contexts where deduction is done and fails, or in
15074    contexts where deduction is not done, if a template argument list is
15075    specified and it, along with any default template arguments, identifies
15076    a single function template specialization, then the template-id is an
15077    lvalue for the function template specialization.  */
15078
15079 tree
15080 resolve_nondeduced_context (tree orig_expr)
15081 {
15082   tree expr, offset, baselink;
15083   bool addr;
15084
15085   if (!type_unknown_p (orig_expr))
15086     return orig_expr;
15087
15088   expr = orig_expr;
15089   addr = false;
15090   offset = NULL_TREE;
15091   baselink = NULL_TREE;
15092
15093   if (TREE_CODE (expr) == ADDR_EXPR)
15094     {
15095       expr = TREE_OPERAND (expr, 0);
15096       addr = true;
15097     }
15098   if (TREE_CODE (expr) == OFFSET_REF)
15099     {
15100       offset = expr;
15101       expr = TREE_OPERAND (expr, 1);
15102     }
15103   if (TREE_CODE (expr) == BASELINK)
15104     {
15105       baselink = expr;
15106       expr = BASELINK_FUNCTIONS (expr);
15107     }
15108
15109   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15110     {
15111       int good = 0;
15112       tree goodfn = NULL_TREE;
15113
15114       /* If we got some explicit template args, we need to plug them into
15115          the affected templates before we try to unify, in case the
15116          explicit args will completely resolve the templates in question.  */
15117
15118       tree expl_subargs = TREE_OPERAND (expr, 1);
15119       tree arg = TREE_OPERAND (expr, 0);
15120       tree badfn = NULL_TREE;
15121       tree badargs = NULL_TREE;
15122
15123       for (; arg; arg = OVL_NEXT (arg))
15124         {
15125           tree fn = OVL_CURRENT (arg);
15126           tree subargs, elem;
15127
15128           if (TREE_CODE (fn) != TEMPLATE_DECL)
15129             continue;
15130
15131           ++processing_template_decl;
15132           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15133                                   expl_subargs, /*check_ret=*/false);
15134           if (subargs && !any_dependent_template_arguments_p (subargs))
15135             {
15136               elem = instantiate_template (fn, subargs, tf_none);
15137               if (elem == error_mark_node)
15138                 {
15139                   badfn = fn;
15140                   badargs = subargs;
15141                 }
15142               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15143                 {
15144                   goodfn = elem;
15145                   ++good;
15146                 }
15147             }
15148           --processing_template_decl;
15149         }
15150       if (good == 1)
15151         {
15152           mark_used (goodfn);
15153           expr = goodfn;
15154           if (baselink)
15155             expr = build_baselink (BASELINK_BINFO (baselink),
15156                                    BASELINK_ACCESS_BINFO (baselink),
15157                                    expr, BASELINK_OPTYPE (baselink));
15158           if (offset)
15159             {
15160               tree base
15161                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15162               expr = build_offset_ref (base, expr, addr);
15163             }
15164           if (addr)
15165             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15166           return expr;
15167         }
15168       else if (good == 0 && badargs)
15169         /* There were no good options and at least one bad one, so let the
15170            user know what the problem is.  */
15171         instantiate_template (badfn, badargs, tf_warning_or_error);
15172     }
15173   return orig_expr;
15174 }
15175
15176 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15177    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15178    different overloads deduce different arguments for a given parm.
15179    ADDR_P is true if the expression for which deduction is being
15180    performed was of the form "& fn" rather than simply "fn".
15181
15182    Returns 1 on success.  */
15183
15184 static int
15185 try_one_overload (tree tparms,
15186                   tree orig_targs,
15187                   tree targs,
15188                   tree parm,
15189                   tree arg,
15190                   unification_kind_t strict,
15191                   int sub_strict,
15192                   bool addr_p,
15193                   bool explain_p)
15194 {
15195   int nargs;
15196   tree tempargs;
15197   int i;
15198
15199   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15200      to function or pointer to member function argument if the set of
15201      overloaded functions does not contain function templates and at most
15202      one of a set of overloaded functions provides a unique match.
15203
15204      So if this is a template, just return success.  */
15205
15206   if (uses_template_parms (arg))
15207     return 1;
15208
15209   if (TREE_CODE (arg) == METHOD_TYPE)
15210     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15211   else if (addr_p)
15212     arg = build_pointer_type (arg);
15213
15214   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15215
15216   /* We don't copy orig_targs for this because if we have already deduced
15217      some template args from previous args, unify would complain when we
15218      try to deduce a template parameter for the same argument, even though
15219      there isn't really a conflict.  */
15220   nargs = TREE_VEC_LENGTH (targs);
15221   tempargs = make_tree_vec (nargs);
15222
15223   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15224     return 0;
15225
15226   /* First make sure we didn't deduce anything that conflicts with
15227      explicitly specified args.  */
15228   for (i = nargs; i--; )
15229     {
15230       tree elt = TREE_VEC_ELT (tempargs, i);
15231       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15232
15233       if (!elt)
15234         /*NOP*/;
15235       else if (uses_template_parms (elt))
15236         /* Since we're unifying against ourselves, we will fill in
15237            template args used in the function parm list with our own
15238            template parms.  Discard them.  */
15239         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15240       else if (oldelt && !template_args_equal (oldelt, elt))
15241         return 0;
15242     }
15243
15244   for (i = nargs; i--; )
15245     {
15246       tree elt = TREE_VEC_ELT (tempargs, i);
15247
15248       if (elt)
15249         TREE_VEC_ELT (targs, i) = elt;
15250     }
15251
15252   return 1;
15253 }
15254
15255 /* PARM is a template class (perhaps with unbound template
15256    parameters).  ARG is a fully instantiated type.  If ARG can be
15257    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15258    TARGS are as for unify.  */
15259
15260 static tree
15261 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15262                        bool explain_p)
15263 {
15264   tree copy_of_targs;
15265
15266   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15267       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15268           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15269     return NULL_TREE;
15270
15271   /* We need to make a new template argument vector for the call to
15272      unify.  If we used TARGS, we'd clutter it up with the result of
15273      the attempted unification, even if this class didn't work out.
15274      We also don't want to commit ourselves to all the unifications
15275      we've already done, since unification is supposed to be done on
15276      an argument-by-argument basis.  In other words, consider the
15277      following pathological case:
15278
15279        template <int I, int J, int K>
15280        struct S {};
15281
15282        template <int I, int J>
15283        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15284
15285        template <int I, int J, int K>
15286        void f(S<I, J, K>, S<I, I, I>);
15287
15288        void g() {
15289          S<0, 0, 0> s0;
15290          S<0, 1, 2> s2;
15291
15292          f(s0, s2);
15293        }
15294
15295      Now, by the time we consider the unification involving `s2', we
15296      already know that we must have `f<0, 0, 0>'.  But, even though
15297      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15298      because there are two ways to unify base classes of S<0, 1, 2>
15299      with S<I, I, I>.  If we kept the already deduced knowledge, we
15300      would reject the possibility I=1.  */
15301   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15302
15303   /* If unification failed, we're done.  */
15304   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15305              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15306     return NULL_TREE;
15307
15308   return arg;
15309 }
15310
15311 /* Given a template type PARM and a class type ARG, find the unique
15312    base type in ARG that is an instance of PARM.  We do not examine
15313    ARG itself; only its base-classes.  If there is not exactly one
15314    appropriate base class, return NULL_TREE.  PARM may be the type of
15315    a partial specialization, as well as a plain template type.  Used
15316    by unify.  */
15317
15318 static enum template_base_result
15319 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15320                    bool explain_p, tree *result)
15321 {
15322   tree rval = NULL_TREE;
15323   tree binfo;
15324
15325   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15326
15327   binfo = TYPE_BINFO (complete_type (arg));
15328   if (!binfo)
15329     {
15330       /* The type could not be completed.  */
15331       *result = NULL_TREE;
15332       return tbr_incomplete_type;
15333     }
15334
15335   /* Walk in inheritance graph order.  The search order is not
15336      important, and this avoids multiple walks of virtual bases.  */
15337   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15338     {
15339       tree r = try_class_unification (tparms, targs, parm,
15340                                       BINFO_TYPE (binfo), explain_p);
15341
15342       if (r)
15343         {
15344           /* If there is more than one satisfactory baseclass, then:
15345
15346                [temp.deduct.call]
15347
15348               If they yield more than one possible deduced A, the type
15349               deduction fails.
15350
15351              applies.  */
15352           if (rval && !same_type_p (r, rval))
15353             {
15354               *result = NULL_TREE;
15355               return tbr_ambiguous_baseclass;
15356             }
15357
15358           rval = r;
15359         }
15360     }
15361
15362   *result = rval;
15363   return tbr_success;
15364 }
15365
15366 /* Returns the level of DECL, which declares a template parameter.  */
15367
15368 static int
15369 template_decl_level (tree decl)
15370 {
15371   switch (TREE_CODE (decl))
15372     {
15373     case TYPE_DECL:
15374     case TEMPLATE_DECL:
15375       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15376
15377     case PARM_DECL:
15378       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15379
15380     default:
15381       gcc_unreachable ();
15382     }
15383   return 0;
15384 }
15385
15386 /* Decide whether ARG can be unified with PARM, considering only the
15387    cv-qualifiers of each type, given STRICT as documented for unify.
15388    Returns nonzero iff the unification is OK on that basis.  */
15389
15390 static int
15391 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15392 {
15393   int arg_quals = cp_type_quals (arg);
15394   int parm_quals = cp_type_quals (parm);
15395
15396   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15397       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15398     {
15399       /*  Although a CVR qualifier is ignored when being applied to a
15400           substituted template parameter ([8.3.2]/1 for example), that
15401           does not allow us to unify "const T" with "int&" because both
15402           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15403           It is ok when we're allowing additional CV qualifiers
15404           at the outer level [14.8.2.1]/3,1st bullet.  */
15405       if ((TREE_CODE (arg) == REFERENCE_TYPE
15406            || TREE_CODE (arg) == FUNCTION_TYPE
15407            || TREE_CODE (arg) == METHOD_TYPE)
15408           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15409         return 0;
15410
15411       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15412           && (parm_quals & TYPE_QUAL_RESTRICT))
15413         return 0;
15414     }
15415
15416   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15417       && (arg_quals & parm_quals) != parm_quals)
15418     return 0;
15419
15420   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15421       && (parm_quals & arg_quals) != arg_quals)
15422     return 0;
15423
15424   return 1;
15425 }
15426
15427 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15428 void 
15429 template_parm_level_and_index (tree parm, int* level, int* index)
15430 {
15431   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15432       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15433       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15434     {
15435       *index = TEMPLATE_TYPE_IDX (parm);
15436       *level = TEMPLATE_TYPE_LEVEL (parm);
15437     }
15438   else
15439     {
15440       *index = TEMPLATE_PARM_IDX (parm);
15441       *level = TEMPLATE_PARM_LEVEL (parm);
15442     }
15443 }
15444
15445 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15446   do {                                                                  \
15447     if (unify (TP, TA, P, A, S, EP))                                    \
15448       return 1;                                                         \
15449   } while (0);
15450
15451 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15452    expansion at the end of PACKED_PARMS. Returns 0 if the type
15453    deduction succeeds, 1 otherwise. STRICT is the same as in
15454    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15455    call argument list. We'll need to adjust the arguments to make them
15456    types. SUBR tells us if this is from a recursive call to
15457    type_unification_real.  */
15458 static int
15459 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15460                       tree packed_args, int strict, bool call_args_p,
15461                       bool subr, bool explain_p)
15462 {
15463   tree parm 
15464     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15465   tree pattern = PACK_EXPANSION_PATTERN (parm);
15466   tree pack, packs = NULL_TREE;
15467   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15468   int len = TREE_VEC_LENGTH (packed_args);
15469
15470   /* Determine the parameter packs we will be deducing from the
15471      pattern, and record their current deductions.  */
15472   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15473        pack; pack = TREE_CHAIN (pack))
15474     {
15475       tree parm_pack = TREE_VALUE (pack);
15476       int idx, level;
15477
15478       /* Determine the index and level of this parameter pack.  */
15479       template_parm_level_and_index (parm_pack, &level, &idx);
15480
15481       /* Keep track of the parameter packs and their corresponding
15482          argument packs.  */
15483       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15484       TREE_TYPE (packs) = make_tree_vec (len - start);
15485     }
15486   
15487   /* Loop through all of the arguments that have not yet been
15488      unified and unify each with the pattern.  */
15489   for (i = start; i < len; i++)
15490     {
15491       tree parm = pattern;
15492
15493       /* For each parameter pack, clear out the deduced value so that
15494          we can deduce it again.  */
15495       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15496         {
15497           int idx, level;
15498           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15499
15500           TMPL_ARG (targs, level, idx) = NULL_TREE;
15501         }
15502
15503       /* Unify the pattern with the current argument.  */
15504       {
15505         tree arg = TREE_VEC_ELT (packed_args, i);
15506         tree arg_expr = NULL_TREE;
15507         int arg_strict = strict;
15508
15509         if (call_args_p)
15510           {
15511             int sub_strict;
15512
15513             /* This mirrors what we do in type_unification_real.  */
15514             switch (strict)
15515               {
15516               case DEDUCE_CALL:
15517                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
15518                               | UNIFY_ALLOW_MORE_CV_QUAL
15519                               | UNIFY_ALLOW_DERIVED);
15520                 break;
15521                 
15522               case DEDUCE_CONV:
15523                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
15524                 break;
15525                 
15526               case DEDUCE_EXACT:
15527                 sub_strict = UNIFY_ALLOW_NONE;
15528                 break;
15529                 
15530               default:
15531                 gcc_unreachable ();
15532               }
15533
15534             if (!TYPE_P (arg))
15535               {
15536                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
15537                 if (type_unknown_p (arg))
15538                   {
15539                     /* [temp.deduct.type] A template-argument can be
15540                        deduced from a pointer to function or pointer
15541                        to member function argument if the set of
15542                        overloaded functions does not contain function
15543                        templates and at most one of a set of
15544                        overloaded functions provides a unique
15545                        match.  */
15546
15547                     if (resolve_overloaded_unification
15548                         (tparms, targs, parm, arg,
15549                          (unification_kind_t) strict,
15550                          sub_strict, explain_p))
15551                       goto unified;
15552                     return unify_overload_resolution_failure (explain_p, arg);
15553                   }
15554
15555                 arg_expr = arg;
15556                 arg = unlowered_expr_type (arg);
15557                 if (arg == error_mark_node)
15558                   return unify_invalid (explain_p);
15559               }
15560       
15561             arg_strict = sub_strict;
15562
15563             if (!subr)
15564               arg_strict |= 
15565                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
15566                                                   &parm, &arg, arg_expr);
15567           }
15568
15569         /* For deduction from an init-list we need the actual list.  */
15570         if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15571           arg = arg_expr;
15572         RECUR_AND_CHECK_FAILURE (tparms, targs, parm, arg, arg_strict,
15573                                  explain_p);
15574       }
15575
15576     unified:
15577       /* For each parameter pack, collect the deduced value.  */
15578       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15579         {
15580           int idx, level;
15581           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15582
15583           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15584             TMPL_ARG (targs, level, idx);
15585         }
15586     }
15587
15588   /* Verify that the results of unification with the parameter packs
15589      produce results consistent with what we've seen before, and make
15590      the deduced argument packs available.  */
15591   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15592     {
15593       tree old_pack = TREE_VALUE (pack);
15594       tree new_args = TREE_TYPE (pack);
15595       int i, len = TREE_VEC_LENGTH (new_args);
15596       int idx, level;
15597       bool nondeduced_p = false;
15598
15599       /* By default keep the original deduced argument pack.
15600          If necessary, more specific code is going to update the
15601          resulting deduced argument later down in this function.  */
15602       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15603       TMPL_ARG (targs, level, idx) = old_pack;
15604
15605       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15606          actually deduce anything.  */
15607       for (i = 0; i < len && !nondeduced_p; ++i)
15608         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15609           nondeduced_p = true;
15610       if (nondeduced_p)
15611         continue;
15612
15613       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15614         {
15615           /* Prepend the explicit arguments onto NEW_ARGS.  */
15616           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15617           tree old_args = new_args;
15618           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
15619           int len = explicit_len + TREE_VEC_LENGTH (old_args);
15620
15621           /* Copy the explicit arguments.  */
15622           new_args = make_tree_vec (len);
15623           for (i = 0; i < explicit_len; i++)
15624             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
15625
15626           /* Copy the deduced arguments.  */
15627           for (; i < len; i++)
15628             TREE_VEC_ELT (new_args, i) =
15629               TREE_VEC_ELT (old_args, i - explicit_len);
15630         }
15631
15632       if (!old_pack)
15633         {
15634           tree result;
15635           /* Build the deduced *_ARGUMENT_PACK.  */
15636           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15637             {
15638               result = make_node (NONTYPE_ARGUMENT_PACK);
15639               TREE_TYPE (result) = 
15640                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15641               TREE_CONSTANT (result) = 1;
15642             }
15643           else
15644             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15645
15646           SET_ARGUMENT_PACK_ARGS (result, new_args);
15647
15648           /* Note the deduced argument packs for this parameter
15649              pack.  */
15650           TMPL_ARG (targs, level, idx) = result;
15651         }
15652       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15653                && (ARGUMENT_PACK_ARGS (old_pack) 
15654                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15655         {
15656           /* We only had the explicitly-provided arguments before, but
15657              now we have a complete set of arguments.  */
15658           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15659
15660           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15661           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15662           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15663         }
15664       else
15665         {
15666           tree bad_old_arg, bad_new_arg;
15667           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15668
15669           if (!comp_template_args_with_info (old_args, new_args,
15670                                              &bad_old_arg, &bad_new_arg))
15671             /* Inconsistent unification of this parameter pack.  */
15672             return unify_parameter_pack_inconsistent (explain_p,
15673                                                       bad_old_arg,
15674                                                       bad_new_arg);
15675         }
15676     }
15677
15678   return unify_success (explain_p);
15679 }
15680
15681 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15682    set of template parameters to a template.  TARGS is the bindings
15683    for those template parameters, as determined thus far; TARGS may
15684    include template arguments for outer levels of template parameters
15685    as well.  PARM is a parameter to a template function, or a
15686    subcomponent of that parameter; ARG is the corresponding argument.
15687    This function attempts to match PARM with ARG in a manner
15688    consistent with the existing assignments in TARGS.  If more values
15689    are deduced, then TARGS is updated.
15690
15691    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15692    parameter STRICT is a bitwise or of the following flags:
15693
15694      UNIFY_ALLOW_NONE:
15695        Require an exact match between PARM and ARG.
15696      UNIFY_ALLOW_MORE_CV_QUAL:
15697        Allow the deduced ARG to be more cv-qualified (by qualification
15698        conversion) than ARG.
15699      UNIFY_ALLOW_LESS_CV_QUAL:
15700        Allow the deduced ARG to be less cv-qualified than ARG.
15701      UNIFY_ALLOW_DERIVED:
15702        Allow the deduced ARG to be a template base class of ARG,
15703        or a pointer to a template base class of the type pointed to by
15704        ARG.
15705      UNIFY_ALLOW_INTEGER:
15706        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15707        case for more information.
15708      UNIFY_ALLOW_OUTER_LEVEL:
15709        This is the outermost level of a deduction. Used to determine validity
15710        of qualification conversions. A valid qualification conversion must
15711        have const qualified pointers leading up to the inner type which
15712        requires additional CV quals, except at the outer level, where const
15713        is not required [conv.qual]. It would be normal to set this flag in
15714        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15715      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15716        This is the outermost level of a deduction, and PARM can be more CV
15717        qualified at this point.
15718      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15719        This is the outermost level of a deduction, and PARM can be less CV
15720        qualified at this point.  */
15721
15722 static int
15723 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15724        bool explain_p)
15725 {
15726   int idx;
15727   tree targ;
15728   tree tparm;
15729   int strict_in = strict;
15730
15731   /* I don't think this will do the right thing with respect to types.
15732      But the only case I've seen it in so far has been array bounds, where
15733      signedness is the only information lost, and I think that will be
15734      okay.  */
15735   while (TREE_CODE (parm) == NOP_EXPR)
15736     parm = TREE_OPERAND (parm, 0);
15737
15738   if (arg == error_mark_node)
15739     return unify_invalid (explain_p);
15740   if (arg == unknown_type_node
15741       || arg == init_list_type_node)
15742     /* We can't deduce anything from this, but we might get all the
15743        template args from other function args.  */
15744     return unify_success (explain_p);
15745
15746   /* If PARM uses template parameters, then we can't bail out here,
15747      even if ARG == PARM, since we won't record unifications for the
15748      template parameters.  We might need them if we're trying to
15749      figure out which of two things is more specialized.  */
15750   if (arg == parm && !uses_template_parms (parm))
15751     return unify_success (explain_p);
15752
15753   /* Handle init lists early, so the rest of the function can assume
15754      we're dealing with a type. */
15755   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15756     {
15757       tree elt, elttype;
15758       unsigned i;
15759       tree orig_parm = parm;
15760
15761       /* Replace T with std::initializer_list<T> for deduction.  */
15762       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15763           && flag_deduce_init_list)
15764         parm = listify (parm);
15765
15766       if (!is_std_init_list (parm))
15767         /* We can only deduce from an initializer list argument if the
15768            parameter is std::initializer_list; otherwise this is a
15769            non-deduced context. */
15770         return unify_success (explain_p);
15771
15772       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15773
15774       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15775         {
15776           int elt_strict = strict;
15777
15778           if (elt == error_mark_node)
15779             return unify_invalid (explain_p);
15780
15781           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15782             {
15783               tree type = TREE_TYPE (elt);
15784               /* It should only be possible to get here for a call.  */
15785               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15786               elt_strict |= maybe_adjust_types_for_deduction
15787                 (DEDUCE_CALL, &elttype, &type, elt);
15788               elt = type;
15789             }
15790
15791           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15792                                    explain_p);
15793         }
15794
15795       /* If the std::initializer_list<T> deduction worked, replace the
15796          deduced A with std::initializer_list<A>.  */
15797       if (orig_parm != parm)
15798         {
15799           idx = TEMPLATE_TYPE_IDX (orig_parm);
15800           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15801           targ = listify (targ);
15802           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15803         }
15804       return unify_success (explain_p);
15805     }
15806
15807   /* Immediately reject some pairs that won't unify because of
15808      cv-qualification mismatches.  */
15809   if (TREE_CODE (arg) == TREE_CODE (parm)
15810       && TYPE_P (arg)
15811       /* It is the elements of the array which hold the cv quals of an array
15812          type, and the elements might be template type parms. We'll check
15813          when we recurse.  */
15814       && TREE_CODE (arg) != ARRAY_TYPE
15815       /* We check the cv-qualifiers when unifying with template type
15816          parameters below.  We want to allow ARG `const T' to unify with
15817          PARM `T' for example, when computing which of two templates
15818          is more specialized, for example.  */
15819       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15820       && !check_cv_quals_for_unify (strict_in, arg, parm))
15821     return unify_cv_qual_mismatch (explain_p, parm, arg);
15822
15823   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15824       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15825     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15826   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15827   strict &= ~UNIFY_ALLOW_DERIVED;
15828   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15829   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15830
15831   switch (TREE_CODE (parm))
15832     {
15833     case TYPENAME_TYPE:
15834     case SCOPE_REF:
15835     case UNBOUND_CLASS_TEMPLATE:
15836       /* In a type which contains a nested-name-specifier, template
15837          argument values cannot be deduced for template parameters used
15838          within the nested-name-specifier.  */
15839       return unify_success (explain_p);
15840
15841     case TEMPLATE_TYPE_PARM:
15842     case TEMPLATE_TEMPLATE_PARM:
15843     case BOUND_TEMPLATE_TEMPLATE_PARM:
15844       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15845       if (tparm == error_mark_node)
15846         return unify_invalid (explain_p);
15847
15848       if (TEMPLATE_TYPE_LEVEL (parm)
15849           != template_decl_level (tparm))
15850         /* The PARM is not one we're trying to unify.  Just check
15851            to see if it matches ARG.  */
15852         {
15853           if (TREE_CODE (arg) == TREE_CODE (parm)
15854               && same_type_p (parm, arg))
15855             return unify_success (explain_p);
15856           else
15857             return unify_type_mismatch (explain_p, parm, arg);
15858         }
15859       idx = TEMPLATE_TYPE_IDX (parm);
15860       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15861       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15862
15863       /* Check for mixed types and values.  */
15864       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15865            && TREE_CODE (tparm) != TYPE_DECL)
15866           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15867               && TREE_CODE (tparm) != TEMPLATE_DECL))
15868         gcc_unreachable ();
15869
15870       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15871         {
15872           /* ARG must be constructed from a template class or a template
15873              template parameter.  */
15874           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15875               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15876             return unify_template_deduction_failure (explain_p, parm, arg);
15877
15878           {
15879             tree parmvec = TYPE_TI_ARGS (parm);
15880             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15881             tree full_argvec = add_to_template_args (targs, argvec);
15882             tree parm_parms 
15883               = DECL_INNERMOST_TEMPLATE_PARMS
15884                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15885             int i, len;
15886             int parm_variadic_p = 0;
15887
15888             /* The resolution to DR150 makes clear that default
15889                arguments for an N-argument may not be used to bind T
15890                to a template template parameter with fewer than N
15891                parameters.  It is not safe to permit the binding of
15892                default arguments as an extension, as that may change
15893                the meaning of a conforming program.  Consider:
15894
15895                   struct Dense { static const unsigned int dim = 1; };
15896
15897                   template <template <typename> class View,
15898                             typename Block>
15899                   void operator+(float, View<Block> const&);
15900
15901                   template <typename Block,
15902                             unsigned int Dim = Block::dim>
15903                   struct Lvalue_proxy { operator float() const; };
15904
15905                   void
15906                   test_1d (void) {
15907                     Lvalue_proxy<Dense> p;
15908                     float b;
15909                     b + p;
15910                   }
15911
15912               Here, if Lvalue_proxy is permitted to bind to View, then
15913               the global operator+ will be used; if they are not, the
15914               Lvalue_proxy will be converted to float.  */
15915             if (coerce_template_parms (parm_parms,
15916                                        full_argvec,
15917                                        TYPE_TI_TEMPLATE (parm),
15918                                        (explain_p
15919                                         ? tf_warning_or_error
15920                                         : tf_none),
15921                                        /*require_all_args=*/true,
15922                                        /*use_default_args=*/false)
15923                 == error_mark_node)
15924               return 1;
15925
15926             /* Deduce arguments T, i from TT<T> or TT<i>.
15927                We check each element of PARMVEC and ARGVEC individually
15928                rather than the whole TREE_VEC since they can have
15929                different number of elements.  */
15930
15931             parmvec = expand_template_argument_pack (parmvec);
15932             argvec = expand_template_argument_pack (argvec);
15933
15934             len = TREE_VEC_LENGTH (parmvec);
15935
15936             /* Check if the parameters end in a pack, making them
15937                variadic.  */
15938             if (len > 0
15939                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15940               parm_variadic_p = 1;
15941             
15942             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15943               return unify_too_few_arguments (explain_p,
15944                                               TREE_VEC_LENGTH (argvec), len);
15945
15946              for (i = 0; i < len - parm_variadic_p; ++i)
15947               {
15948                 RECUR_AND_CHECK_FAILURE (tparms, targs,
15949                                          TREE_VEC_ELT (parmvec, i),
15950                                          TREE_VEC_ELT (argvec, i),
15951                                          UNIFY_ALLOW_NONE, explain_p);
15952               }
15953
15954             if (parm_variadic_p
15955                 && unify_pack_expansion (tparms, targs,
15956                                          parmvec, argvec,
15957                                          UNIFY_ALLOW_NONE,
15958                                          /*call_args_p=*/false,
15959                                          /*subr=*/false, explain_p))
15960               return 1;
15961           }
15962           arg = TYPE_TI_TEMPLATE (arg);
15963
15964           /* Fall through to deduce template name.  */
15965         }
15966
15967       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15968           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15969         {
15970           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15971
15972           /* Simple cases: Value already set, does match or doesn't.  */
15973           if (targ != NULL_TREE && template_args_equal (targ, arg))
15974             return unify_success (explain_p);
15975           else if (targ)
15976             return unify_inconsistency (explain_p, parm, targ, arg);
15977         }
15978       else
15979         {
15980           /* If PARM is `const T' and ARG is only `int', we don't have
15981              a match unless we are allowing additional qualification.
15982              If ARG is `const int' and PARM is just `T' that's OK;
15983              that binds `const int' to `T'.  */
15984           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15985                                          arg, parm))
15986             return unify_cv_qual_mismatch (explain_p, parm, arg);
15987
15988           /* Consider the case where ARG is `const volatile int' and
15989              PARM is `const T'.  Then, T should be `volatile int'.  */
15990           arg = cp_build_qualified_type_real
15991             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15992           if (arg == error_mark_node)
15993             return unify_invalid (explain_p);
15994
15995           /* Simple cases: Value already set, does match or doesn't.  */
15996           if (targ != NULL_TREE && same_type_p (targ, arg))
15997             return unify_success (explain_p);
15998           else if (targ)
15999             return unify_inconsistency (explain_p, parm, targ, arg);
16000
16001           /* Make sure that ARG is not a variable-sized array.  (Note
16002              that were talking about variable-sized arrays (like
16003              `int[n]'), rather than arrays of unknown size (like
16004              `int[]').)  We'll get very confused by such a type since
16005              the bound of the array is not constant, and therefore
16006              not mangleable.  Besides, such types are not allowed in
16007              ISO C++, so we can do as we please here.  We do allow
16008              them for 'auto' deduction, since that isn't ABI-exposed.  */
16009           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16010             return unify_vla_arg (explain_p, arg);
16011
16012           /* Strip typedefs as in convert_template_argument.  */
16013           arg = canonicalize_type_argument (arg, tf_none);
16014         }
16015
16016       /* If ARG is a parameter pack or an expansion, we cannot unify
16017          against it unless PARM is also a parameter pack.  */
16018       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16019           && !template_parameter_pack_p (parm))
16020         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16021
16022       /* If the argument deduction results is a METHOD_TYPE,
16023          then there is a problem.
16024          METHOD_TYPE doesn't map to any real C++ type the result of
16025          the deduction can not be of that type.  */
16026       if (TREE_CODE (arg) == METHOD_TYPE)
16027         return unify_method_type_error (explain_p, arg);
16028
16029       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16030       return unify_success (explain_p);
16031
16032     case TEMPLATE_PARM_INDEX:
16033       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16034       if (tparm == error_mark_node)
16035         return unify_invalid (explain_p);
16036
16037       if (TEMPLATE_PARM_LEVEL (parm)
16038           != template_decl_level (tparm))
16039         {
16040           /* The PARM is not one we're trying to unify.  Just check
16041              to see if it matches ARG.  */
16042           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16043                          && cp_tree_equal (parm, arg));
16044           if (result)
16045             unify_expression_unequal (explain_p, parm, arg);
16046           return result;
16047         }
16048
16049       idx = TEMPLATE_PARM_IDX (parm);
16050       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16051
16052       if (targ)
16053         {
16054           int x = !cp_tree_equal (targ, arg);
16055           if (x)
16056             unify_inconsistency (explain_p, parm, targ, arg);
16057           return x;
16058         }
16059
16060       /* [temp.deduct.type] If, in the declaration of a function template
16061          with a non-type template-parameter, the non-type
16062          template-parameter is used in an expression in the function
16063          parameter-list and, if the corresponding template-argument is
16064          deduced, the template-argument type shall match the type of the
16065          template-parameter exactly, except that a template-argument
16066          deduced from an array bound may be of any integral type.
16067          The non-type parameter might use already deduced type parameters.  */
16068       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16069       if (!TREE_TYPE (arg))
16070         /* Template-parameter dependent expression.  Just accept it for now.
16071            It will later be processed in convert_template_argument.  */
16072         ;
16073       else if (same_type_p (TREE_TYPE (arg), tparm))
16074         /* OK */;
16075       else if ((strict & UNIFY_ALLOW_INTEGER)
16076                && (TREE_CODE (tparm) == INTEGER_TYPE
16077                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16078         /* Convert the ARG to the type of PARM; the deduced non-type
16079            template argument must exactly match the types of the
16080            corresponding parameter.  */
16081         arg = fold (build_nop (tparm, arg));
16082       else if (uses_template_parms (tparm))
16083         /* We haven't deduced the type of this parameter yet.  Try again
16084            later.  */
16085         return unify_success (explain_p);
16086       else
16087         return unify_type_mismatch (explain_p, tparm, arg);
16088
16089       /* If ARG is a parameter pack or an expansion, we cannot unify
16090          against it unless PARM is also a parameter pack.  */
16091       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16092           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16093         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16094
16095       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16096       return unify_success (explain_p);
16097
16098     case PTRMEM_CST:
16099      {
16100         /* A pointer-to-member constant can be unified only with
16101          another constant.  */
16102       if (TREE_CODE (arg) != PTRMEM_CST)
16103         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16104
16105       /* Just unify the class member. It would be useless (and possibly
16106          wrong, depending on the strict flags) to unify also
16107          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16108          arg refer to the same variable, even if through different
16109          classes. For instance:
16110
16111          struct A { int x; };
16112          struct B : A { };
16113
16114          Unification of &A::x and &B::x must succeed.  */
16115       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16116                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16117      }
16118
16119     case POINTER_TYPE:
16120       {
16121         if (TREE_CODE (arg) != POINTER_TYPE)
16122           return unify_type_mismatch (explain_p, parm, arg);
16123
16124         /* [temp.deduct.call]
16125
16126            A can be another pointer or pointer to member type that can
16127            be converted to the deduced A via a qualification
16128            conversion (_conv.qual_).
16129
16130            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16131            This will allow for additional cv-qualification of the
16132            pointed-to types if appropriate.  */
16133
16134         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16135           /* The derived-to-base conversion only persists through one
16136              level of pointers.  */
16137           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16138
16139         return unify (tparms, targs, TREE_TYPE (parm),
16140                       TREE_TYPE (arg), strict, explain_p);
16141       }
16142
16143     case REFERENCE_TYPE:
16144       if (TREE_CODE (arg) != REFERENCE_TYPE)
16145         return unify_type_mismatch (explain_p, parm, arg);
16146       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16147                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16148
16149     case ARRAY_TYPE:
16150       if (TREE_CODE (arg) != ARRAY_TYPE)
16151         return unify_type_mismatch (explain_p, parm, arg);
16152       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16153           != (TYPE_DOMAIN (arg) == NULL_TREE))
16154         return unify_type_mismatch (explain_p, parm, arg);
16155       if (TYPE_DOMAIN (parm) != NULL_TREE)
16156         {
16157           tree parm_max;
16158           tree arg_max;
16159           bool parm_cst;
16160           bool arg_cst;
16161
16162           /* Our representation of array types uses "N - 1" as the
16163              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16164              not an integer constant.  We cannot unify arbitrarily
16165              complex expressions, so we eliminate the MINUS_EXPRs
16166              here.  */
16167           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16168           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16169           if (!parm_cst)
16170             {
16171               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16172               parm_max = TREE_OPERAND (parm_max, 0);
16173             }
16174           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16175           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16176           if (!arg_cst)
16177             {
16178               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16179                  trying to unify the type of a variable with the type
16180                  of a template parameter.  For example:
16181
16182                    template <unsigned int N>
16183                    void f (char (&) [N]);
16184                    int g(); 
16185                    void h(int i) {
16186                      char a[g(i)];
16187                      f(a); 
16188                    }
16189
16190                 Here, the type of the ARG will be "int [g(i)]", and
16191                 may be a SAVE_EXPR, etc.  */
16192               if (TREE_CODE (arg_max) != MINUS_EXPR)
16193                 return unify_vla_arg (explain_p, arg);
16194               arg_max = TREE_OPERAND (arg_max, 0);
16195             }
16196
16197           /* If only one of the bounds used a MINUS_EXPR, compensate
16198              by adding one to the other bound.  */
16199           if (parm_cst && !arg_cst)
16200             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16201                                     integer_type_node,
16202                                     parm_max,
16203                                     integer_one_node);
16204           else if (arg_cst && !parm_cst)
16205             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16206                                    integer_type_node,
16207                                    arg_max,
16208                                    integer_one_node);
16209
16210           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16211                                    UNIFY_ALLOW_INTEGER, explain_p);
16212         }
16213       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16214                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16215
16216     case REAL_TYPE:
16217     case COMPLEX_TYPE:
16218     case VECTOR_TYPE:
16219     case INTEGER_TYPE:
16220     case BOOLEAN_TYPE:
16221     case ENUMERAL_TYPE:
16222     case VOID_TYPE:
16223       if (TREE_CODE (arg) != TREE_CODE (parm))
16224         return unify_type_mismatch (explain_p, parm, arg);
16225
16226       /* We have already checked cv-qualification at the top of the
16227          function.  */
16228       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16229         return unify_type_mismatch (explain_p, parm, arg);
16230
16231       /* As far as unification is concerned, this wins.  Later checks
16232          will invalidate it if necessary.  */
16233       return unify_success (explain_p);
16234
16235       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16236       /* Type INTEGER_CST can come from ordinary constant template args.  */
16237     case INTEGER_CST:
16238       while (TREE_CODE (arg) == NOP_EXPR)
16239         arg = TREE_OPERAND (arg, 0);
16240
16241       if (TREE_CODE (arg) != INTEGER_CST)
16242         return unify_template_argument_mismatch (explain_p, parm, arg);
16243       return (tree_int_cst_equal (parm, arg)
16244               ? unify_success (explain_p)
16245               : unify_template_argument_mismatch (explain_p, parm, arg));
16246
16247     case TREE_VEC:
16248       {
16249         int i;
16250         if (TREE_CODE (arg) != TREE_VEC)
16251           return unify_template_argument_mismatch (explain_p, parm, arg);
16252         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
16253           return unify_arity (explain_p, TREE_VEC_LENGTH (arg),
16254                               TREE_VEC_LENGTH (parm));
16255         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
16256           RECUR_AND_CHECK_FAILURE (tparms, targs,
16257                                    TREE_VEC_ELT (parm, i),
16258                                    TREE_VEC_ELT (arg, i),
16259                                    UNIFY_ALLOW_NONE, explain_p);
16260         return unify_success (explain_p);
16261       }
16262
16263     case RECORD_TYPE:
16264     case UNION_TYPE:
16265       if (TREE_CODE (arg) != TREE_CODE (parm))
16266         return unify_type_mismatch (explain_p, parm, arg);
16267
16268       if (TYPE_PTRMEMFUNC_P (parm))
16269         {
16270           if (!TYPE_PTRMEMFUNC_P (arg))
16271             return unify_type_mismatch (explain_p, parm, arg);
16272
16273           return unify (tparms, targs,
16274                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16275                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16276                         strict, explain_p);
16277         }
16278
16279       if (CLASSTYPE_TEMPLATE_INFO (parm))
16280         {
16281           tree t = NULL_TREE;
16282
16283           if (strict_in & UNIFY_ALLOW_DERIVED)
16284             {
16285               /* First, we try to unify the PARM and ARG directly.  */
16286               t = try_class_unification (tparms, targs,
16287                                          parm, arg, explain_p);
16288
16289               if (!t)
16290                 {
16291                   /* Fallback to the special case allowed in
16292                      [temp.deduct.call]:
16293
16294                        If P is a class, and P has the form
16295                        template-id, then A can be a derived class of
16296                        the deduced A.  Likewise, if P is a pointer to
16297                        a class of the form template-id, A can be a
16298                        pointer to a derived class pointed to by the
16299                        deduced A.  */
16300                   enum template_base_result r;
16301                   r = get_template_base (tparms, targs, parm, arg,
16302                                          explain_p, &t);
16303
16304                   if (!t)
16305                     return unify_no_common_base (explain_p, r, parm, arg);
16306                 }
16307             }
16308           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16309                    && (CLASSTYPE_TI_TEMPLATE (parm)
16310                        == CLASSTYPE_TI_TEMPLATE (arg)))
16311             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16312                Then, we should unify `int' and `U'.  */
16313             t = arg;
16314           else
16315             /* There's no chance of unification succeeding.  */
16316             return unify_type_mismatch (explain_p, parm, arg);
16317
16318           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16319                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16320         }
16321       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16322         return unify_type_mismatch (explain_p, parm, arg);
16323       return unify_success (explain_p);
16324
16325     case METHOD_TYPE:
16326     case FUNCTION_TYPE:
16327       {
16328         unsigned int nargs;
16329         tree *args;
16330         tree a;
16331         unsigned int i;
16332
16333         if (TREE_CODE (arg) != TREE_CODE (parm))
16334           return unify_type_mismatch (explain_p, parm, arg);
16335
16336         /* CV qualifications for methods can never be deduced, they must
16337            match exactly.  We need to check them explicitly here,
16338            because type_unification_real treats them as any other
16339            cv-qualified parameter.  */
16340         if (TREE_CODE (parm) == METHOD_TYPE
16341             && (!check_cv_quals_for_unify
16342                 (UNIFY_ALLOW_NONE,
16343                  class_of_this_parm (arg),
16344                  class_of_this_parm (parm))))
16345           return unify_cv_qual_mismatch (explain_p, parm, arg);
16346
16347         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16348                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16349
16350         nargs = list_length (TYPE_ARG_TYPES (arg));
16351         args = XALLOCAVEC (tree, nargs);
16352         for (a = TYPE_ARG_TYPES (arg), i = 0;
16353              a != NULL_TREE && a != void_list_node;
16354              a = TREE_CHAIN (a), ++i)
16355           args[i] = TREE_VALUE (a);
16356         nargs = i;
16357
16358         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16359                                       args, nargs, 1, DEDUCE_EXACT,
16360                                       LOOKUP_NORMAL, explain_p);
16361       }
16362
16363     case OFFSET_TYPE:
16364       /* Unify a pointer to member with a pointer to member function, which
16365          deduces the type of the member as a function type. */
16366       if (TYPE_PTRMEMFUNC_P (arg))
16367         {
16368           tree method_type;
16369           tree fntype;
16370
16371           /* Check top-level cv qualifiers */
16372           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16373             return unify_cv_qual_mismatch (explain_p, parm, arg);
16374
16375           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16376                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16377                                    UNIFY_ALLOW_NONE, explain_p);
16378
16379           /* Determine the type of the function we are unifying against. */
16380           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16381           fntype =
16382             build_function_type (TREE_TYPE (method_type),
16383                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16384
16385           /* Extract the cv-qualifiers of the member function from the
16386              implicit object parameter and place them on the function
16387              type to be restored later. */
16388           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16389           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16390         }
16391
16392       if (TREE_CODE (arg) != OFFSET_TYPE)
16393         return unify_type_mismatch (explain_p, parm, arg);
16394       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16395                                TYPE_OFFSET_BASETYPE (arg),
16396                                UNIFY_ALLOW_NONE, explain_p);
16397       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16398                     strict, explain_p);
16399
16400     case CONST_DECL:
16401       if (DECL_TEMPLATE_PARM_P (parm))
16402         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16403       if (arg != integral_constant_value (parm))
16404         return unify_template_argument_mismatch (explain_p, parm, arg);
16405       return unify_success (explain_p);
16406
16407     case FIELD_DECL:
16408     case TEMPLATE_DECL:
16409       /* Matched cases are handled by the ARG == PARM test above.  */
16410       return unify_template_argument_mismatch (explain_p, parm, arg);
16411
16412     case VAR_DECL:
16413       /* A non-type template parameter that is a variable should be a
16414          an integral constant, in which case, it whould have been
16415          folded into its (constant) value. So we should not be getting
16416          a variable here.  */
16417       gcc_unreachable ();
16418
16419     case TYPE_ARGUMENT_PACK:
16420     case NONTYPE_ARGUMENT_PACK:
16421       {
16422         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
16423         tree packed_args = ARGUMENT_PACK_ARGS (arg);
16424         int i, len = TREE_VEC_LENGTH (packed_parms);
16425         int argslen = TREE_VEC_LENGTH (packed_args);
16426         int parm_variadic_p = 0;
16427
16428         for (i = 0; i < len; ++i)
16429           {
16430             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
16431               {
16432                 if (i == len - 1)
16433                   /* We can unify against something with a trailing
16434                      parameter pack.  */
16435                   parm_variadic_p = 1;
16436                 else
16437                   /* Since there is something following the pack
16438                      expansion, we cannot unify this template argument
16439                      list.  */
16440                   return unify_success (explain_p);
16441               }
16442           }
16443           
16444
16445         /* If we don't have enough arguments to satisfy the parameters
16446            (not counting the pack expression at the end), or we have
16447            too many arguments for a parameter list that doesn't end in
16448            a pack expression, we can't unify.  */
16449         if (argslen < (len - parm_variadic_p))
16450           return unify_too_few_arguments (explain_p, argslen, len);
16451         if (argslen > len && !parm_variadic_p)
16452           return unify_too_many_arguments (explain_p, argslen, len);
16453
16454         /* Unify all of the parameters that precede the (optional)
16455            pack expression.  */
16456         for (i = 0; i < len - parm_variadic_p; ++i)
16457           {
16458             RECUR_AND_CHECK_FAILURE (tparms, targs,
16459                                      TREE_VEC_ELT (packed_parms, i),
16460                                      TREE_VEC_ELT (packed_args, i),
16461                                      strict, explain_p);
16462           }
16463
16464         if (parm_variadic_p)
16465           return unify_pack_expansion (tparms, targs, 
16466                                        packed_parms, packed_args,
16467                                        strict, /*call_args_p=*/false,
16468                                        /*subr=*/false, explain_p);
16469         return unify_success (explain_p);
16470       }
16471
16472       break;
16473
16474     case TYPEOF_TYPE:
16475     case DECLTYPE_TYPE:
16476     case UNDERLYING_TYPE:
16477       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16478          or UNDERLYING_TYPE nodes.  */
16479       return unify_success (explain_p);
16480
16481     case ERROR_MARK:
16482       /* Unification fails if we hit an error node.  */
16483       return unify_invalid (explain_p);
16484
16485     default:
16486       /* An unresolved overload is a nondeduced context.  */
16487       if (type_unknown_p (parm))
16488         return unify_success (explain_p);
16489       gcc_assert (EXPR_P (parm));
16490
16491       /* We must be looking at an expression.  This can happen with
16492          something like:
16493
16494            template <int I>
16495            void foo(S<I>, S<I + 2>);
16496
16497          This is a "nondeduced context":
16498
16499            [deduct.type]
16500
16501            The nondeduced contexts are:
16502
16503            --A type that is a template-id in which one or more of
16504              the template-arguments is an expression that references
16505              a template-parameter.
16506
16507          In these cases, we assume deduction succeeded, but don't
16508          actually infer any unifications.  */
16509
16510       if (!uses_template_parms (parm)
16511           && !template_args_equal (parm, arg))
16512         return unify_expression_unequal (explain_p, parm, arg);
16513       else
16514         return unify_success (explain_p);
16515     }
16516 }
16517 #undef RECUR_AND_CHECK_FAILURE
16518 \f
16519 /* Note that DECL can be defined in this translation unit, if
16520    required.  */
16521
16522 static void
16523 mark_definable (tree decl)
16524 {
16525   tree clone;
16526   DECL_NOT_REALLY_EXTERN (decl) = 1;
16527   FOR_EACH_CLONE (clone, decl)
16528     DECL_NOT_REALLY_EXTERN (clone) = 1;
16529 }
16530
16531 /* Called if RESULT is explicitly instantiated, or is a member of an
16532    explicitly instantiated class.  */
16533
16534 void
16535 mark_decl_instantiated (tree result, int extern_p)
16536 {
16537   SET_DECL_EXPLICIT_INSTANTIATION (result);
16538
16539   /* If this entity has already been written out, it's too late to
16540      make any modifications.  */
16541   if (TREE_ASM_WRITTEN (result))
16542     return;
16543
16544   if (TREE_CODE (result) != FUNCTION_DECL)
16545     /* The TREE_PUBLIC flag for function declarations will have been
16546        set correctly by tsubst.  */
16547     TREE_PUBLIC (result) = 1;
16548
16549   /* This might have been set by an earlier implicit instantiation.  */
16550   DECL_COMDAT (result) = 0;
16551
16552   if (extern_p)
16553     DECL_NOT_REALLY_EXTERN (result) = 0;
16554   else
16555     {
16556       mark_definable (result);
16557       /* Always make artificials weak.  */
16558       if (DECL_ARTIFICIAL (result) && flag_weak)
16559         comdat_linkage (result);
16560       /* For WIN32 we also want to put explicit instantiations in
16561          linkonce sections.  */
16562       else if (TREE_PUBLIC (result))
16563         maybe_make_one_only (result);
16564     }
16565
16566   /* If EXTERN_P, then this function will not be emitted -- unless
16567      followed by an explicit instantiation, at which point its linkage
16568      will be adjusted.  If !EXTERN_P, then this function will be
16569      emitted here.  In neither circumstance do we want
16570      import_export_decl to adjust the linkage.  */
16571   DECL_INTERFACE_KNOWN (result) = 1;
16572 }
16573
16574 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16575    important template arguments.  If any are missing, we check whether
16576    they're important by using error_mark_node for substituting into any
16577    args that were used for partial ordering (the ones between ARGS and END)
16578    and seeing if it bubbles up.  */
16579
16580 static bool
16581 check_undeduced_parms (tree targs, tree args, tree end)
16582 {
16583   bool found = false;
16584   int i;
16585   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16586     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16587       {
16588         found = true;
16589         TREE_VEC_ELT (targs, i) = error_mark_node;
16590       }
16591   if (found)
16592     {
16593       for (; args != end; args = TREE_CHAIN (args))
16594         {
16595           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16596           if (substed == error_mark_node)
16597             return true;
16598         }
16599     }
16600   return false;
16601 }
16602
16603 /* Given two function templates PAT1 and PAT2, return:
16604
16605    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16606    -1 if PAT2 is more specialized than PAT1.
16607    0 if neither is more specialized.
16608
16609    LEN indicates the number of parameters we should consider
16610    (defaulted parameters should not be considered).
16611
16612    The 1998 std underspecified function template partial ordering, and
16613    DR214 addresses the issue.  We take pairs of arguments, one from
16614    each of the templates, and deduce them against each other.  One of
16615    the templates will be more specialized if all the *other*
16616    template's arguments deduce against its arguments and at least one
16617    of its arguments *does* *not* deduce against the other template's
16618    corresponding argument.  Deduction is done as for class templates.
16619    The arguments used in deduction have reference and top level cv
16620    qualifiers removed.  Iff both arguments were originally reference
16621    types *and* deduction succeeds in both directions, the template
16622    with the more cv-qualified argument wins for that pairing (if
16623    neither is more cv-qualified, they both are equal).  Unlike regular
16624    deduction, after all the arguments have been deduced in this way,
16625    we do *not* verify the deduced template argument values can be
16626    substituted into non-deduced contexts.
16627
16628    The logic can be a bit confusing here, because we look at deduce1 and
16629    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16630    can find template arguments for pat1 to make arg1 look like arg2, that
16631    means that arg2 is at least as specialized as arg1.  */
16632
16633 int
16634 more_specialized_fn (tree pat1, tree pat2, int len)
16635 {
16636   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16637   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16638   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16639   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16640   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16641   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16642   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16643   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16644   tree origs1, origs2;
16645   bool lose1 = false;
16646   bool lose2 = false;
16647
16648   /* Remove the this parameter from non-static member functions.  If
16649      one is a non-static member function and the other is not a static
16650      member function, remove the first parameter from that function
16651      also.  This situation occurs for operator functions where we
16652      locate both a member function (with this pointer) and non-member
16653      operator (with explicit first operand).  */
16654   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16655     {
16656       len--; /* LEN is the number of significant arguments for DECL1 */
16657       args1 = TREE_CHAIN (args1);
16658       if (!DECL_STATIC_FUNCTION_P (decl2))
16659         args2 = TREE_CHAIN (args2);
16660     }
16661   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16662     {
16663       args2 = TREE_CHAIN (args2);
16664       if (!DECL_STATIC_FUNCTION_P (decl1))
16665         {
16666           len--;
16667           args1 = TREE_CHAIN (args1);
16668         }
16669     }
16670
16671   /* If only one is a conversion operator, they are unordered.  */
16672   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16673     return 0;
16674
16675   /* Consider the return type for a conversion function */
16676   if (DECL_CONV_FN_P (decl1))
16677     {
16678       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16679       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16680       len++;
16681     }
16682
16683   processing_template_decl++;
16684
16685   origs1 = args1;
16686   origs2 = args2;
16687
16688   while (len--
16689          /* Stop when an ellipsis is seen.  */
16690          && args1 != NULL_TREE && args2 != NULL_TREE)
16691     {
16692       tree arg1 = TREE_VALUE (args1);
16693       tree arg2 = TREE_VALUE (args2);
16694       int deduce1, deduce2;
16695       int quals1 = -1;
16696       int quals2 = -1;
16697
16698       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16699           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16700         {
16701           /* When both arguments are pack expansions, we need only
16702              unify the patterns themselves.  */
16703           arg1 = PACK_EXPANSION_PATTERN (arg1);
16704           arg2 = PACK_EXPANSION_PATTERN (arg2);
16705
16706           /* This is the last comparison we need to do.  */
16707           len = 0;
16708         }
16709
16710       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16711         {
16712           arg1 = TREE_TYPE (arg1);
16713           quals1 = cp_type_quals (arg1);
16714         }
16715
16716       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16717         {
16718           arg2 = TREE_TYPE (arg2);
16719           quals2 = cp_type_quals (arg2);
16720         }
16721
16722       if ((quals1 < 0) != (quals2 < 0))
16723         {
16724           /* Only of the args is a reference, see if we should apply
16725              array/function pointer decay to it.  This is not part of
16726              DR214, but is, IMHO, consistent with the deduction rules
16727              for the function call itself, and with our earlier
16728              implementation of the underspecified partial ordering
16729              rules.  (nathan).  */
16730           if (quals1 >= 0)
16731             {
16732               switch (TREE_CODE (arg1))
16733                 {
16734                 case ARRAY_TYPE:
16735                   arg1 = TREE_TYPE (arg1);
16736                   /* FALLTHROUGH. */
16737                 case FUNCTION_TYPE:
16738                   arg1 = build_pointer_type (arg1);
16739                   break;
16740
16741                 default:
16742                   break;
16743                 }
16744             }
16745           else
16746             {
16747               switch (TREE_CODE (arg2))
16748                 {
16749                 case ARRAY_TYPE:
16750                   arg2 = TREE_TYPE (arg2);
16751                   /* FALLTHROUGH. */
16752                 case FUNCTION_TYPE:
16753                   arg2 = build_pointer_type (arg2);
16754                   break;
16755
16756                 default:
16757                   break;
16758                 }
16759             }
16760         }
16761
16762       arg1 = TYPE_MAIN_VARIANT (arg1);
16763       arg2 = TYPE_MAIN_VARIANT (arg2);
16764
16765       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16766         {
16767           int i, len2 = list_length (args2);
16768           tree parmvec = make_tree_vec (1);
16769           tree argvec = make_tree_vec (len2);
16770           tree ta = args2;
16771
16772           /* Setup the parameter vector, which contains only ARG1.  */
16773           TREE_VEC_ELT (parmvec, 0) = arg1;
16774
16775           /* Setup the argument vector, which contains the remaining
16776              arguments.  */
16777           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16778             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16779
16780           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16781                                            argvec, UNIFY_ALLOW_NONE, 
16782                                            /*call_args_p=*/false, 
16783                                            /*subr=*/0, /*explain_p=*/false)
16784                      == 0);
16785
16786           /* We cannot deduce in the other direction, because ARG1 is
16787              a pack expansion but ARG2 is not.  */
16788           deduce2 = 0;
16789         }
16790       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16791         {
16792           int i, len1 = list_length (args1);
16793           tree parmvec = make_tree_vec (1);
16794           tree argvec = make_tree_vec (len1);
16795           tree ta = args1;
16796
16797           /* Setup the parameter vector, which contains only ARG1.  */
16798           TREE_VEC_ELT (parmvec, 0) = arg2;
16799
16800           /* Setup the argument vector, which contains the remaining
16801              arguments.  */
16802           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16803             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16804
16805           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16806                                            argvec, UNIFY_ALLOW_NONE, 
16807                                            /*call_args_p=*/false, 
16808                                            /*subr=*/0, /*explain_p=*/false)
16809                      == 0);
16810
16811           /* We cannot deduce in the other direction, because ARG2 is
16812              a pack expansion but ARG1 is not.*/
16813           deduce1 = 0;
16814         }
16815
16816       else
16817         {
16818           /* The normal case, where neither argument is a pack
16819              expansion.  */
16820           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16821                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16822                      == 0);
16823           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16824                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16825                      == 0);
16826         }
16827
16828       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16829          arg2, then arg2 is not as specialized as arg1.  */
16830       if (!deduce1)
16831         lose2 = true;
16832       if (!deduce2)
16833         lose1 = true;
16834
16835       /* "If, for a given type, deduction succeeds in both directions
16836          (i.e., the types are identical after the transformations above)
16837          and if the type from the argument template is more cv-qualified
16838          than the type from the parameter template (as described above)
16839          that type is considered to be more specialized than the other. If
16840          neither type is more cv-qualified than the other then neither type
16841          is more specialized than the other."  */
16842
16843       if (deduce1 && deduce2
16844           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16845         {
16846           if ((quals1 & quals2) == quals2)
16847             lose2 = true;
16848           if ((quals1 & quals2) == quals1)
16849             lose1 = true;
16850         }
16851
16852       if (lose1 && lose2)
16853         /* We've failed to deduce something in either direction.
16854            These must be unordered.  */
16855         break;
16856
16857       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16858           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16859         /* We have already processed all of the arguments in our
16860            handing of the pack expansion type.  */
16861         len = 0;
16862
16863       args1 = TREE_CHAIN (args1);
16864       args2 = TREE_CHAIN (args2);
16865     }
16866
16867   /* "In most cases, all template parameters must have values in order for
16868      deduction to succeed, but for partial ordering purposes a template
16869      parameter may remain without a value provided it is not used in the
16870      types being used for partial ordering."
16871
16872      Thus, if we are missing any of the targs1 we need to substitute into
16873      origs1, then pat2 is not as specialized as pat1.  This can happen when
16874      there is a nondeduced context.  */
16875   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16876     lose2 = true;
16877   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16878     lose1 = true;
16879
16880   processing_template_decl--;
16881
16882   /* All things being equal, if the next argument is a pack expansion
16883      for one function but not for the other, prefer the
16884      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16885   if (lose1 == lose2
16886       && args1 && TREE_VALUE (args1)
16887       && args2 && TREE_VALUE (args2))
16888     {
16889       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16890       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16891     }
16892
16893   if (lose1 == lose2)
16894     return 0;
16895   else if (!lose1)
16896     return 1;
16897   else
16898     return -1;
16899 }
16900
16901 /* Determine which of two partial specializations is more specialized.
16902
16903    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16904    to the first partial specialization.  The TREE_VALUE is the
16905    innermost set of template parameters for the partial
16906    specialization.  PAT2 is similar, but for the second template.
16907
16908    Return 1 if the first partial specialization is more specialized;
16909    -1 if the second is more specialized; 0 if neither is more
16910    specialized.
16911
16912    See [temp.class.order] for information about determining which of
16913    two templates is more specialized.  */
16914
16915 static int
16916 more_specialized_class (tree pat1, tree pat2)
16917 {
16918   tree targs;
16919   tree tmpl1, tmpl2;
16920   int winner = 0;
16921   bool any_deductions = false;
16922
16923   tmpl1 = TREE_TYPE (pat1);
16924   tmpl2 = TREE_TYPE (pat2);
16925
16926   /* Just like what happens for functions, if we are ordering between
16927      different class template specializations, we may encounter dependent
16928      types in the arguments, and we need our dependency check functions
16929      to behave correctly.  */
16930   ++processing_template_decl;
16931   targs = get_class_bindings (TREE_VALUE (pat1),
16932                               CLASSTYPE_TI_ARGS (tmpl1),
16933                               CLASSTYPE_TI_ARGS (tmpl2));
16934   if (targs)
16935     {
16936       --winner;
16937       any_deductions = true;
16938     }
16939
16940   targs = get_class_bindings (TREE_VALUE (pat2),
16941                               CLASSTYPE_TI_ARGS (tmpl2),
16942                               CLASSTYPE_TI_ARGS (tmpl1));
16943   if (targs)
16944     {
16945       ++winner;
16946       any_deductions = true;
16947     }
16948   --processing_template_decl;
16949
16950   /* In the case of a tie where at least one of the class templates
16951      has a parameter pack at the end, the template with the most
16952      non-packed parameters wins.  */
16953   if (winner == 0
16954       && any_deductions
16955       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16956           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16957     {
16958       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16959       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16960       int len1 = TREE_VEC_LENGTH (args1);
16961       int len2 = TREE_VEC_LENGTH (args2);
16962
16963       /* We don't count the pack expansion at the end.  */
16964       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16965         --len1;
16966       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16967         --len2;
16968
16969       if (len1 > len2)
16970         return 1;
16971       else if (len1 < len2)
16972         return -1;
16973     }
16974
16975   return winner;
16976 }
16977
16978 /* Return the template arguments that will produce the function signature
16979    DECL from the function template FN, with the explicit template
16980    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16981    also match.  Return NULL_TREE if no satisfactory arguments could be
16982    found.  */
16983
16984 static tree
16985 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16986 {
16987   int ntparms = DECL_NTPARMS (fn);
16988   tree targs = make_tree_vec (ntparms);
16989   tree decl_type;
16990   tree decl_arg_types;
16991   tree *args;
16992   unsigned int nargs, ix;
16993   tree arg;
16994
16995   /* Substitute the explicit template arguments into the type of DECL.
16996      The call to fn_type_unification will handle substitution into the
16997      FN.  */
16998   decl_type = TREE_TYPE (decl);
16999   if (explicit_args && uses_template_parms (decl_type))
17000     {
17001       tree tmpl;
17002       tree converted_args;
17003
17004       if (DECL_TEMPLATE_INFO (decl))
17005         tmpl = DECL_TI_TEMPLATE (decl);
17006       else
17007         /* We can get here for some invalid specializations.  */
17008         return NULL_TREE;
17009
17010       converted_args
17011         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17012                                  explicit_args, NULL_TREE,
17013                                  tf_none,
17014                                  /*require_all_args=*/false,
17015                                  /*use_default_args=*/false);
17016       if (converted_args == error_mark_node)
17017         return NULL_TREE;
17018
17019       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17020       if (decl_type == error_mark_node)
17021         return NULL_TREE;
17022     }
17023
17024   /* Never do unification on the 'this' parameter.  */
17025   decl_arg_types = skip_artificial_parms_for (decl, 
17026                                               TYPE_ARG_TYPES (decl_type));
17027
17028   nargs = list_length (decl_arg_types);
17029   args = XALLOCAVEC (tree, nargs);
17030   for (arg = decl_arg_types, ix = 0;
17031        arg != NULL_TREE && arg != void_list_node;
17032        arg = TREE_CHAIN (arg), ++ix)
17033     args[ix] = TREE_VALUE (arg);
17034
17035   if (fn_type_unification (fn, explicit_args, targs,
17036                            args, ix,
17037                            (check_rettype || DECL_CONV_FN_P (fn)
17038                             ? TREE_TYPE (decl_type) : NULL_TREE),
17039                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17040     return NULL_TREE;
17041
17042   return targs;
17043 }
17044
17045 /* Return the innermost template arguments that, when applied to a
17046    template specialization whose innermost template parameters are
17047    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17048    ARGS.
17049
17050    For example, suppose we have:
17051
17052      template <class T, class U> struct S {};
17053      template <class T> struct S<T*, int> {};
17054
17055    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17056    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17057    int}.  The resulting vector will be {double}, indicating that `T'
17058    is bound to `double'.  */
17059
17060 static tree
17061 get_class_bindings (tree tparms, tree spec_args, tree args)
17062 {
17063   int i, ntparms = TREE_VEC_LENGTH (tparms);
17064   tree deduced_args;
17065   tree innermost_deduced_args;
17066
17067   innermost_deduced_args = make_tree_vec (ntparms);
17068   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17069     {
17070       deduced_args = copy_node (args);
17071       SET_TMPL_ARGS_LEVEL (deduced_args,
17072                            TMPL_ARGS_DEPTH (deduced_args),
17073                            innermost_deduced_args);
17074     }
17075   else
17076     deduced_args = innermost_deduced_args;
17077
17078   if (unify (tparms, deduced_args,
17079              INNERMOST_TEMPLATE_ARGS (spec_args),
17080              INNERMOST_TEMPLATE_ARGS (args),
17081              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17082     return NULL_TREE;
17083
17084   for (i =  0; i < ntparms; ++i)
17085     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17086       return NULL_TREE;
17087
17088   /* Verify that nondeduced template arguments agree with the type
17089      obtained from argument deduction.
17090
17091      For example:
17092
17093        struct A { typedef int X; };
17094        template <class T, class U> struct C {};
17095        template <class T> struct C<T, typename T::X> {};
17096
17097      Then with the instantiation `C<A, int>', we can deduce that
17098      `T' is `A' but unify () does not check whether `typename T::X'
17099      is `int'.  */
17100   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17101   if (spec_args == error_mark_node
17102       /* We only need to check the innermost arguments; the other
17103          arguments will always agree.  */
17104       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17105                               INNERMOST_TEMPLATE_ARGS (args)))
17106     return NULL_TREE;
17107
17108   /* Now that we have bindings for all of the template arguments,
17109      ensure that the arguments deduced for the template template
17110      parameters have compatible template parameter lists.  See the use
17111      of template_template_parm_bindings_ok_p in fn_type_unification
17112      for more information.  */
17113   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17114     return NULL_TREE;
17115
17116   return deduced_args;
17117 }
17118
17119 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17120    Return the TREE_LIST node with the most specialized template, if
17121    any.  If there is no most specialized template, the error_mark_node
17122    is returned.
17123
17124    Note that this function does not look at, or modify, the
17125    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17126    returned is one of the elements of INSTANTIATIONS, callers may
17127    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17128    and retrieve it from the value returned.  */
17129
17130 tree
17131 most_specialized_instantiation (tree templates)
17132 {
17133   tree fn, champ;
17134
17135   ++processing_template_decl;
17136
17137   champ = templates;
17138   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17139     {
17140       int fate = 0;
17141
17142       if (get_bindings (TREE_VALUE (champ),
17143                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17144                         NULL_TREE, /*check_ret=*/true))
17145         fate--;
17146
17147       if (get_bindings (TREE_VALUE (fn),
17148                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17149                         NULL_TREE, /*check_ret=*/true))
17150         fate++;
17151
17152       if (fate == -1)
17153         champ = fn;
17154       else if (!fate)
17155         {
17156           /* Equally specialized, move to next function.  If there
17157              is no next function, nothing's most specialized.  */
17158           fn = TREE_CHAIN (fn);
17159           champ = fn;
17160           if (!fn)
17161             break;
17162         }
17163     }
17164
17165   if (champ)
17166     /* Now verify that champ is better than everything earlier in the
17167        instantiation list.  */
17168     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17169       if (get_bindings (TREE_VALUE (champ),
17170                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17171                         NULL_TREE, /*check_ret=*/true)
17172           || !get_bindings (TREE_VALUE (fn),
17173                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17174                             NULL_TREE, /*check_ret=*/true))
17175         {
17176           champ = NULL_TREE;
17177           break;
17178         }
17179
17180   processing_template_decl--;
17181
17182   if (!champ)
17183     return error_mark_node;
17184
17185   return champ;
17186 }
17187
17188 /* If DECL is a specialization of some template, return the most
17189    general such template.  Otherwise, returns NULL_TREE.
17190
17191    For example, given:
17192
17193      template <class T> struct S { template <class U> void f(U); };
17194
17195    if TMPL is `template <class U> void S<int>::f(U)' this will return
17196    the full template.  This function will not trace past partial
17197    specializations, however.  For example, given in addition:
17198
17199      template <class T> struct S<T*> { template <class U> void f(U); };
17200
17201    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17202    `template <class T> template <class U> S<T*>::f(U)'.  */
17203
17204 tree
17205 most_general_template (tree decl)
17206 {
17207   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17208      an immediate specialization.  */
17209   if (TREE_CODE (decl) == FUNCTION_DECL)
17210     {
17211       if (DECL_TEMPLATE_INFO (decl)) {
17212         decl = DECL_TI_TEMPLATE (decl);
17213
17214         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17215            template friend.  */
17216         if (TREE_CODE (decl) != TEMPLATE_DECL)
17217           return NULL_TREE;
17218       } else
17219         return NULL_TREE;
17220     }
17221
17222   /* Look for more and more general templates.  */
17223   while (DECL_TEMPLATE_INFO (decl))
17224     {
17225       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17226          (See cp-tree.h for details.)  */
17227       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17228         break;
17229
17230       if (CLASS_TYPE_P (TREE_TYPE (decl))
17231           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17232         break;
17233
17234       /* Stop if we run into an explicitly specialized class template.  */
17235       if (!DECL_NAMESPACE_SCOPE_P (decl)
17236           && DECL_CONTEXT (decl)
17237           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17238         break;
17239
17240       decl = DECL_TI_TEMPLATE (decl);
17241     }
17242
17243   return decl;
17244 }
17245
17246 /* Return the most specialized of the class template partial
17247    specializations of TMPL which can produce TYPE, a specialization of
17248    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17249    a _TYPE node corresponding to the partial specialization, while the
17250    TREE_PURPOSE is the set of template arguments that must be
17251    substituted into the TREE_TYPE in order to generate TYPE.
17252
17253    If the choice of partial specialization is ambiguous, a diagnostic
17254    is issued, and the error_mark_node is returned.  If there are no
17255    partial specializations of TMPL matching TYPE, then NULL_TREE is
17256    returned.  */
17257
17258 static tree
17259 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17260 {
17261   tree list = NULL_TREE;
17262   tree t;
17263   tree champ;
17264   int fate;
17265   bool ambiguous_p;
17266   tree args;
17267   tree outer_args = NULL_TREE;
17268
17269   tmpl = most_general_template (tmpl);
17270   args = CLASSTYPE_TI_ARGS (type);
17271
17272   /* For determining which partial specialization to use, only the
17273      innermost args are interesting.  */
17274   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17275     {
17276       outer_args = strip_innermost_template_args (args, 1);
17277       args = INNERMOST_TEMPLATE_ARGS (args);
17278     }
17279
17280   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17281     {
17282       tree partial_spec_args;
17283       tree spec_args;
17284       tree parms = TREE_VALUE (t);
17285
17286       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17287
17288       ++processing_template_decl;
17289
17290       if (outer_args)
17291         {
17292           int i;
17293
17294           /* Discard the outer levels of args, and then substitute in the
17295              template args from the enclosing class.  */
17296           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17297           partial_spec_args = tsubst_template_args
17298             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17299
17300           /* PARMS already refers to just the innermost parms, but the
17301              template parms in partial_spec_args had their levels lowered
17302              by tsubst, so we need to do the same for the parm list.  We
17303              can't just tsubst the TREE_VEC itself, as tsubst wants to
17304              treat a TREE_VEC as an argument vector.  */
17305           parms = copy_node (parms);
17306           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17307             TREE_VEC_ELT (parms, i) =
17308               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17309
17310         }
17311
17312       partial_spec_args =
17313           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17314                                  add_to_template_args (outer_args,
17315                                                        partial_spec_args),
17316                                  tmpl, tf_none,
17317                                  /*require_all_args=*/true,
17318                                  /*use_default_args=*/true);
17319
17320       --processing_template_decl;
17321
17322       if (partial_spec_args == error_mark_node)
17323         return error_mark_node;
17324
17325       spec_args = get_class_bindings (parms,
17326                                       partial_spec_args,
17327                                       args);
17328       if (spec_args)
17329         {
17330           if (outer_args)
17331             spec_args = add_to_template_args (outer_args, spec_args);
17332           list = tree_cons (spec_args, TREE_VALUE (t), list);
17333           TREE_TYPE (list) = TREE_TYPE (t);
17334         }
17335     }
17336
17337   if (! list)
17338     return NULL_TREE;
17339
17340   ambiguous_p = false;
17341   t = list;
17342   champ = t;
17343   t = TREE_CHAIN (t);
17344   for (; t; t = TREE_CHAIN (t))
17345     {
17346       fate = more_specialized_class (champ, t);
17347       if (fate == 1)
17348         ;
17349       else
17350         {
17351           if (fate == 0)
17352             {
17353               t = TREE_CHAIN (t);
17354               if (! t)
17355                 {
17356                   ambiguous_p = true;
17357                   break;
17358                 }
17359             }
17360           champ = t;
17361         }
17362     }
17363
17364   if (!ambiguous_p)
17365     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17366       {
17367         fate = more_specialized_class (champ, t);
17368         if (fate != 1)
17369           {
17370             ambiguous_p = true;
17371             break;
17372           }
17373       }
17374
17375   if (ambiguous_p)
17376     {
17377       const char *str;
17378       char *spaces = NULL;
17379       if (!(complain & tf_error))
17380         return error_mark_node;
17381       error ("ambiguous class template instantiation for %q#T", type);
17382       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17383       for (t = list; t; t = TREE_CHAIN (t))
17384         {
17385           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17386           spaces = spaces ? spaces : get_spaces (str);
17387         }
17388       free (spaces);
17389       return error_mark_node;
17390     }
17391
17392   return champ;
17393 }
17394
17395 /* Explicitly instantiate DECL.  */
17396
17397 void
17398 do_decl_instantiation (tree decl, tree storage)
17399 {
17400   tree result = NULL_TREE;
17401   int extern_p = 0;
17402
17403   if (!decl || decl == error_mark_node)
17404     /* An error occurred, for which grokdeclarator has already issued
17405        an appropriate message.  */
17406     return;
17407   else if (! DECL_LANG_SPECIFIC (decl))
17408     {
17409       error ("explicit instantiation of non-template %q#D", decl);
17410       return;
17411     }
17412   else if (TREE_CODE (decl) == VAR_DECL)
17413     {
17414       /* There is an asymmetry here in the way VAR_DECLs and
17415          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17416          the latter, the DECL we get back will be marked as a
17417          template instantiation, and the appropriate
17418          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17419          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17420          should handle VAR_DECLs as it currently handles
17421          FUNCTION_DECLs.  */
17422       if (!DECL_CLASS_SCOPE_P (decl))
17423         {
17424           error ("%qD is not a static data member of a class template", decl);
17425           return;
17426         }
17427       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17428       if (!result || TREE_CODE (result) != VAR_DECL)
17429         {
17430           error ("no matching template for %qD found", decl);
17431           return;
17432         }
17433       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17434         {
17435           error ("type %qT for explicit instantiation %qD does not match "
17436                  "declared type %qT", TREE_TYPE (result), decl,
17437                  TREE_TYPE (decl));
17438           return;
17439         }
17440     }
17441   else if (TREE_CODE (decl) != FUNCTION_DECL)
17442     {
17443       error ("explicit instantiation of %q#D", decl);
17444       return;
17445     }
17446   else
17447     result = decl;
17448
17449   /* Check for various error cases.  Note that if the explicit
17450      instantiation is valid the RESULT will currently be marked as an
17451      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17452      until we get here.  */
17453
17454   if (DECL_TEMPLATE_SPECIALIZATION (result))
17455     {
17456       /* DR 259 [temp.spec].
17457
17458          Both an explicit instantiation and a declaration of an explicit
17459          specialization shall not appear in a program unless the explicit
17460          instantiation follows a declaration of the explicit specialization.
17461
17462          For a given set of template parameters, if an explicit
17463          instantiation of a template appears after a declaration of an
17464          explicit specialization for that template, the explicit
17465          instantiation has no effect.  */
17466       return;
17467     }
17468   else if (DECL_EXPLICIT_INSTANTIATION (result))
17469     {
17470       /* [temp.spec]
17471
17472          No program shall explicitly instantiate any template more
17473          than once.
17474
17475          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17476          the first instantiation was `extern' and the second is not,
17477          and EXTERN_P for the opposite case.  */
17478       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17479         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17480       /* If an "extern" explicit instantiation follows an ordinary
17481          explicit instantiation, the template is instantiated.  */
17482       if (extern_p)
17483         return;
17484     }
17485   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17486     {
17487       error ("no matching template for %qD found", result);
17488       return;
17489     }
17490   else if (!DECL_TEMPLATE_INFO (result))
17491     {
17492       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17493       return;
17494     }
17495
17496   if (storage == NULL_TREE)
17497     ;
17498   else if (storage == ridpointers[(int) RID_EXTERN])
17499     {
17500       if (!in_system_header && (cxx_dialect == cxx98))
17501         pedwarn (input_location, OPT_pedantic, 
17502                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17503                  "instantiations");
17504       extern_p = 1;
17505     }
17506   else
17507     error ("storage class %qD applied to template instantiation", storage);
17508
17509   check_explicit_instantiation_namespace (result);
17510   mark_decl_instantiated (result, extern_p);
17511   if (! extern_p)
17512     instantiate_decl (result, /*defer_ok=*/1,
17513                       /*expl_inst_class_mem_p=*/false);
17514 }
17515
17516 static void
17517 mark_class_instantiated (tree t, int extern_p)
17518 {
17519   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17520   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17521   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17522   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17523   if (! extern_p)
17524     {
17525       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17526       rest_of_type_compilation (t, 1);
17527     }
17528 }
17529
17530 /* Called from do_type_instantiation through binding_table_foreach to
17531    do recursive instantiation for the type bound in ENTRY.  */
17532 static void
17533 bt_instantiate_type_proc (binding_entry entry, void *data)
17534 {
17535   tree storage = *(tree *) data;
17536
17537   if (MAYBE_CLASS_TYPE_P (entry->type)
17538       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17539     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17540 }
17541
17542 /* Called from do_type_instantiation to instantiate a member
17543    (a member function or a static member variable) of an
17544    explicitly instantiated class template.  */
17545 static void
17546 instantiate_class_member (tree decl, int extern_p)
17547 {
17548   mark_decl_instantiated (decl, extern_p);
17549   if (! extern_p)
17550     instantiate_decl (decl, /*defer_ok=*/1,
17551                       /*expl_inst_class_mem_p=*/true);
17552 }
17553
17554 /* Perform an explicit instantiation of template class T.  STORAGE, if
17555    non-null, is the RID for extern, inline or static.  COMPLAIN is
17556    nonzero if this is called from the parser, zero if called recursively,
17557    since the standard is unclear (as detailed below).  */
17558
17559 void
17560 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17561 {
17562   int extern_p = 0;
17563   int nomem_p = 0;
17564   int static_p = 0;
17565   int previous_instantiation_extern_p = 0;
17566
17567   if (TREE_CODE (t) == TYPE_DECL)
17568     t = TREE_TYPE (t);
17569
17570   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17571     {
17572       error ("explicit instantiation of non-template type %qT", t);
17573       return;
17574     }
17575
17576   complete_type (t);
17577
17578   if (!COMPLETE_TYPE_P (t))
17579     {
17580       if (complain & tf_error)
17581         error ("explicit instantiation of %q#T before definition of template",
17582                t);
17583       return;
17584     }
17585
17586   if (storage != NULL_TREE)
17587     {
17588       if (!in_system_header)
17589         {
17590           if (storage == ridpointers[(int) RID_EXTERN])
17591             {
17592               if (cxx_dialect == cxx98)
17593                 pedwarn (input_location, OPT_pedantic, 
17594                          "ISO C++ 1998 forbids the use of %<extern%> on "
17595                          "explicit instantiations");
17596             }
17597           else
17598             pedwarn (input_location, OPT_pedantic, 
17599                      "ISO C++ forbids the use of %qE"
17600                      " on explicit instantiations", storage);
17601         }
17602
17603       if (storage == ridpointers[(int) RID_INLINE])
17604         nomem_p = 1;
17605       else if (storage == ridpointers[(int) RID_EXTERN])
17606         extern_p = 1;
17607       else if (storage == ridpointers[(int) RID_STATIC])
17608         static_p = 1;
17609       else
17610         {
17611           error ("storage class %qD applied to template instantiation",
17612                  storage);
17613           extern_p = 0;
17614         }
17615     }
17616
17617   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17618     {
17619       /* DR 259 [temp.spec].
17620
17621          Both an explicit instantiation and a declaration of an explicit
17622          specialization shall not appear in a program unless the explicit
17623          instantiation follows a declaration of the explicit specialization.
17624
17625          For a given set of template parameters, if an explicit
17626          instantiation of a template appears after a declaration of an
17627          explicit specialization for that template, the explicit
17628          instantiation has no effect.  */
17629       return;
17630     }
17631   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17632     {
17633       /* [temp.spec]
17634
17635          No program shall explicitly instantiate any template more
17636          than once.
17637
17638          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17639          instantiation was `extern'.  If EXTERN_P then the second is.
17640          These cases are OK.  */
17641       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17642
17643       if (!previous_instantiation_extern_p && !extern_p
17644           && (complain & tf_error))
17645         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17646
17647       /* If we've already instantiated the template, just return now.  */
17648       if (!CLASSTYPE_INTERFACE_ONLY (t))
17649         return;
17650     }
17651
17652   check_explicit_instantiation_namespace (TYPE_NAME (t));
17653   mark_class_instantiated (t, extern_p);
17654
17655   if (nomem_p)
17656     return;
17657
17658   {
17659     tree tmp;
17660
17661     /* In contrast to implicit instantiation, where only the
17662        declarations, and not the definitions, of members are
17663        instantiated, we have here:
17664
17665          [temp.explicit]
17666
17667          The explicit instantiation of a class template specialization
17668          implies the instantiation of all of its members not
17669          previously explicitly specialized in the translation unit
17670          containing the explicit instantiation.
17671
17672        Of course, we can't instantiate member template classes, since
17673        we don't have any arguments for them.  Note that the standard
17674        is unclear on whether the instantiation of the members are
17675        *explicit* instantiations or not.  However, the most natural
17676        interpretation is that it should be an explicit instantiation.  */
17677
17678     if (! static_p)
17679       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17680         if (TREE_CODE (tmp) == FUNCTION_DECL
17681             && DECL_TEMPLATE_INSTANTIATION (tmp))
17682           instantiate_class_member (tmp, extern_p);
17683
17684     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17685       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17686         instantiate_class_member (tmp, extern_p);
17687
17688     if (CLASSTYPE_NESTED_UTDS (t))
17689       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17690                              bt_instantiate_type_proc, &storage);
17691   }
17692 }
17693
17694 /* Given a function DECL, which is a specialization of TMPL, modify
17695    DECL to be a re-instantiation of TMPL with the same template
17696    arguments.  TMPL should be the template into which tsubst'ing
17697    should occur for DECL, not the most general template.
17698
17699    One reason for doing this is a scenario like this:
17700
17701      template <class T>
17702      void f(const T&, int i);
17703
17704      void g() { f(3, 7); }
17705
17706      template <class T>
17707      void f(const T& t, const int i) { }
17708
17709    Note that when the template is first instantiated, with
17710    instantiate_template, the resulting DECL will have no name for the
17711    first parameter, and the wrong type for the second.  So, when we go
17712    to instantiate the DECL, we regenerate it.  */
17713
17714 static void
17715 regenerate_decl_from_template (tree decl, tree tmpl)
17716 {
17717   /* The arguments used to instantiate DECL, from the most general
17718      template.  */
17719   tree args;
17720   tree code_pattern;
17721
17722   args = DECL_TI_ARGS (decl);
17723   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17724
17725   /* Make sure that we can see identifiers, and compute access
17726      correctly.  */
17727   push_access_scope (decl);
17728
17729   if (TREE_CODE (decl) == FUNCTION_DECL)
17730     {
17731       tree decl_parm;
17732       tree pattern_parm;
17733       tree specs;
17734       int args_depth;
17735       int parms_depth;
17736
17737       args_depth = TMPL_ARGS_DEPTH (args);
17738       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17739       if (args_depth > parms_depth)
17740         args = get_innermost_template_args (args, parms_depth);
17741
17742       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17743                                               args, tf_error, NULL_TREE,
17744                                               /*defer_ok*/false);
17745       if (specs && specs != error_mark_node)
17746         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17747                                                     specs);
17748
17749       /* Merge parameter declarations.  */
17750       decl_parm = skip_artificial_parms_for (decl,
17751                                              DECL_ARGUMENTS (decl));
17752       pattern_parm
17753         = skip_artificial_parms_for (code_pattern,
17754                                      DECL_ARGUMENTS (code_pattern));
17755       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17756         {
17757           tree parm_type;
17758           tree attributes;
17759           
17760           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17761             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17762           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17763                               NULL_TREE);
17764           parm_type = type_decays_to (parm_type);
17765           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17766             TREE_TYPE (decl_parm) = parm_type;
17767           attributes = DECL_ATTRIBUTES (pattern_parm);
17768           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17769             {
17770               DECL_ATTRIBUTES (decl_parm) = attributes;
17771               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17772             }
17773           decl_parm = DECL_CHAIN (decl_parm);
17774           pattern_parm = DECL_CHAIN (pattern_parm);
17775         }
17776       /* Merge any parameters that match with the function parameter
17777          pack.  */
17778       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17779         {
17780           int i, len;
17781           tree expanded_types;
17782           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17783              the parameters in this function parameter pack.  */
17784           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17785                                                  args, tf_error, NULL_TREE);
17786           len = TREE_VEC_LENGTH (expanded_types);
17787           for (i = 0; i < len; i++)
17788             {
17789               tree parm_type;
17790               tree attributes;
17791           
17792               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17793                 /* Rename the parameter to include the index.  */
17794                 DECL_NAME (decl_parm) = 
17795                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17796               parm_type = TREE_VEC_ELT (expanded_types, i);
17797               parm_type = type_decays_to (parm_type);
17798               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17799                 TREE_TYPE (decl_parm) = parm_type;
17800               attributes = DECL_ATTRIBUTES (pattern_parm);
17801               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17802                 {
17803                   DECL_ATTRIBUTES (decl_parm) = attributes;
17804                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17805                 }
17806               decl_parm = DECL_CHAIN (decl_parm);
17807             }
17808         }
17809       /* Merge additional specifiers from the CODE_PATTERN.  */
17810       if (DECL_DECLARED_INLINE_P (code_pattern)
17811           && !DECL_DECLARED_INLINE_P (decl))
17812         DECL_DECLARED_INLINE_P (decl) = 1;
17813     }
17814   else if (TREE_CODE (decl) == VAR_DECL)
17815     {
17816       DECL_INITIAL (decl) =
17817         tsubst_expr (DECL_INITIAL (code_pattern), args,
17818                      tf_error, DECL_TI_TEMPLATE (decl),
17819                      /*integral_constant_expression_p=*/false);
17820       if (VAR_HAD_UNKNOWN_BOUND (decl))
17821         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17822                                    tf_error, DECL_TI_TEMPLATE (decl));
17823     }
17824   else
17825     gcc_unreachable ();
17826
17827   pop_access_scope (decl);
17828 }
17829
17830 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17831    substituted to get DECL.  */
17832
17833 tree
17834 template_for_substitution (tree decl)
17835 {
17836   tree tmpl = DECL_TI_TEMPLATE (decl);
17837
17838   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17839      for the instantiation.  This is not always the most general
17840      template.  Consider, for example:
17841
17842         template <class T>
17843         struct S { template <class U> void f();
17844                    template <> void f<int>(); };
17845
17846      and an instantiation of S<double>::f<int>.  We want TD to be the
17847      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17848   while (/* An instantiation cannot have a definition, so we need a
17849             more general template.  */
17850          DECL_TEMPLATE_INSTANTIATION (tmpl)
17851            /* We must also deal with friend templates.  Given:
17852
17853                 template <class T> struct S {
17854                   template <class U> friend void f() {};
17855                 };
17856
17857               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17858               so far as the language is concerned, but that's still
17859               where we get the pattern for the instantiation from.  On
17860               other hand, if the definition comes outside the class, say:
17861
17862                 template <class T> struct S {
17863                   template <class U> friend void f();
17864                 };
17865                 template <class U> friend void f() {}
17866
17867               we don't need to look any further.  That's what the check for
17868               DECL_INITIAL is for.  */
17869           || (TREE_CODE (decl) == FUNCTION_DECL
17870               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17871               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17872     {
17873       /* The present template, TD, should not be a definition.  If it
17874          were a definition, we should be using it!  Note that we
17875          cannot restructure the loop to just keep going until we find
17876          a template with a definition, since that might go too far if
17877          a specialization was declared, but not defined.  */
17878       gcc_assert (TREE_CODE (decl) != VAR_DECL
17879                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17880
17881       /* Fetch the more general template.  */
17882       tmpl = DECL_TI_TEMPLATE (tmpl);
17883     }
17884
17885   return tmpl;
17886 }
17887
17888 /* Returns true if we need to instantiate this template instance even if we
17889    know we aren't going to emit it..  */
17890
17891 bool
17892 always_instantiate_p (tree decl)
17893 {
17894   /* We always instantiate inline functions so that we can inline them.  An
17895      explicit instantiation declaration prohibits implicit instantiation of
17896      non-inline functions.  With high levels of optimization, we would
17897      normally inline non-inline functions -- but we're not allowed to do
17898      that for "extern template" functions.  Therefore, we check
17899      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17900   return ((TREE_CODE (decl) == FUNCTION_DECL
17901            && DECL_DECLARED_INLINE_P (decl))
17902           /* And we need to instantiate static data members so that
17903              their initializers are available in integral constant
17904              expressions.  */
17905           || (TREE_CODE (decl) == VAR_DECL
17906               && decl_maybe_constant_var_p (decl)));
17907 }
17908
17909 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17910    instantiate it now, modifying TREE_TYPE (fn).  */
17911
17912 void
17913 maybe_instantiate_noexcept (tree fn)
17914 {
17915   tree fntype, spec, noex, clone;
17916
17917   if (DECL_CLONED_FUNCTION_P (fn))
17918     fn = DECL_CLONED_FUNCTION (fn);
17919   fntype = TREE_TYPE (fn);
17920   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17921
17922   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17923     return;
17924
17925   noex = TREE_PURPOSE (spec);
17926
17927   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17928     {
17929       push_tinst_level (fn);
17930       push_access_scope (fn);
17931       input_location = DECL_SOURCE_LOCATION (fn);
17932       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17933                                     DEFERRED_NOEXCEPT_ARGS (noex),
17934                                     tf_warning_or_error, fn, /*function_p=*/false,
17935                                     /*integral_constant_expression_p=*/true);
17936       pop_access_scope (fn);
17937       pop_tinst_level ();
17938       spec = build_noexcept_spec (noex, tf_warning_or_error);
17939       if (spec == error_mark_node)
17940         spec = noexcept_false_spec;
17941     }
17942   else
17943     {
17944       /* This is an implicitly declared function, so NOEX is a list of
17945          other functions to evaluate and merge.  */
17946       tree elt;
17947       spec = noexcept_true_spec;
17948       for (elt = noex; elt; elt = OVL_NEXT (elt))
17949         {
17950           tree fn = OVL_CURRENT (elt);
17951           tree subspec;
17952           maybe_instantiate_noexcept (fn);
17953           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17954           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17955         }
17956     }
17957
17958   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17959
17960   FOR_EACH_CLONE (clone, fn)
17961     {
17962       if (TREE_TYPE (clone) == fntype)
17963         TREE_TYPE (clone) = TREE_TYPE (fn);
17964       else
17965         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
17966     }
17967 }
17968
17969 /* Produce the definition of D, a _DECL generated from a template.  If
17970    DEFER_OK is nonzero, then we don't have to actually do the
17971    instantiation now; we just have to do it sometime.  Normally it is
17972    an error if this is an explicit instantiation but D is undefined.
17973    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17974    explicitly instantiated class template.  */
17975
17976 tree
17977 instantiate_decl (tree d, int defer_ok,
17978                   bool expl_inst_class_mem_p)
17979 {
17980   tree tmpl = DECL_TI_TEMPLATE (d);
17981   tree gen_args;
17982   tree args;
17983   tree td;
17984   tree code_pattern;
17985   tree spec;
17986   tree gen_tmpl;
17987   bool pattern_defined;
17988   int need_push;
17989   location_t saved_loc = input_location;
17990   bool external_p;
17991
17992   /* This function should only be used to instantiate templates for
17993      functions and static member variables.  */
17994   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17995               || TREE_CODE (d) == VAR_DECL);
17996
17997   /* Variables are never deferred; if instantiation is required, they
17998      are instantiated right away.  That allows for better code in the
17999      case that an expression refers to the value of the variable --
18000      if the variable has a constant value the referring expression can
18001      take advantage of that fact.  */
18002   if (TREE_CODE (d) == VAR_DECL
18003       || DECL_DECLARED_CONSTEXPR_P (d))
18004     defer_ok = 0;
18005
18006   /* Don't instantiate cloned functions.  Instead, instantiate the
18007      functions they cloned.  */
18008   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18009     d = DECL_CLONED_FUNCTION (d);
18010
18011   if (DECL_TEMPLATE_INSTANTIATED (d)
18012       || DECL_TEMPLATE_SPECIALIZATION (d))
18013     /* D has already been instantiated or explicitly specialized, so
18014        there's nothing for us to do here.
18015
18016        It might seem reasonable to check whether or not D is an explicit
18017        instantiation, and, if so, stop here.  But when an explicit
18018        instantiation is deferred until the end of the compilation,
18019        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18020        the instantiation.  */
18021     return d;
18022
18023   /* Check to see whether we know that this template will be
18024      instantiated in some other file, as with "extern template"
18025      extension.  */
18026   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18027
18028   /* In general, we do not instantiate such templates.  */
18029   if (external_p && !always_instantiate_p (d))
18030     return d;
18031
18032   gen_tmpl = most_general_template (tmpl);
18033   gen_args = DECL_TI_ARGS (d);
18034
18035   if (tmpl != gen_tmpl)
18036     /* We should already have the extra args.  */
18037     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18038                 == TMPL_ARGS_DEPTH (gen_args));
18039   /* And what's in the hash table should match D.  */
18040   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18041               || spec == NULL_TREE);
18042
18043   /* This needs to happen before any tsubsting.  */
18044   if (! push_tinst_level (d))
18045     return d;
18046
18047   timevar_push (TV_TEMPLATE_INST);
18048
18049   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18050      for the instantiation.  */
18051   td = template_for_substitution (d);
18052   code_pattern = DECL_TEMPLATE_RESULT (td);
18053
18054   /* We should never be trying to instantiate a member of a class
18055      template or partial specialization.  */
18056   gcc_assert (d != code_pattern);
18057
18058   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18059       || DECL_TEMPLATE_SPECIALIZATION (td))
18060     /* In the case of a friend template whose definition is provided
18061        outside the class, we may have too many arguments.  Drop the
18062        ones we don't need.  The same is true for specializations.  */
18063     args = get_innermost_template_args
18064       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18065   else
18066     args = gen_args;
18067
18068   if (TREE_CODE (d) == FUNCTION_DECL)
18069     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18070                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18071   else
18072     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18073
18074   /* We may be in the middle of deferred access check.  Disable it now.  */
18075   push_deferring_access_checks (dk_no_deferred);
18076
18077   /* Unless an explicit instantiation directive has already determined
18078      the linkage of D, remember that a definition is available for
18079      this entity.  */
18080   if (pattern_defined
18081       && !DECL_INTERFACE_KNOWN (d)
18082       && !DECL_NOT_REALLY_EXTERN (d))
18083     mark_definable (d);
18084
18085   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18086   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18087   input_location = DECL_SOURCE_LOCATION (d);
18088
18089   /* If D is a member of an explicitly instantiated class template,
18090      and no definition is available, treat it like an implicit
18091      instantiation.  */
18092   if (!pattern_defined && expl_inst_class_mem_p
18093       && DECL_EXPLICIT_INSTANTIATION (d))
18094     {
18095       /* Leave linkage flags alone on instantiations with anonymous
18096          visibility.  */
18097       if (TREE_PUBLIC (d))
18098         {
18099           DECL_NOT_REALLY_EXTERN (d) = 0;
18100           DECL_INTERFACE_KNOWN (d) = 0;
18101         }
18102       SET_DECL_IMPLICIT_INSTANTIATION (d);
18103     }
18104
18105   if (TREE_CODE (d) == FUNCTION_DECL)
18106     maybe_instantiate_noexcept (d);
18107
18108   /* Recheck the substitutions to obtain any warning messages
18109      about ignoring cv qualifiers.  Don't do this for artificial decls,
18110      as it breaks the context-sensitive substitution for lambda op(). */
18111   if (!defer_ok && !DECL_ARTIFICIAL (d))
18112     {
18113       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18114       tree type = TREE_TYPE (gen);
18115
18116       /* Make sure that we can see identifiers, and compute access
18117          correctly.  D is already the target FUNCTION_DECL with the
18118          right context.  */
18119       push_access_scope (d);
18120
18121       if (TREE_CODE (gen) == FUNCTION_DECL)
18122         {
18123           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18124           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18125                                           d, /*defer_ok*/true);
18126           /* Don't simply tsubst the function type, as that will give
18127              duplicate warnings about poor parameter qualifications.
18128              The function arguments are the same as the decl_arguments
18129              without the top level cv qualifiers.  */
18130           type = TREE_TYPE (type);
18131         }
18132       tsubst (type, gen_args, tf_warning_or_error, d);
18133
18134       pop_access_scope (d);
18135     }
18136
18137   /* Defer all other templates, unless we have been explicitly
18138      forbidden from doing so.  */
18139   if (/* If there is no definition, we cannot instantiate the
18140          template.  */
18141       ! pattern_defined
18142       /* If it's OK to postpone instantiation, do so.  */
18143       || defer_ok
18144       /* If this is a static data member that will be defined
18145          elsewhere, we don't want to instantiate the entire data
18146          member, but we do want to instantiate the initializer so that
18147          we can substitute that elsewhere.  */
18148       || (external_p && TREE_CODE (d) == VAR_DECL))
18149     {
18150       /* The definition of the static data member is now required so
18151          we must substitute the initializer.  */
18152       if (TREE_CODE (d) == VAR_DECL
18153           && !DECL_INITIAL (d)
18154           && DECL_INITIAL (code_pattern))
18155         {
18156           tree ns;
18157           tree init;
18158           bool const_init = false;
18159
18160           ns = decl_namespace_context (d);
18161           push_nested_namespace (ns);
18162           push_nested_class (DECL_CONTEXT (d));
18163           init = tsubst_expr (DECL_INITIAL (code_pattern),
18164                               args,
18165                               tf_warning_or_error, NULL_TREE,
18166                               /*integral_constant_expression_p=*/false);
18167           /* Make sure the initializer is still constant, in case of
18168              circular dependency (template/instantiate6.C). */
18169           const_init
18170             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18171           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18172                           /*asmspec_tree=*/NULL_TREE,
18173                           LOOKUP_ONLYCONVERTING);
18174           pop_nested_class ();
18175           pop_nested_namespace (ns);
18176         }
18177
18178       /* We restore the source position here because it's used by
18179          add_pending_template.  */
18180       input_location = saved_loc;
18181
18182       if (at_eof && !pattern_defined
18183           && DECL_EXPLICIT_INSTANTIATION (d)
18184           && DECL_NOT_REALLY_EXTERN (d))
18185         /* [temp.explicit]
18186
18187            The definition of a non-exported function template, a
18188            non-exported member function template, or a non-exported
18189            member function or static data member of a class template
18190            shall be present in every translation unit in which it is
18191            explicitly instantiated.  */
18192         permerror (input_location,  "explicit instantiation of %qD "
18193                    "but no definition available", d);
18194
18195       /* If we're in unevaluated context, we just wanted to get the
18196          constant value; this isn't an odr use, so don't queue
18197          a full instantiation.  */
18198       if (cp_unevaluated_operand != 0)
18199         goto out;
18200       /* ??? Historically, we have instantiated inline functions, even
18201          when marked as "extern template".  */
18202       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18203         add_pending_template (d);
18204       goto out;
18205     }
18206   /* Tell the repository that D is available in this translation unit
18207      -- and see if it is supposed to be instantiated here.  */
18208   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18209     {
18210       /* In a PCH file, despite the fact that the repository hasn't
18211          requested instantiation in the PCH it is still possible that
18212          an instantiation will be required in a file that includes the
18213          PCH.  */
18214       if (pch_file)
18215         add_pending_template (d);
18216       /* Instantiate inline functions so that the inliner can do its
18217          job, even though we'll not be emitting a copy of this
18218          function.  */
18219       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18220         goto out;
18221     }
18222
18223   need_push = !cfun || !global_bindings_p ();
18224   if (need_push)
18225     push_to_top_level ();
18226
18227   /* Mark D as instantiated so that recursive calls to
18228      instantiate_decl do not try to instantiate it again.  */
18229   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18230
18231   /* Regenerate the declaration in case the template has been modified
18232      by a subsequent redeclaration.  */
18233   regenerate_decl_from_template (d, td);
18234
18235   /* We already set the file and line above.  Reset them now in case
18236      they changed as a result of calling regenerate_decl_from_template.  */
18237   input_location = DECL_SOURCE_LOCATION (d);
18238
18239   if (TREE_CODE (d) == VAR_DECL)
18240     {
18241       tree init;
18242       bool const_init = false;
18243
18244       /* Clear out DECL_RTL; whatever was there before may not be right
18245          since we've reset the type of the declaration.  */
18246       SET_DECL_RTL (d, NULL);
18247       DECL_IN_AGGR_P (d) = 0;
18248
18249       /* The initializer is placed in DECL_INITIAL by
18250          regenerate_decl_from_template so we don't need to
18251          push/pop_access_scope again here.  Pull it out so that
18252          cp_finish_decl can process it.  */
18253       init = DECL_INITIAL (d);
18254       DECL_INITIAL (d) = NULL_TREE;
18255       DECL_INITIALIZED_P (d) = 0;
18256
18257       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18258          initializer.  That function will defer actual emission until
18259          we have a chance to determine linkage.  */
18260       DECL_EXTERNAL (d) = 0;
18261
18262       /* Enter the scope of D so that access-checking works correctly.  */
18263       push_nested_class (DECL_CONTEXT (d));
18264       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18265       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18266       pop_nested_class ();
18267     }
18268   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18269     synthesize_method (d);
18270   else if (TREE_CODE (d) == FUNCTION_DECL)
18271     {
18272       htab_t saved_local_specializations;
18273       tree subst_decl;
18274       tree tmpl_parm;
18275       tree spec_parm;
18276
18277       /* Save away the current list, in case we are instantiating one
18278          template from within the body of another.  */
18279       saved_local_specializations = local_specializations;
18280
18281       /* Set up the list of local specializations.  */
18282       local_specializations = htab_create (37,
18283                                            hash_local_specialization,
18284                                            eq_local_specializations,
18285                                            NULL);
18286
18287       /* Set up context.  */
18288       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18289
18290       /* Create substitution entries for the parameters.  */
18291       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18292       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18293       spec_parm = DECL_ARGUMENTS (d);
18294       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18295         {
18296           register_local_specialization (spec_parm, tmpl_parm);
18297           spec_parm = skip_artificial_parms_for (d, spec_parm);
18298           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18299         }
18300       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18301         {
18302           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18303             {
18304               register_local_specialization (spec_parm, tmpl_parm);
18305               spec_parm = DECL_CHAIN (spec_parm);
18306             }
18307           else
18308             {
18309               /* Register the (value) argument pack as a specialization of
18310                  TMPL_PARM, then move on.  */
18311               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18312               register_local_specialization (argpack, tmpl_parm);
18313             }
18314         }
18315       gcc_assert (!spec_parm);
18316
18317       /* Substitute into the body of the function.  */
18318       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18319                    tf_warning_or_error, tmpl,
18320                    /*integral_constant_expression_p=*/false);
18321
18322       /* Set the current input_location to the end of the function
18323          so that finish_function knows where we are.  */
18324       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18325
18326       /* We don't need the local specializations any more.  */
18327       htab_delete (local_specializations);
18328       local_specializations = saved_local_specializations;
18329
18330       /* Finish the function.  */
18331       d = finish_function (0);
18332       expand_or_defer_fn (d);
18333     }
18334
18335   /* We're not deferring instantiation any more.  */
18336   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18337
18338   if (need_push)
18339     pop_from_top_level ();
18340
18341 out:
18342   input_location = saved_loc;
18343   pop_deferring_access_checks ();
18344   pop_tinst_level ();
18345
18346   timevar_pop (TV_TEMPLATE_INST);
18347
18348   return d;
18349 }
18350
18351 /* Run through the list of templates that we wish we could
18352    instantiate, and instantiate any we can.  RETRIES is the
18353    number of times we retry pending template instantiation.  */
18354
18355 void
18356 instantiate_pending_templates (int retries)
18357 {
18358   int reconsider;
18359   location_t saved_loc = input_location;
18360
18361   /* Instantiating templates may trigger vtable generation.  This in turn
18362      may require further template instantiations.  We place a limit here
18363      to avoid infinite loop.  */
18364   if (pending_templates && retries >= max_tinst_depth)
18365     {
18366       tree decl = pending_templates->tinst->decl;
18367
18368       error ("template instantiation depth exceeds maximum of %d"
18369              " instantiating %q+D, possibly from virtual table generation"
18370              " (use -ftemplate-depth= to increase the maximum)",
18371              max_tinst_depth, decl);
18372       if (TREE_CODE (decl) == FUNCTION_DECL)
18373         /* Pretend that we defined it.  */
18374         DECL_INITIAL (decl) = error_mark_node;
18375       return;
18376     }
18377
18378   do
18379     {
18380       struct pending_template **t = &pending_templates;
18381       struct pending_template *last = NULL;
18382       reconsider = 0;
18383       while (*t)
18384         {
18385           tree instantiation = reopen_tinst_level ((*t)->tinst);
18386           bool complete = false;
18387
18388           if (TYPE_P (instantiation))
18389             {
18390               tree fn;
18391
18392               if (!COMPLETE_TYPE_P (instantiation))
18393                 {
18394                   instantiate_class_template (instantiation);
18395                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18396                     for (fn = TYPE_METHODS (instantiation);
18397                          fn;
18398                          fn = TREE_CHAIN (fn))
18399                       if (! DECL_ARTIFICIAL (fn))
18400                         instantiate_decl (fn,
18401                                           /*defer_ok=*/0,
18402                                           /*expl_inst_class_mem_p=*/false);
18403                   if (COMPLETE_TYPE_P (instantiation))
18404                     reconsider = 1;
18405                 }
18406
18407               complete = COMPLETE_TYPE_P (instantiation);
18408             }
18409           else
18410             {
18411               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18412                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18413                 {
18414                   instantiation
18415                     = instantiate_decl (instantiation,
18416                                         /*defer_ok=*/0,
18417                                         /*expl_inst_class_mem_p=*/false);
18418                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18419                     reconsider = 1;
18420                 }
18421
18422               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18423                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18424             }
18425
18426           if (complete)
18427             /* If INSTANTIATION has been instantiated, then we don't
18428                need to consider it again in the future.  */
18429             *t = (*t)->next;
18430           else
18431             {
18432               last = *t;
18433               t = &(*t)->next;
18434             }
18435           tinst_depth = 0;
18436           current_tinst_level = NULL;
18437         }
18438       last_pending_template = last;
18439     }
18440   while (reconsider);
18441
18442   input_location = saved_loc;
18443 }
18444
18445 /* Substitute ARGVEC into T, which is a list of initializers for
18446    either base class or a non-static data member.  The TREE_PURPOSEs
18447    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18448    instantiate_decl.  */
18449
18450 static tree
18451 tsubst_initializer_list (tree t, tree argvec)
18452 {
18453   tree inits = NULL_TREE;
18454
18455   for (; t; t = TREE_CHAIN (t))
18456     {
18457       tree decl;
18458       tree init;
18459       tree expanded_bases = NULL_TREE;
18460       tree expanded_arguments = NULL_TREE;
18461       int i, len = 1;
18462
18463       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18464         {
18465           tree expr;
18466           tree arg;
18467
18468           /* Expand the base class expansion type into separate base
18469              classes.  */
18470           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18471                                                  tf_warning_or_error,
18472                                                  NULL_TREE);
18473           if (expanded_bases == error_mark_node)
18474             continue;
18475           
18476           /* We'll be building separate TREE_LISTs of arguments for
18477              each base.  */
18478           len = TREE_VEC_LENGTH (expanded_bases);
18479           expanded_arguments = make_tree_vec (len);
18480           for (i = 0; i < len; i++)
18481             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18482
18483           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18484              expand each argument in the TREE_VALUE of t.  */
18485           expr = make_node (EXPR_PACK_EXPANSION);
18486           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18487             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18488
18489           if (TREE_VALUE (t) == void_type_node)
18490             /* VOID_TYPE_NODE is used to indicate
18491                value-initialization.  */
18492             {
18493               for (i = 0; i < len; i++)
18494                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18495             }
18496           else
18497             {
18498               /* Substitute parameter packs into each argument in the
18499                  TREE_LIST.  */
18500               in_base_initializer = 1;
18501               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18502                 {
18503                   tree expanded_exprs;
18504
18505                   /* Expand the argument.  */
18506                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18507                   expanded_exprs 
18508                     = tsubst_pack_expansion (expr, argvec,
18509                                              tf_warning_or_error,
18510                                              NULL_TREE);
18511                   if (expanded_exprs == error_mark_node)
18512                     continue;
18513
18514                   /* Prepend each of the expanded expressions to the
18515                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18516                   for (i = 0; i < len; i++)
18517                     {
18518                       TREE_VEC_ELT (expanded_arguments, i) = 
18519                         tree_cons (NULL_TREE, 
18520                                    TREE_VEC_ELT (expanded_exprs, i),
18521                                    TREE_VEC_ELT (expanded_arguments, i));
18522                     }
18523                 }
18524               in_base_initializer = 0;
18525
18526               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18527                  since we built them backwards.  */
18528               for (i = 0; i < len; i++)
18529                 {
18530                   TREE_VEC_ELT (expanded_arguments, i) = 
18531                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18532                 }
18533             }
18534         }
18535
18536       for (i = 0; i < len; ++i)
18537         {
18538           if (expanded_bases)
18539             {
18540               decl = TREE_VEC_ELT (expanded_bases, i);
18541               decl = expand_member_init (decl);
18542               init = TREE_VEC_ELT (expanded_arguments, i);
18543             }
18544           else
18545             {
18546               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18547                                   tf_warning_or_error, NULL_TREE);
18548
18549               decl = expand_member_init (decl);
18550               if (decl && !DECL_P (decl))
18551                 in_base_initializer = 1;
18552
18553               init = TREE_VALUE (t);
18554               if (init != void_type_node)
18555                 init = tsubst_expr (init, argvec,
18556                                     tf_warning_or_error, NULL_TREE,
18557                                     /*integral_constant_expression_p=*/false);
18558               in_base_initializer = 0;
18559             }
18560
18561           if (decl)
18562             {
18563               init = build_tree_list (decl, init);
18564               TREE_CHAIN (init) = inits;
18565               inits = init;
18566             }
18567         }
18568     }
18569   return inits;
18570 }
18571
18572 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18573
18574 static void
18575 set_current_access_from_decl (tree decl)
18576 {
18577   if (TREE_PRIVATE (decl))
18578     current_access_specifier = access_private_node;
18579   else if (TREE_PROTECTED (decl))
18580     current_access_specifier = access_protected_node;
18581   else
18582     current_access_specifier = access_public_node;
18583 }
18584
18585 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18586    is the instantiation (which should have been created with
18587    start_enum) and ARGS are the template arguments to use.  */
18588
18589 static void
18590 tsubst_enum (tree tag, tree newtag, tree args)
18591 {
18592   tree e;
18593
18594   if (SCOPED_ENUM_P (newtag))
18595     begin_scope (sk_scoped_enum, newtag);
18596
18597   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18598     {
18599       tree value;
18600       tree decl;
18601
18602       decl = TREE_VALUE (e);
18603       /* Note that in a template enum, the TREE_VALUE is the
18604          CONST_DECL, not the corresponding INTEGER_CST.  */
18605       value = tsubst_expr (DECL_INITIAL (decl),
18606                            args, tf_warning_or_error, NULL_TREE,
18607                            /*integral_constant_expression_p=*/true);
18608
18609       /* Give this enumeration constant the correct access.  */
18610       set_current_access_from_decl (decl);
18611
18612       /* Actually build the enumerator itself.  */
18613       build_enumerator
18614         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18615     }
18616
18617   if (SCOPED_ENUM_P (newtag))
18618     finish_scope ();
18619
18620   finish_enum_value_list (newtag);
18621   finish_enum (newtag);
18622
18623   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18624     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18625 }
18626
18627 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18628    its type -- but without substituting the innermost set of template
18629    arguments.  So, innermost set of template parameters will appear in
18630    the type.  */
18631
18632 tree
18633 get_mostly_instantiated_function_type (tree decl)
18634 {
18635   tree fn_type;
18636   tree tmpl;
18637   tree targs;
18638   tree tparms;
18639   int parm_depth;
18640
18641   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18642   targs = DECL_TI_ARGS (decl);
18643   tparms = DECL_TEMPLATE_PARMS (tmpl);
18644   parm_depth = TMPL_PARMS_DEPTH (tparms);
18645
18646   /* There should be as many levels of arguments as there are levels
18647      of parameters.  */
18648   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18649
18650   fn_type = TREE_TYPE (tmpl);
18651
18652   if (parm_depth == 1)
18653     /* No substitution is necessary.  */
18654     ;
18655   else
18656     {
18657       int i;
18658       tree partial_args;
18659
18660       /* Replace the innermost level of the TARGS with NULL_TREEs to
18661          let tsubst know not to substitute for those parameters.  */
18662       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18663       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18664         SET_TMPL_ARGS_LEVEL (partial_args, i,
18665                              TMPL_ARGS_LEVEL (targs, i));
18666       SET_TMPL_ARGS_LEVEL (partial_args,
18667                            TMPL_ARGS_DEPTH (targs),
18668                            make_tree_vec (DECL_NTPARMS (tmpl)));
18669
18670       /* Make sure that we can see identifiers, and compute access
18671          correctly.  */
18672       push_access_scope (decl);
18673
18674       ++processing_template_decl;
18675       /* Now, do the (partial) substitution to figure out the
18676          appropriate function type.  */
18677       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18678       --processing_template_decl;
18679
18680       /* Substitute into the template parameters to obtain the real
18681          innermost set of parameters.  This step is important if the
18682          innermost set of template parameters contains value
18683          parameters whose types depend on outer template parameters.  */
18684       TREE_VEC_LENGTH (partial_args)--;
18685       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18686
18687       pop_access_scope (decl);
18688     }
18689
18690   return fn_type;
18691 }
18692
18693 /* Return truthvalue if we're processing a template different from
18694    the last one involved in diagnostics.  */
18695 int
18696 problematic_instantiation_changed (void)
18697 {
18698   return current_tinst_level != last_error_tinst_level;
18699 }
18700
18701 /* Remember current template involved in diagnostics.  */
18702 void
18703 record_last_problematic_instantiation (void)
18704 {
18705   last_error_tinst_level = current_tinst_level;
18706 }
18707
18708 struct tinst_level *
18709 current_instantiation (void)
18710 {
18711   return current_tinst_level;
18712 }
18713
18714 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18715    type. Return zero for ok, nonzero for disallowed. Issue error and
18716    warning messages under control of COMPLAIN.  */
18717
18718 static int
18719 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18720 {
18721   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18722     return 0;
18723   else if (POINTER_TYPE_P (type))
18724     return 0;
18725   else if (TYPE_PTR_TO_MEMBER_P (type))
18726     return 0;
18727   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18728     return 0;
18729   else if (TREE_CODE (type) == TYPENAME_TYPE)
18730     return 0;
18731   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18732     return 0;
18733   else if (TREE_CODE (type) == NULLPTR_TYPE)
18734     return 0;
18735
18736   if (complain & tf_error)
18737     error ("%q#T is not a valid type for a template constant parameter", type);
18738   return 1;
18739 }
18740
18741 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18742    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18743
18744 static bool
18745 dependent_type_p_r (tree type)
18746 {
18747   tree scope;
18748
18749   /* [temp.dep.type]
18750
18751      A type is dependent if it is:
18752
18753      -- a template parameter. Template template parameters are types
18754         for us (since TYPE_P holds true for them) so we handle
18755         them here.  */
18756   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18757       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18758     return true;
18759   /* -- a qualified-id with a nested-name-specifier which contains a
18760         class-name that names a dependent type or whose unqualified-id
18761         names a dependent type.  */
18762   if (TREE_CODE (type) == TYPENAME_TYPE)
18763     return true;
18764   /* -- a cv-qualified type where the cv-unqualified type is
18765         dependent.  */
18766   type = TYPE_MAIN_VARIANT (type);
18767   /* -- a compound type constructed from any dependent type.  */
18768   if (TYPE_PTR_TO_MEMBER_P (type))
18769     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18770             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18771                                            (type)));
18772   else if (TREE_CODE (type) == POINTER_TYPE
18773            || TREE_CODE (type) == REFERENCE_TYPE)
18774     return dependent_type_p (TREE_TYPE (type));
18775   else if (TREE_CODE (type) == FUNCTION_TYPE
18776            || TREE_CODE (type) == METHOD_TYPE)
18777     {
18778       tree arg_type;
18779
18780       if (dependent_type_p (TREE_TYPE (type)))
18781         return true;
18782       for (arg_type = TYPE_ARG_TYPES (type);
18783            arg_type;
18784            arg_type = TREE_CHAIN (arg_type))
18785         if (dependent_type_p (TREE_VALUE (arg_type)))
18786           return true;
18787       return false;
18788     }
18789   /* -- an array type constructed from any dependent type or whose
18790         size is specified by a constant expression that is
18791         value-dependent.
18792
18793         We checked for type- and value-dependence of the bounds in
18794         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18795   if (TREE_CODE (type) == ARRAY_TYPE)
18796     {
18797       if (TYPE_DOMAIN (type)
18798           && dependent_type_p (TYPE_DOMAIN (type)))
18799         return true;
18800       return dependent_type_p (TREE_TYPE (type));
18801     }
18802
18803   /* -- a template-id in which either the template name is a template
18804      parameter ...  */
18805   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18806     return true;
18807   /* ... or any of the template arguments is a dependent type or
18808         an expression that is type-dependent or value-dependent.  */
18809   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18810            && (any_dependent_template_arguments_p
18811                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18812     return true;
18813
18814   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18815      dependent; if the argument of the `typeof' expression is not
18816      type-dependent, then it should already been have resolved.  */
18817   if (TREE_CODE (type) == TYPEOF_TYPE
18818       || TREE_CODE (type) == DECLTYPE_TYPE
18819       || TREE_CODE (type) == UNDERLYING_TYPE)
18820     return true;
18821
18822   /* A template argument pack is dependent if any of its packed
18823      arguments are.  */
18824   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18825     {
18826       tree args = ARGUMENT_PACK_ARGS (type);
18827       int i, len = TREE_VEC_LENGTH (args);
18828       for (i = 0; i < len; ++i)
18829         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18830           return true;
18831     }
18832
18833   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18834      be template parameters.  */
18835   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18836     return true;
18837
18838   /* The standard does not specifically mention types that are local
18839      to template functions or local classes, but they should be
18840      considered dependent too.  For example:
18841
18842        template <int I> void f() {
18843          enum E { a = I };
18844          S<sizeof (E)> s;
18845        }
18846
18847      The size of `E' cannot be known until the value of `I' has been
18848      determined.  Therefore, `E' must be considered dependent.  */
18849   scope = TYPE_CONTEXT (type);
18850   if (scope && TYPE_P (scope))
18851     return dependent_type_p (scope);
18852   /* Don't use type_dependent_expression_p here, as it can lead
18853      to infinite recursion trying to determine whether a lambda
18854      nested in a lambda is dependent (c++/47687).  */
18855   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18856            && DECL_LANG_SPECIFIC (scope)
18857            && DECL_TEMPLATE_INFO (scope)
18858            && (any_dependent_template_arguments_p
18859                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18860     return true;
18861
18862   /* Other types are non-dependent.  */
18863   return false;
18864 }
18865
18866 /* Returns TRUE if TYPE is dependent, in the sense of
18867    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18868
18869 bool
18870 dependent_type_p (tree type)
18871 {
18872   /* If there are no template parameters in scope, then there can't be
18873      any dependent types.  */
18874   if (!processing_template_decl)
18875     {
18876       /* If we are not processing a template, then nobody should be
18877          providing us with a dependent type.  */
18878       gcc_assert (type);
18879       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18880       return false;
18881     }
18882
18883   /* If the type is NULL, we have not computed a type for the entity
18884      in question; in that case, the type is dependent.  */
18885   if (!type)
18886     return true;
18887
18888   /* Erroneous types can be considered non-dependent.  */
18889   if (type == error_mark_node)
18890     return false;
18891
18892   /* If we have not already computed the appropriate value for TYPE,
18893      do so now.  */
18894   if (!TYPE_DEPENDENT_P_VALID (type))
18895     {
18896       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18897       TYPE_DEPENDENT_P_VALID (type) = 1;
18898     }
18899
18900   return TYPE_DEPENDENT_P (type);
18901 }
18902
18903 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18904    lookup.  In other words, a dependent type that is not the current
18905    instantiation.  */
18906
18907 bool
18908 dependent_scope_p (tree scope)
18909 {
18910   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18911           && !currently_open_class (scope));
18912 }
18913
18914 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18915    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18916    expression.  */
18917
18918 /* Note that this predicate is not appropriate for general expressions;
18919    only constant expressions (that satisfy potential_constant_expression)
18920    can be tested for value dependence.
18921
18922    We should really also have a predicate for "instantiation-dependent".
18923
18924    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18925      (what about instantiation-dependent constant-expressions?)
18926    is_late_template_attribute: defer if instantiation-dependent.
18927    compute_array_index_type: proceed if constant and not t- or v-dependent
18928      if instantiation-dependent, need to remember full expression
18929    uses_template_parms: FIXME - need to audit callers
18930    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18931    dependent_type_p [array_type]: dependent if index type is dependent
18932      (or non-constant?)
18933    static_assert - instantiation-dependent */
18934
18935 bool
18936 value_dependent_expression_p (tree expression)
18937 {
18938   if (!processing_template_decl)
18939     return false;
18940
18941   /* A name declared with a dependent type.  */
18942   if (DECL_P (expression) && type_dependent_expression_p (expression))
18943     return true;
18944
18945   switch (TREE_CODE (expression))
18946     {
18947     case IDENTIFIER_NODE:
18948       /* A name that has not been looked up -- must be dependent.  */
18949       return true;
18950
18951     case TEMPLATE_PARM_INDEX:
18952       /* A non-type template parm.  */
18953       return true;
18954
18955     case CONST_DECL:
18956       /* A non-type template parm.  */
18957       if (DECL_TEMPLATE_PARM_P (expression))
18958         return true;
18959       return value_dependent_expression_p (DECL_INITIAL (expression));
18960
18961     case VAR_DECL:
18962        /* A constant with literal type and is initialized
18963           with an expression that is value-dependent.  */
18964       if (DECL_INITIAL (expression)
18965           && decl_constant_var_p (expression)
18966           && value_dependent_expression_p (DECL_INITIAL (expression)))
18967         return true;
18968       return false;
18969
18970     case DYNAMIC_CAST_EXPR:
18971     case STATIC_CAST_EXPR:
18972     case CONST_CAST_EXPR:
18973     case REINTERPRET_CAST_EXPR:
18974     case CAST_EXPR:
18975       /* These expressions are value-dependent if the type to which
18976          the cast occurs is dependent or the expression being casted
18977          is value-dependent.  */
18978       {
18979         tree type = TREE_TYPE (expression);
18980
18981         if (dependent_type_p (type))
18982           return true;
18983
18984         /* A functional cast has a list of operands.  */
18985         expression = TREE_OPERAND (expression, 0);
18986         if (!expression)
18987           {
18988             /* If there are no operands, it must be an expression such
18989                as "int()". This should not happen for aggregate types
18990                because it would form non-constant expressions.  */
18991             gcc_assert (cxx_dialect >= cxx0x
18992                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18993
18994             return false;
18995           }
18996
18997         if (TREE_CODE (expression) == TREE_LIST)
18998           return any_value_dependent_elements_p (expression);
18999
19000         return value_dependent_expression_p (expression);
19001       }
19002
19003     case SIZEOF_EXPR:
19004     case ALIGNOF_EXPR:
19005     case TYPEID_EXPR:
19006       /* A `sizeof' expression is value-dependent if the operand is
19007          type-dependent or is a pack expansion.  */
19008       expression = TREE_OPERAND (expression, 0);
19009       if (PACK_EXPANSION_P (expression))
19010         return true;
19011       else if (TYPE_P (expression))
19012         return dependent_type_p (expression);
19013       return type_dependent_expression_p (expression);
19014
19015     case AT_ENCODE_EXPR:
19016       /* An 'encode' expression is value-dependent if the operand is
19017          type-dependent.  */
19018       expression = TREE_OPERAND (expression, 0);
19019       return dependent_type_p (expression);
19020
19021     case NOEXCEPT_EXPR:
19022       expression = TREE_OPERAND (expression, 0);
19023       return type_dependent_expression_p (expression);
19024
19025     case SCOPE_REF:
19026       {
19027         tree name = TREE_OPERAND (expression, 1);
19028         return value_dependent_expression_p (name);
19029       }
19030
19031     case COMPONENT_REF:
19032       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19033               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19034
19035     case NONTYPE_ARGUMENT_PACK:
19036       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19037          is value-dependent.  */
19038       {
19039         tree values = ARGUMENT_PACK_ARGS (expression);
19040         int i, len = TREE_VEC_LENGTH (values);
19041         
19042         for (i = 0; i < len; ++i)
19043           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19044             return true;
19045         
19046         return false;
19047       }
19048
19049     case TRAIT_EXPR:
19050       {
19051         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19052         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19053                 || (type2 ? dependent_type_p (type2) : false));
19054       }
19055
19056     case MODOP_EXPR:
19057       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19058               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19059
19060     case ARRAY_REF:
19061       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19062               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19063
19064     case ADDR_EXPR:
19065       {
19066         tree op = TREE_OPERAND (expression, 0);
19067         return (value_dependent_expression_p (op)
19068                 || has_value_dependent_address (op));
19069       }
19070
19071     case CALL_EXPR:
19072       {
19073         tree fn = get_callee_fndecl (expression);
19074         int i, nargs;
19075         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19076           return true;
19077         nargs = call_expr_nargs (expression);
19078         for (i = 0; i < nargs; ++i)
19079           {
19080             tree op = CALL_EXPR_ARG (expression, i);
19081             /* In a call to a constexpr member function, look through the
19082                implicit ADDR_EXPR on the object argument so that it doesn't
19083                cause the call to be considered value-dependent.  We also
19084                look through it in potential_constant_expression.  */
19085             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19086                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19087                 && TREE_CODE (op) == ADDR_EXPR)
19088               op = TREE_OPERAND (op, 0);
19089             if (value_dependent_expression_p (op))
19090               return true;
19091           }
19092         return false;
19093       }
19094
19095     case TEMPLATE_ID_EXPR:
19096       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19097          type-dependent.  */
19098       return type_dependent_expression_p (expression);
19099
19100     case CONSTRUCTOR:
19101       {
19102         unsigned ix;
19103         tree val;
19104         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19105           if (value_dependent_expression_p (val))
19106             return true;
19107         return false;
19108       }
19109
19110     default:
19111       /* A constant expression is value-dependent if any subexpression is
19112          value-dependent.  */
19113       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19114         {
19115         case tcc_reference:
19116         case tcc_unary:
19117         case tcc_comparison:
19118         case tcc_binary:
19119         case tcc_expression:
19120         case tcc_vl_exp:
19121           {
19122             int i, len = cp_tree_operand_length (expression);
19123
19124             for (i = 0; i < len; i++)
19125               {
19126                 tree t = TREE_OPERAND (expression, i);
19127
19128                 /* In some cases, some of the operands may be missing.l
19129                    (For example, in the case of PREDECREMENT_EXPR, the
19130                    amount to increment by may be missing.)  That doesn't
19131                    make the expression dependent.  */
19132                 if (t && value_dependent_expression_p (t))
19133                   return true;
19134               }
19135           }
19136           break;
19137         default:
19138           break;
19139         }
19140       break;
19141     }
19142
19143   /* The expression is not value-dependent.  */
19144   return false;
19145 }
19146
19147 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19148    [temp.dep.expr].  Note that an expression with no type is
19149    considered dependent.  Other parts of the compiler arrange for an
19150    expression with type-dependent subexpressions to have no type, so
19151    this function doesn't have to be fully recursive.  */
19152
19153 bool
19154 type_dependent_expression_p (tree expression)
19155 {
19156   if (!processing_template_decl)
19157     return false;
19158
19159   if (expression == error_mark_node)
19160     return false;
19161
19162   /* An unresolved name is always dependent.  */
19163   if (TREE_CODE (expression) == IDENTIFIER_NODE
19164       || TREE_CODE (expression) == USING_DECL)
19165     return true;
19166
19167   /* Some expression forms are never type-dependent.  */
19168   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19169       || TREE_CODE (expression) == SIZEOF_EXPR
19170       || TREE_CODE (expression) == ALIGNOF_EXPR
19171       || TREE_CODE (expression) == AT_ENCODE_EXPR
19172       || TREE_CODE (expression) == NOEXCEPT_EXPR
19173       || TREE_CODE (expression) == TRAIT_EXPR
19174       || TREE_CODE (expression) == TYPEID_EXPR
19175       || TREE_CODE (expression) == DELETE_EXPR
19176       || TREE_CODE (expression) == VEC_DELETE_EXPR
19177       || TREE_CODE (expression) == THROW_EXPR)
19178     return false;
19179
19180   /* The types of these expressions depends only on the type to which
19181      the cast occurs.  */
19182   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19183       || TREE_CODE (expression) == STATIC_CAST_EXPR
19184       || TREE_CODE (expression) == CONST_CAST_EXPR
19185       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19186       || TREE_CODE (expression) == CAST_EXPR)
19187     return dependent_type_p (TREE_TYPE (expression));
19188
19189   /* The types of these expressions depends only on the type created
19190      by the expression.  */
19191   if (TREE_CODE (expression) == NEW_EXPR
19192       || TREE_CODE (expression) == VEC_NEW_EXPR)
19193     {
19194       /* For NEW_EXPR tree nodes created inside a template, either
19195          the object type itself or a TREE_LIST may appear as the
19196          operand 1.  */
19197       tree type = TREE_OPERAND (expression, 1);
19198       if (TREE_CODE (type) == TREE_LIST)
19199         /* This is an array type.  We need to check array dimensions
19200            as well.  */
19201         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19202                || value_dependent_expression_p
19203                     (TREE_OPERAND (TREE_VALUE (type), 1));
19204       else
19205         return dependent_type_p (type);
19206     }
19207
19208   if (TREE_CODE (expression) == SCOPE_REF)
19209     {
19210       tree scope = TREE_OPERAND (expression, 0);
19211       tree name = TREE_OPERAND (expression, 1);
19212
19213       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19214          contains an identifier associated by name lookup with one or more
19215          declarations declared with a dependent type, or...a
19216          nested-name-specifier or qualified-id that names a member of an
19217          unknown specialization.  */
19218       return (type_dependent_expression_p (name)
19219               || dependent_scope_p (scope));
19220     }
19221
19222   if (TREE_CODE (expression) == FUNCTION_DECL
19223       && DECL_LANG_SPECIFIC (expression)
19224       && DECL_TEMPLATE_INFO (expression)
19225       && (any_dependent_template_arguments_p
19226           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19227     return true;
19228
19229   if (TREE_CODE (expression) == TEMPLATE_DECL
19230       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19231     return false;
19232
19233   if (TREE_CODE (expression) == STMT_EXPR)
19234     expression = stmt_expr_value_expr (expression);
19235
19236   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19237     {
19238       tree elt;
19239       unsigned i;
19240
19241       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19242         {
19243           if (type_dependent_expression_p (elt))
19244             return true;
19245         }
19246       return false;
19247     }
19248
19249   /* A static data member of the current instantiation with incomplete
19250      array type is type-dependent, as the definition and specializations
19251      can have different bounds.  */
19252   if (TREE_CODE (expression) == VAR_DECL
19253       && DECL_CLASS_SCOPE_P (expression)
19254       && dependent_type_p (DECL_CONTEXT (expression))
19255       && VAR_HAD_UNKNOWN_BOUND (expression))
19256     return true;
19257
19258   if (TREE_TYPE (expression) == unknown_type_node)
19259     {
19260       if (TREE_CODE (expression) == ADDR_EXPR)
19261         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19262       if (TREE_CODE (expression) == COMPONENT_REF
19263           || TREE_CODE (expression) == OFFSET_REF)
19264         {
19265           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19266             return true;
19267           expression = TREE_OPERAND (expression, 1);
19268           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19269             return false;
19270         }
19271       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19272       if (TREE_CODE (expression) == SCOPE_REF)
19273         return false;
19274
19275       if (TREE_CODE (expression) == BASELINK)
19276         expression = BASELINK_FUNCTIONS (expression);
19277
19278       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19279         {
19280           if (any_dependent_template_arguments_p
19281               (TREE_OPERAND (expression, 1)))
19282             return true;
19283           expression = TREE_OPERAND (expression, 0);
19284         }
19285       gcc_assert (TREE_CODE (expression) == OVERLOAD
19286                   || TREE_CODE (expression) == FUNCTION_DECL);
19287
19288       while (expression)
19289         {
19290           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19291             return true;
19292           expression = OVL_NEXT (expression);
19293         }
19294       return false;
19295     }
19296
19297   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19298
19299   return (dependent_type_p (TREE_TYPE (expression)));
19300 }
19301
19302 /* Like type_dependent_expression_p, but it also works while not processing
19303    a template definition, i.e. during substitution or mangling.  */
19304
19305 bool
19306 type_dependent_expression_p_push (tree expr)
19307 {
19308   bool b;
19309   ++processing_template_decl;
19310   b = type_dependent_expression_p (expr);
19311   --processing_template_decl;
19312   return b;
19313 }
19314
19315 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19316
19317 bool
19318 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19319 {
19320   unsigned int i;
19321   tree arg;
19322
19323   FOR_EACH_VEC_ELT (tree, args, i, arg)
19324     {
19325       if (type_dependent_expression_p (arg))
19326         return true;
19327     }
19328   return false;
19329 }
19330
19331 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19332    expressions) contains any type-dependent expressions.  */
19333
19334 bool
19335 any_type_dependent_elements_p (const_tree list)
19336 {
19337   for (; list; list = TREE_CHAIN (list))
19338     if (value_dependent_expression_p (TREE_VALUE (list)))
19339       return true;
19340
19341   return false;
19342 }
19343
19344 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19345    expressions) contains any value-dependent expressions.  */
19346
19347 bool
19348 any_value_dependent_elements_p (const_tree list)
19349 {
19350   for (; list; list = TREE_CHAIN (list))
19351     if (value_dependent_expression_p (TREE_VALUE (list)))
19352       return true;
19353
19354   return false;
19355 }
19356
19357 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19358
19359 bool
19360 dependent_template_arg_p (tree arg)
19361 {
19362   if (!processing_template_decl)
19363     return false;
19364
19365   /* Assume a template argument that was wrongly written by the user
19366      is dependent. This is consistent with what
19367      any_dependent_template_arguments_p [that calls this function]
19368      does.  */
19369   if (!arg || arg == error_mark_node)
19370     return true;
19371
19372   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19373     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19374
19375   if (TREE_CODE (arg) == TEMPLATE_DECL
19376       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19377     return dependent_template_p (arg);
19378   else if (ARGUMENT_PACK_P (arg))
19379     {
19380       tree args = ARGUMENT_PACK_ARGS (arg);
19381       int i, len = TREE_VEC_LENGTH (args);
19382       for (i = 0; i < len; ++i)
19383         {
19384           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19385             return true;
19386         }
19387
19388       return false;
19389     }
19390   else if (TYPE_P (arg))
19391     return dependent_type_p (arg);
19392   else
19393     return (type_dependent_expression_p (arg)
19394             || value_dependent_expression_p (arg));
19395 }
19396
19397 /* Returns true if ARGS (a collection of template arguments) contains
19398    any types that require structural equality testing.  */
19399
19400 bool
19401 any_template_arguments_need_structural_equality_p (tree args)
19402 {
19403   int i;
19404   int j;
19405
19406   if (!args)
19407     return false;
19408   if (args == error_mark_node)
19409     return true;
19410
19411   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19412     {
19413       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19414       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19415         {
19416           tree arg = TREE_VEC_ELT (level, j);
19417           tree packed_args = NULL_TREE;
19418           int k, len = 1;
19419
19420           if (ARGUMENT_PACK_P (arg))
19421             {
19422               /* Look inside the argument pack.  */
19423               packed_args = ARGUMENT_PACK_ARGS (arg);
19424               len = TREE_VEC_LENGTH (packed_args);
19425             }
19426
19427           for (k = 0; k < len; ++k)
19428             {
19429               if (packed_args)
19430                 arg = TREE_VEC_ELT (packed_args, k);
19431
19432               if (error_operand_p (arg))
19433                 return true;
19434               else if (TREE_CODE (arg) == TEMPLATE_DECL
19435                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19436                 continue;
19437               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19438                 return true;
19439               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19440                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19441                 return true;
19442             }
19443         }
19444     }
19445
19446   return false;
19447 }
19448
19449 /* Returns true if ARGS (a collection of template arguments) contains
19450    any dependent arguments.  */
19451
19452 bool
19453 any_dependent_template_arguments_p (const_tree args)
19454 {
19455   int i;
19456   int j;
19457
19458   if (!args)
19459     return false;
19460   if (args == error_mark_node)
19461     return true;
19462
19463   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19464     {
19465       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19466       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19467         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19468           return true;
19469     }
19470
19471   return false;
19472 }
19473
19474 /* Returns TRUE if the template TMPL is dependent.  */
19475
19476 bool
19477 dependent_template_p (tree tmpl)
19478 {
19479   if (TREE_CODE (tmpl) == OVERLOAD)
19480     {
19481       while (tmpl)
19482         {
19483           if (dependent_template_p (OVL_CURRENT (tmpl)))
19484             return true;
19485           tmpl = OVL_NEXT (tmpl);
19486         }
19487       return false;
19488     }
19489
19490   /* Template template parameters are dependent.  */
19491   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19492       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19493     return true;
19494   /* So are names that have not been looked up.  */
19495   if (TREE_CODE (tmpl) == SCOPE_REF
19496       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19497     return true;
19498   /* So are member templates of dependent classes.  */
19499   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19500     return dependent_type_p (DECL_CONTEXT (tmpl));
19501   return false;
19502 }
19503
19504 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19505
19506 bool
19507 dependent_template_id_p (tree tmpl, tree args)
19508 {
19509   return (dependent_template_p (tmpl)
19510           || any_dependent_template_arguments_p (args));
19511 }
19512
19513 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19514    is dependent.  */
19515
19516 bool
19517 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19518 {
19519   int i;
19520
19521   if (!processing_template_decl)
19522     return false;
19523
19524   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19525     {
19526       tree decl = TREE_VEC_ELT (declv, i);
19527       tree init = TREE_VEC_ELT (initv, i);
19528       tree cond = TREE_VEC_ELT (condv, i);
19529       tree incr = TREE_VEC_ELT (incrv, i);
19530
19531       if (type_dependent_expression_p (decl))
19532         return true;
19533
19534       if (init && type_dependent_expression_p (init))
19535         return true;
19536
19537       if (type_dependent_expression_p (cond))
19538         return true;
19539
19540       if (COMPARISON_CLASS_P (cond)
19541           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19542               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19543         return true;
19544
19545       if (TREE_CODE (incr) == MODOP_EXPR)
19546         {
19547           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19548               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19549             return true;
19550         }
19551       else if (type_dependent_expression_p (incr))
19552         return true;
19553       else if (TREE_CODE (incr) == MODIFY_EXPR)
19554         {
19555           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19556             return true;
19557           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19558             {
19559               tree t = TREE_OPERAND (incr, 1);
19560               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19561                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19562                 return true;
19563             }
19564         }
19565     }
19566
19567   return false;
19568 }
19569
19570 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19571    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19572    no such TYPE can be found.  Note that this function peers inside
19573    uninstantiated templates and therefore should be used only in
19574    extremely limited situations.  ONLY_CURRENT_P restricts this
19575    peering to the currently open classes hierarchy (which is required
19576    when comparing types).  */
19577
19578 tree
19579 resolve_typename_type (tree type, bool only_current_p)
19580 {
19581   tree scope;
19582   tree name;
19583   tree decl;
19584   int quals;
19585   tree pushed_scope;
19586   tree result;
19587
19588   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19589
19590   scope = TYPE_CONTEXT (type);
19591   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19592      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19593      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19594      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19595      identifier  of the TYPENAME_TYPE anymore.
19596      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19597      TYPENAME_TYPE instead, we avoid messing up with a possible
19598      typedef variant case.  */
19599   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19600
19601   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19602      it first before we can figure out what NAME refers to.  */
19603   if (TREE_CODE (scope) == TYPENAME_TYPE)
19604     scope = resolve_typename_type (scope, only_current_p);
19605   /* If we don't know what SCOPE refers to, then we cannot resolve the
19606      TYPENAME_TYPE.  */
19607   if (TREE_CODE (scope) == TYPENAME_TYPE)
19608     return type;
19609   /* If the SCOPE is a template type parameter, we have no way of
19610      resolving the name.  */
19611   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19612     return type;
19613   /* If the SCOPE is not the current instantiation, there's no reason
19614      to look inside it.  */
19615   if (only_current_p && !currently_open_class (scope))
19616     return type;
19617   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19618   if (typedef_variant_p (type))
19619     return type;
19620   /* If SCOPE isn't the template itself, it will not have a valid
19621      TYPE_FIELDS list.  */
19622   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19623     /* scope is either the template itself or a compatible instantiation
19624        like X<T>, so look up the name in the original template.  */
19625     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19626   else
19627     /* scope is a partial instantiation, so we can't do the lookup or we
19628        will lose the template arguments.  */
19629     return type;
19630   /* Enter the SCOPE so that name lookup will be resolved as if we
19631      were in the class definition.  In particular, SCOPE will no
19632      longer be considered a dependent type.  */
19633   pushed_scope = push_scope (scope);
19634   /* Look up the declaration.  */
19635   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19636
19637   result = NULL_TREE;
19638   
19639   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19640      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19641   if (!decl)
19642     /*nop*/;
19643   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19644            && TREE_CODE (decl) == TYPE_DECL)
19645     {
19646       result = TREE_TYPE (decl);
19647       if (result == error_mark_node)
19648         result = NULL_TREE;
19649     }
19650   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19651            && DECL_CLASS_TEMPLATE_P (decl))
19652     {
19653       tree tmpl;
19654       tree args;
19655       /* Obtain the template and the arguments.  */
19656       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19657       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19658       /* Instantiate the template.  */
19659       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19660                                       /*entering_scope=*/0,
19661                                       tf_error | tf_user);
19662       if (result == error_mark_node)
19663         result = NULL_TREE;
19664     }
19665   
19666   /* Leave the SCOPE.  */
19667   if (pushed_scope)
19668     pop_scope (pushed_scope);
19669
19670   /* If we failed to resolve it, return the original typename.  */
19671   if (!result)
19672     return type;
19673   
19674   /* If lookup found a typename type, resolve that too.  */
19675   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19676     {
19677       /* Ill-formed programs can cause infinite recursion here, so we
19678          must catch that.  */
19679       TYPENAME_IS_RESOLVING_P (type) = 1;
19680       result = resolve_typename_type (result, only_current_p);
19681       TYPENAME_IS_RESOLVING_P (type) = 0;
19682     }
19683   
19684   /* Qualify the resulting type.  */
19685   quals = cp_type_quals (type);
19686   if (quals)
19687     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19688
19689   return result;
19690 }
19691
19692 /* EXPR is an expression which is not type-dependent.  Return a proxy
19693    for EXPR that can be used to compute the types of larger
19694    expressions containing EXPR.  */
19695
19696 tree
19697 build_non_dependent_expr (tree expr)
19698 {
19699   tree inner_expr;
19700
19701 #ifdef ENABLE_CHECKING
19702   /* Try to get a constant value for all non-type-dependent expressions in
19703       order to expose bugs in *_dependent_expression_p and constexpr.  */
19704   if (cxx_dialect >= cxx0x)
19705     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19706 #endif
19707
19708   /* Preserve OVERLOADs; the functions must be available to resolve
19709      types.  */
19710   inner_expr = expr;
19711   if (TREE_CODE (inner_expr) == STMT_EXPR)
19712     inner_expr = stmt_expr_value_expr (inner_expr);
19713   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19714     inner_expr = TREE_OPERAND (inner_expr, 0);
19715   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19716     inner_expr = TREE_OPERAND (inner_expr, 1);
19717   if (is_overloaded_fn (inner_expr)
19718       || TREE_CODE (inner_expr) == OFFSET_REF)
19719     return expr;
19720   /* There is no need to return a proxy for a variable.  */
19721   if (TREE_CODE (expr) == VAR_DECL)
19722     return expr;
19723   /* Preserve string constants; conversions from string constants to
19724      "char *" are allowed, even though normally a "const char *"
19725      cannot be used to initialize a "char *".  */
19726   if (TREE_CODE (expr) == STRING_CST)
19727     return expr;
19728   /* Preserve arithmetic constants, as an optimization -- there is no
19729      reason to create a new node.  */
19730   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19731     return expr;
19732   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19733      There is at least one place where we want to know that a
19734      particular expression is a throw-expression: when checking a ?:
19735      expression, there are special rules if the second or third
19736      argument is a throw-expression.  */
19737   if (TREE_CODE (expr) == THROW_EXPR)
19738     return expr;
19739
19740   /* Don't wrap an initializer list, we need to be able to look inside.  */
19741   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19742     return expr;
19743
19744   if (TREE_CODE (expr) == COND_EXPR)
19745     return build3 (COND_EXPR,
19746                    TREE_TYPE (expr),
19747                    TREE_OPERAND (expr, 0),
19748                    (TREE_OPERAND (expr, 1)
19749                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19750                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19751                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19752   if (TREE_CODE (expr) == COMPOUND_EXPR
19753       && !COMPOUND_EXPR_OVERLOADED (expr))
19754     return build2 (COMPOUND_EXPR,
19755                    TREE_TYPE (expr),
19756                    TREE_OPERAND (expr, 0),
19757                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19758
19759   /* If the type is unknown, it can't really be non-dependent */
19760   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19761
19762   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19763   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19764 }
19765
19766 /* ARGS is a vector of expressions as arguments to a function call.
19767    Replace the arguments with equivalent non-dependent expressions.
19768    This modifies ARGS in place.  */
19769
19770 void
19771 make_args_non_dependent (VEC(tree,gc) *args)
19772 {
19773   unsigned int ix;
19774   tree arg;
19775
19776   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19777     {
19778       tree newarg = build_non_dependent_expr (arg);
19779       if (newarg != arg)
19780         VEC_replace (tree, args, ix, newarg);
19781     }
19782 }
19783
19784 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19785    with a level one deeper than the actual template parms.  */
19786
19787 tree
19788 make_auto (void)
19789 {
19790   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19791   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19792                                TYPE_DECL, get_identifier ("auto"), au);
19793   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19794   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19795     (0, processing_template_decl + 1, processing_template_decl + 1,
19796      0, TYPE_NAME (au), NULL_TREE);
19797   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19798   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19799   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19800
19801   return au;
19802 }
19803
19804 /* Given type ARG, return std::initializer_list<ARG>.  */
19805
19806 static tree
19807 listify (tree arg)
19808 {
19809   tree std_init_list = namespace_binding
19810     (get_identifier ("initializer_list"), std_node);
19811   tree argvec;
19812   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19813     {    
19814       error ("deducing from brace-enclosed initializer list requires "
19815              "#include <initializer_list>");
19816       return error_mark_node;
19817     }
19818   argvec = make_tree_vec (1);
19819   TREE_VEC_ELT (argvec, 0) = arg;
19820   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19821                                 NULL_TREE, 0, tf_warning_or_error);
19822 }
19823
19824 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19825
19826 static tree
19827 listify_autos (tree type, tree auto_node)
19828 {
19829   tree init_auto = listify (auto_node);
19830   tree argvec = make_tree_vec (1);
19831   TREE_VEC_ELT (argvec, 0) = init_auto;
19832   if (processing_template_decl)
19833     argvec = add_to_template_args (current_template_args (), argvec);
19834   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19835 }
19836
19837 /* walk_tree helper for do_auto_deduction.  */
19838
19839 static tree
19840 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19841                  void *type)
19842 {
19843   /* Is this a variable with the type we're looking for?  */
19844   if (DECL_P (*tp)
19845       && TREE_TYPE (*tp) == type)
19846     return *tp;
19847   else
19848     return NULL_TREE;
19849 }
19850
19851 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19852    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19853
19854 tree
19855 do_auto_deduction (tree type, tree init, tree auto_node)
19856 {
19857   tree parms, tparms, targs;
19858   tree args[1];
19859   tree decl;
19860   int val;
19861
19862   if (processing_template_decl
19863       && (TREE_TYPE (init) == NULL_TREE
19864           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19865     /* Not enough information to try this yet.  */
19866     return type;
19867
19868   /* The name of the object being declared shall not appear in the
19869      initializer expression.  */
19870   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19871   if (decl)
19872     {
19873       error ("variable %q#D with %<auto%> type used in its own "
19874              "initializer", decl);
19875       return error_mark_node;
19876     }
19877
19878   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19879      with either a new invented type template parameter U or, if the
19880      initializer is a braced-init-list (8.5.4), with
19881      std::initializer_list<U>.  */
19882   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19883     type = listify_autos (type, auto_node);
19884
19885   init = resolve_nondeduced_context (init);
19886
19887   parms = build_tree_list (NULL_TREE, type);
19888   args[0] = init;
19889   tparms = make_tree_vec (1);
19890   targs = make_tree_vec (1);
19891   TREE_VEC_ELT (tparms, 0)
19892     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19893   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19894                                DEDUCE_CALL, LOOKUP_NORMAL,
19895                                /*explain_p=*/false);
19896   if (val > 0)
19897     {
19898       if (processing_template_decl)
19899         /* Try again at instantiation time.  */
19900         return type;
19901       if (type && type != error_mark_node)
19902         /* If type is error_mark_node a diagnostic must have been
19903            emitted by now.  Also, having a mention to '<type error>'
19904            in the diagnostic is not really useful to the user.  */
19905         error ("unable to deduce %qT from %qE", type, init);
19906       return error_mark_node;
19907     }
19908
19909   /* If the list of declarators contains more than one declarator, the type
19910      of each declared variable is determined as described above. If the
19911      type deduced for the template parameter U is not the same in each
19912      deduction, the program is ill-formed.  */
19913   if (TREE_TYPE (auto_node)
19914       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19915     {
19916       error ("inconsistent deduction for %qT: %qT and then %qT",
19917              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19918       return error_mark_node;
19919     }
19920   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19921
19922   if (processing_template_decl)
19923     targs = add_to_template_args (current_template_args (), targs);
19924   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19925 }
19926
19927 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19928    result.  */
19929
19930 tree
19931 splice_late_return_type (tree type, tree late_return_type)
19932 {
19933   tree argvec;
19934
19935   if (late_return_type == NULL_TREE)
19936     return type;
19937   argvec = make_tree_vec (1);
19938   TREE_VEC_ELT (argvec, 0) = late_return_type;
19939   if (processing_template_parmlist)
19940     /* For a late-specified return type in a template type-parameter, we
19941        need to add a dummy argument level for its parmlist.  */
19942     argvec = add_to_template_args
19943       (make_tree_vec (processing_template_parmlist), argvec);
19944   if (current_template_parms)
19945     argvec = add_to_template_args (current_template_args (), argvec);
19946   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19947 }
19948
19949 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19950
19951 bool
19952 is_auto (const_tree type)
19953 {
19954   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19955       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19956     return true;
19957   else
19958     return false;
19959 }
19960
19961 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19962    appear as a type-specifier for the declaration in question, we don't
19963    have to look through the whole type.  */
19964
19965 tree
19966 type_uses_auto (tree type)
19967 {
19968   enum tree_code code;
19969   if (is_auto (type))
19970     return type;
19971
19972   code = TREE_CODE (type);
19973
19974   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19975       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19976       || code == METHOD_TYPE || code == ARRAY_TYPE)
19977     return type_uses_auto (TREE_TYPE (type));
19978
19979   if (TYPE_PTRMEMFUNC_P (type))
19980     return type_uses_auto (TREE_TYPE (TREE_TYPE
19981                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19982
19983   return NULL_TREE;
19984 }
19985
19986 /* For a given template T, return the vector of typedefs referenced
19987    in T for which access check is needed at T instantiation time.
19988    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19989    Those typedefs were added to T by the function
19990    append_type_to_template_for_access_check.  */
19991
19992 VEC(qualified_typedef_usage_t,gc)*
19993 get_types_needing_access_check (tree t)
19994 {
19995   tree ti;
19996   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19997
19998   if (!t || t == error_mark_node)
19999     return NULL;
20000
20001   if (!(ti = get_template_info (t)))
20002     return NULL;
20003
20004   if (CLASS_TYPE_P (t)
20005       || TREE_CODE (t) == FUNCTION_DECL)
20006     {
20007       if (!TI_TEMPLATE (ti))
20008         return NULL;
20009
20010       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20011     }
20012
20013   return result;
20014 }
20015
20016 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20017    tied to T. That list of typedefs will be access checked at
20018    T instantiation time.
20019    T is either a FUNCTION_DECL or a RECORD_TYPE.
20020    TYPE_DECL is a TYPE_DECL node representing a typedef.
20021    SCOPE is the scope through which TYPE_DECL is accessed.
20022    LOCATION is the location of the usage point of TYPE_DECL.
20023
20024    This function is a subroutine of
20025    append_type_to_template_for_access_check.  */
20026
20027 static void
20028 append_type_to_template_for_access_check_1 (tree t,
20029                                             tree type_decl,
20030                                             tree scope,
20031                                             location_t location)
20032 {
20033   qualified_typedef_usage_t typedef_usage;
20034   tree ti;
20035
20036   if (!t || t == error_mark_node)
20037     return;
20038
20039   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20040                || CLASS_TYPE_P (t))
20041               && type_decl
20042               && TREE_CODE (type_decl) == TYPE_DECL
20043               && scope);
20044
20045   if (!(ti = get_template_info (t)))
20046     return;
20047
20048   gcc_assert (TI_TEMPLATE (ti));
20049
20050   typedef_usage.typedef_decl = type_decl;
20051   typedef_usage.context = scope;
20052   typedef_usage.locus = location;
20053
20054   VEC_safe_push (qualified_typedef_usage_t, gc,
20055                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20056                  &typedef_usage);
20057 }
20058
20059 /* Append TYPE_DECL to the template TEMPL.
20060    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20061    At TEMPL instanciation time, TYPE_DECL will be checked to see
20062    if it can be accessed through SCOPE.
20063    LOCATION is the location of the usage point of TYPE_DECL.
20064
20065    e.g. consider the following code snippet:
20066
20067      class C
20068      {
20069        typedef int myint;
20070      };
20071
20072      template<class U> struct S
20073      {
20074        C::myint mi; // <-- usage point of the typedef C::myint
20075      };
20076
20077      S<char> s;
20078
20079    At S<char> instantiation time, we need to check the access of C::myint
20080    In other words, we need to check the access of the myint typedef through
20081    the C scope. For that purpose, this function will add the myint typedef
20082    and the scope C through which its being accessed to a list of typedefs
20083    tied to the template S. That list will be walked at template instantiation
20084    time and access check performed on each typedefs it contains.
20085    Note that this particular code snippet should yield an error because
20086    myint is private to C.  */
20087
20088 void
20089 append_type_to_template_for_access_check (tree templ,
20090                                           tree type_decl,
20091                                           tree scope,
20092                                           location_t location)
20093 {
20094   qualified_typedef_usage_t *iter;
20095   int i;
20096
20097   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20098
20099   /* Make sure we don't append the type to the template twice.  */
20100   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20101                     get_types_needing_access_check (templ),
20102                     i, iter)
20103     if (iter->typedef_decl == type_decl && scope == iter->context)
20104       return;
20105
20106   append_type_to_template_for_access_check_1 (templ, type_decl,
20107                                               scope, location);
20108 }
20109
20110 /* Set up the hash tables for template instantiations.  */
20111
20112 void
20113 init_template_processing (void)
20114 {
20115   decl_specializations = htab_create_ggc (37,
20116                                           hash_specialization,
20117                                           eq_specializations,
20118                                           ggc_free);
20119   type_specializations = htab_create_ggc (37,
20120                                           hash_specialization,
20121                                           eq_specializations,
20122                                           ggc_free);
20123 }
20124
20125 /* Print stats about the template hash tables for -fstats.  */
20126
20127 void
20128 print_template_statistics (void)
20129 {
20130   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20131            "%f collisions\n", (long) htab_size (decl_specializations),
20132            (long) htab_elements (decl_specializations),
20133            htab_collisions (decl_specializations));
20134   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20135            "%f collisions\n", (long) htab_size (type_specializations),
20136            (long) htab_elements (type_specializations),
20137            htab_collisions (type_specializations));
20138 }
20139
20140 #include "gt-cp-pt.h"