OSDN Git Service

2011-10-28 Paolo Carlini <paolo.carlini@oracle.com>
[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, unification_kind_t, 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 *entry;
896                   void **slot;
897
898                   elt.tmpl = most_general_template (tmpl);
899                   elt.args = CLASSTYPE_TI_ARGS (inst);
900                   elt.spec = inst;
901
902                   htab_remove_elt (type_specializations, &elt);
903
904                   elt.tmpl = tmpl;
905                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
906
907                   slot = htab_find_slot (type_specializations, &elt, INSERT);
908                   entry = ggc_alloc_spec_entry ();
909                   *entry = elt;
910                   *slot = entry;
911                 }
912               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
913                 /* But if we've had an implicit instantiation, that's a
914                    problem ([temp.expl.spec]/6).  */
915                 error ("specialization %qT after instantiation %qT",
916                        type, inst);
917             }
918
919           /* Mark TYPE as a specialization.  And as a result, we only
920              have one level of template argument for the innermost
921              class template.  */
922           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
923           CLASSTYPE_TI_ARGS (type)
924             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
925         }
926     }
927   else if (processing_specialization)
928     {
929        /* Someday C++0x may allow for enum template specialization.  */
930       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
931           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
932         pedwarn (input_location, OPT_pedantic, "template specialization "
933                  "of %qD not allowed by ISO C++", type);
934       else
935         {
936           error ("explicit specialization of non-template %qT", type);
937           return error_mark_node;
938         }
939     }
940
941   return type;
942 }
943
944 /* Returns nonzero if we can optimize the retrieval of specializations
945    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
946    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
947
948 static inline bool
949 optimize_specialization_lookup_p (tree tmpl)
950 {
951   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
952           && DECL_CLASS_SCOPE_P (tmpl)
953           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
954              parameter.  */
955           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
956           /* The optimized lookup depends on the fact that the
957              template arguments for the member function template apply
958              purely to the containing class, which is not true if the
959              containing class is an explicit or partial
960              specialization.  */
961           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
962           && !DECL_MEMBER_TEMPLATE_P (tmpl)
963           && !DECL_CONV_FN_P (tmpl)
964           /* It is possible to have a template that is not a member
965              template and is not a member of a template class:
966
967              template <typename T>
968              struct S { friend A::f(); };
969
970              Here, the friend function is a template, but the context does
971              not have template information.  The optimized lookup relies
972              on having ARGS be the template arguments for both the class
973              and the function template.  */
974           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
975 }
976
977 /* Retrieve the specialization (in the sense of [temp.spec] - a
978    specialization is either an instantiation or an explicit
979    specialization) of TMPL for the given template ARGS.  If there is
980    no such specialization, return NULL_TREE.  The ARGS are a vector of
981    arguments, or a vector of vectors of arguments, in the case of
982    templates with more than one level of parameters.
983
984    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
985    then we search for a partial specialization matching ARGS.  This
986    parameter is ignored if TMPL is not a class template.  */
987
988 static tree
989 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
990 {
991   if (args == error_mark_node)
992     return NULL_TREE;
993
994   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
995
996   /* There should be as many levels of arguments as there are
997      levels of parameters.  */
998   gcc_assert (TMPL_ARGS_DEPTH (args)
999               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
1000
1001   if (optimize_specialization_lookup_p (tmpl))
1002     {
1003       tree class_template;
1004       tree class_specialization;
1005       VEC(tree,gc) *methods;
1006       tree fns;
1007       int idx;
1008
1009       /* The template arguments actually apply to the containing
1010          class.  Find the class specialization with those
1011          arguments.  */
1012       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1013       class_specialization
1014         = retrieve_specialization (class_template, args, 0);
1015       if (!class_specialization)
1016         return NULL_TREE;
1017       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1018          for the specialization.  */
1019       idx = class_method_index_for_fn (class_specialization, tmpl);
1020       if (idx == -1)
1021         return NULL_TREE;
1022       /* Iterate through the methods with the indicated name, looking
1023          for the one that has an instance of TMPL.  */
1024       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1025       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1026         {
1027           tree fn = OVL_CURRENT (fns);
1028           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1029               /* using-declarations can add base methods to the method vec,
1030                  and we don't want those here.  */
1031               && DECL_CONTEXT (fn) == class_specialization)
1032             return fn;
1033         }
1034       return NULL_TREE;
1035     }
1036   else
1037     {
1038       spec_entry *found;
1039       spec_entry elt;
1040       htab_t specializations;
1041
1042       elt.tmpl = tmpl;
1043       elt.args = args;
1044       elt.spec = NULL_TREE;
1045
1046       if (DECL_CLASS_TEMPLATE_P (tmpl))
1047         specializations = type_specializations;
1048       else
1049         specializations = decl_specializations;
1050
1051       if (hash == 0)
1052         hash = hash_specialization (&elt);
1053       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1054       if (found)
1055         return found->spec;
1056     }
1057
1058   return NULL_TREE;
1059 }
1060
1061 /* Like retrieve_specialization, but for local declarations.  */
1062
1063 static tree
1064 retrieve_local_specialization (tree tmpl)
1065 {
1066   tree spec;
1067
1068   if (local_specializations == NULL)
1069     return NULL_TREE;
1070
1071   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1072                                      htab_hash_pointer (tmpl));
1073   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1074 }
1075
1076 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1077
1078 int
1079 is_specialization_of (tree decl, tree tmpl)
1080 {
1081   tree t;
1082
1083   if (TREE_CODE (decl) == FUNCTION_DECL)
1084     {
1085       for (t = decl;
1086            t != NULL_TREE;
1087            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1088         if (t == tmpl)
1089           return 1;
1090     }
1091   else
1092     {
1093       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1094
1095       for (t = TREE_TYPE (decl);
1096            t != NULL_TREE;
1097            t = CLASSTYPE_USE_TEMPLATE (t)
1098              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1099         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1100           return 1;
1101     }
1102
1103   return 0;
1104 }
1105
1106 /* Returns nonzero iff DECL is a specialization of friend declaration
1107    FRIEND_DECL according to [temp.friend].  */
1108
1109 bool
1110 is_specialization_of_friend (tree decl, tree friend_decl)
1111 {
1112   bool need_template = true;
1113   int template_depth;
1114
1115   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1116               || TREE_CODE (decl) == TYPE_DECL);
1117
1118   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1119      of a template class, we want to check if DECL is a specialization
1120      if this.  */
1121   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1122       && DECL_TEMPLATE_INFO (friend_decl)
1123       && !DECL_USE_TEMPLATE (friend_decl))
1124     {
1125       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1126       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1127       need_template = false;
1128     }
1129   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1130            && !PRIMARY_TEMPLATE_P (friend_decl))
1131     need_template = false;
1132
1133   /* There is nothing to do if this is not a template friend.  */
1134   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1135     return false;
1136
1137   if (is_specialization_of (decl, friend_decl))
1138     return true;
1139
1140   /* [temp.friend/6]
1141      A member of a class template may be declared to be a friend of a
1142      non-template class.  In this case, the corresponding member of
1143      every specialization of the class template is a friend of the
1144      class granting friendship.
1145
1146      For example, given a template friend declaration
1147
1148        template <class T> friend void A<T>::f();
1149
1150      the member function below is considered a friend
1151
1152        template <> struct A<int> {
1153          void f();
1154        };
1155
1156      For this type of template friend, TEMPLATE_DEPTH below will be
1157      nonzero.  To determine if DECL is a friend of FRIEND, we first
1158      check if the enclosing class is a specialization of another.  */
1159
1160   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1161   if (template_depth
1162       && DECL_CLASS_SCOPE_P (decl)
1163       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1164                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1165     {
1166       /* Next, we check the members themselves.  In order to handle
1167          a few tricky cases, such as when FRIEND_DECL's are
1168
1169            template <class T> friend void A<T>::g(T t);
1170            template <class T> template <T t> friend void A<T>::h();
1171
1172          and DECL's are
1173
1174            void A<int>::g(int);
1175            template <int> void A<int>::h();
1176
1177          we need to figure out ARGS, the template arguments from
1178          the context of DECL.  This is required for template substitution
1179          of `T' in the function parameter of `g' and template parameter
1180          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1181
1182       tree context = DECL_CONTEXT (decl);
1183       tree args = NULL_TREE;
1184       int current_depth = 0;
1185
1186       while (current_depth < template_depth)
1187         {
1188           if (CLASSTYPE_TEMPLATE_INFO (context))
1189             {
1190               if (current_depth == 0)
1191                 args = TYPE_TI_ARGS (context);
1192               else
1193                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1194               current_depth++;
1195             }
1196           context = TYPE_CONTEXT (context);
1197         }
1198
1199       if (TREE_CODE (decl) == FUNCTION_DECL)
1200         {
1201           bool is_template;
1202           tree friend_type;
1203           tree decl_type;
1204           tree friend_args_type;
1205           tree decl_args_type;
1206
1207           /* Make sure that both DECL and FRIEND_DECL are templates or
1208              non-templates.  */
1209           is_template = DECL_TEMPLATE_INFO (decl)
1210                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1211           if (need_template ^ is_template)
1212             return false;
1213           else if (is_template)
1214             {
1215               /* If both are templates, check template parameter list.  */
1216               tree friend_parms
1217                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1218                                          args, tf_none);
1219               if (!comp_template_parms
1220                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1221                       friend_parms))
1222                 return false;
1223
1224               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1225             }
1226           else
1227             decl_type = TREE_TYPE (decl);
1228
1229           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1230                                               tf_none, NULL_TREE);
1231           if (friend_type == error_mark_node)
1232             return false;
1233
1234           /* Check if return types match.  */
1235           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1236             return false;
1237
1238           /* Check if function parameter types match, ignoring the
1239              `this' parameter.  */
1240           friend_args_type = TYPE_ARG_TYPES (friend_type);
1241           decl_args_type = TYPE_ARG_TYPES (decl_type);
1242           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1243             friend_args_type = TREE_CHAIN (friend_args_type);
1244           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1245             decl_args_type = TREE_CHAIN (decl_args_type);
1246
1247           return compparms (decl_args_type, friend_args_type);
1248         }
1249       else
1250         {
1251           /* DECL is a TYPE_DECL */
1252           bool is_template;
1253           tree decl_type = TREE_TYPE (decl);
1254
1255           /* Make sure that both DECL and FRIEND_DECL are templates or
1256              non-templates.  */
1257           is_template
1258             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1259               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1260
1261           if (need_template ^ is_template)
1262             return false;
1263           else if (is_template)
1264             {
1265               tree friend_parms;
1266               /* If both are templates, check the name of the two
1267                  TEMPLATE_DECL's first because is_friend didn't.  */
1268               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1269                   != DECL_NAME (friend_decl))
1270                 return false;
1271
1272               /* Now check template parameter list.  */
1273               friend_parms
1274                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1275                                          args, tf_none);
1276               return comp_template_parms
1277                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1278                  friend_parms);
1279             }
1280           else
1281             return (DECL_NAME (decl)
1282                     == DECL_NAME (friend_decl));
1283         }
1284     }
1285   return false;
1286 }
1287
1288 /* Register the specialization SPEC as a specialization of TMPL with
1289    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1290    is actually just a friend declaration.  Returns SPEC, or an
1291    equivalent prior declaration, if available.  */
1292
1293 static tree
1294 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1295                          hashval_t hash)
1296 {
1297   tree fn;
1298   void **slot = NULL;
1299   spec_entry elt;
1300
1301   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1302
1303   if (TREE_CODE (spec) == FUNCTION_DECL
1304       && uses_template_parms (DECL_TI_ARGS (spec)))
1305     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1306        register it; we want the corresponding TEMPLATE_DECL instead.
1307        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1308        the more obvious `uses_template_parms (spec)' to avoid problems
1309        with default function arguments.  In particular, given
1310        something like this:
1311
1312           template <class T> void f(T t1, T t = T())
1313
1314        the default argument expression is not substituted for in an
1315        instantiation unless and until it is actually needed.  */
1316     return spec;
1317
1318   if (optimize_specialization_lookup_p (tmpl))
1319     /* We don't put these specializations in the hash table, but we might
1320        want to give an error about a mismatch.  */
1321     fn = retrieve_specialization (tmpl, args, 0);
1322   else
1323     {
1324       elt.tmpl = tmpl;
1325       elt.args = args;
1326       elt.spec = spec;
1327
1328       if (hash == 0)
1329         hash = hash_specialization (&elt);
1330
1331       slot =
1332         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1333       if (*slot)
1334         fn = ((spec_entry *) *slot)->spec;
1335       else
1336         fn = NULL_TREE;
1337     }
1338
1339   /* We can sometimes try to re-register a specialization that we've
1340      already got.  In particular, regenerate_decl_from_template calls
1341      duplicate_decls which will update the specialization list.  But,
1342      we'll still get called again here anyhow.  It's more convenient
1343      to simply allow this than to try to prevent it.  */
1344   if (fn == spec)
1345     return spec;
1346   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1347     {
1348       if (DECL_TEMPLATE_INSTANTIATION (fn))
1349         {
1350           if (DECL_ODR_USED (fn)
1351               || DECL_EXPLICIT_INSTANTIATION (fn))
1352             {
1353               error ("specialization of %qD after instantiation",
1354                      fn);
1355               return error_mark_node;
1356             }
1357           else
1358             {
1359               tree clone;
1360               /* This situation should occur only if the first
1361                  specialization is an implicit instantiation, the
1362                  second is an explicit specialization, and the
1363                  implicit instantiation has not yet been used.  That
1364                  situation can occur if we have implicitly
1365                  instantiated a member function and then specialized
1366                  it later.
1367
1368                  We can also wind up here if a friend declaration that
1369                  looked like an instantiation turns out to be a
1370                  specialization:
1371
1372                    template <class T> void foo(T);
1373                    class S { friend void foo<>(int) };
1374                    template <> void foo(int);
1375
1376                  We transform the existing DECL in place so that any
1377                  pointers to it become pointers to the updated
1378                  declaration.
1379
1380                  If there was a definition for the template, but not
1381                  for the specialization, we want this to look as if
1382                  there were no definition, and vice versa.  */
1383               DECL_INITIAL (fn) = NULL_TREE;
1384               duplicate_decls (spec, fn, is_friend);
1385               /* The call to duplicate_decls will have applied
1386                  [temp.expl.spec]:
1387
1388                    An explicit specialization of a function template
1389                    is inline only if it is explicitly declared to be,
1390                    and independently of whether its function template
1391                    is.
1392
1393                 to the primary function; now copy the inline bits to
1394                 the various clones.  */
1395               FOR_EACH_CLONE (clone, fn)
1396                 {
1397                   DECL_DECLARED_INLINE_P (clone)
1398                     = DECL_DECLARED_INLINE_P (fn);
1399                   DECL_SOURCE_LOCATION (clone)
1400                     = DECL_SOURCE_LOCATION (fn);
1401                 }
1402               check_specialization_namespace (fn);
1403
1404               return fn;
1405             }
1406         }
1407       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1408         {
1409           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1410             /* Dup decl failed, but this is a new definition. Set the
1411                line number so any errors match this new
1412                definition.  */
1413             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1414
1415           return fn;
1416         }
1417     }
1418   else if (fn)
1419     return duplicate_decls (spec, fn, is_friend);
1420
1421   /* A specialization must be declared in the same namespace as the
1422      template it is specializing.  */
1423   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1424       && !check_specialization_namespace (tmpl))
1425     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1426
1427   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1428     {
1429       spec_entry *entry = ggc_alloc_spec_entry ();
1430       gcc_assert (tmpl && args && spec);
1431       *entry = elt;
1432       *slot = entry;
1433       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1434           && PRIMARY_TEMPLATE_P (tmpl)
1435           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1436         /* TMPL is a forward declaration of a template function; keep a list
1437            of all specializations in case we need to reassign them to a friend
1438            template later in tsubst_friend_function.  */
1439         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1440           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1441     }
1442
1443   return spec;
1444 }
1445
1446 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1447    TMPL and ARGS members, ignores SPEC.  */
1448
1449 static int
1450 eq_specializations (const void *p1, const void *p2)
1451 {
1452   const spec_entry *e1 = (const spec_entry *)p1;
1453   const spec_entry *e2 = (const spec_entry *)p2;
1454
1455   return (e1->tmpl == e2->tmpl
1456           && comp_template_args (e1->args, e2->args));
1457 }
1458
1459 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1460
1461 static hashval_t
1462 hash_tmpl_and_args (tree tmpl, tree args)
1463 {
1464   hashval_t val = DECL_UID (tmpl);
1465   return iterative_hash_template_arg (args, val);
1466 }
1467
1468 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1469    ignoring SPEC.  */
1470
1471 static hashval_t
1472 hash_specialization (const void *p)
1473 {
1474   const spec_entry *e = (const spec_entry *)p;
1475   return hash_tmpl_and_args (e->tmpl, e->args);
1476 }
1477
1478 /* Recursively calculate a hash value for a template argument ARG, for use
1479    in the hash tables of template specializations.  */
1480
1481 hashval_t
1482 iterative_hash_template_arg (tree arg, hashval_t val)
1483 {
1484   unsigned HOST_WIDE_INT i;
1485   enum tree_code code;
1486   char tclass;
1487
1488   if (arg == NULL_TREE)
1489     return iterative_hash_object (arg, val);
1490
1491   if (!TYPE_P (arg))
1492     STRIP_NOPS (arg);
1493
1494   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1495     /* We can get one of these when re-hashing a previous entry in the middle
1496        of substituting into a pack expansion.  Just look through it.  */
1497     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1498
1499   code = TREE_CODE (arg);
1500   tclass = TREE_CODE_CLASS (code);
1501
1502   val = iterative_hash_object (code, val);
1503
1504   switch (code)
1505     {
1506     case ERROR_MARK:
1507       return val;
1508
1509     case IDENTIFIER_NODE:
1510       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1511
1512     case TREE_VEC:
1513       {
1514         int i, len = TREE_VEC_LENGTH (arg);
1515         for (i = 0; i < len; ++i)
1516           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1517         return val;
1518       }
1519
1520     case TYPE_PACK_EXPANSION:
1521     case EXPR_PACK_EXPANSION:
1522       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1523
1524     case TYPE_ARGUMENT_PACK:
1525     case NONTYPE_ARGUMENT_PACK:
1526       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1527
1528     case TREE_LIST:
1529       for (; arg; arg = TREE_CHAIN (arg))
1530         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1531       return val;
1532
1533     case OVERLOAD:
1534       for (; arg; arg = OVL_NEXT (arg))
1535         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1536       return val;
1537
1538     case CONSTRUCTOR:
1539       {
1540         tree field, value;
1541         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1542           {
1543             val = iterative_hash_template_arg (field, val);
1544             val = iterative_hash_template_arg (value, val);
1545           }
1546         return val;
1547       }
1548
1549     case PARM_DECL:
1550       if (!DECL_ARTIFICIAL (arg))
1551         {
1552           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1553           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1554         }
1555       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1556
1557     case TARGET_EXPR:
1558       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1559
1560     case PTRMEM_CST:
1561       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1562       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1563
1564     case TEMPLATE_PARM_INDEX:
1565       val = iterative_hash_template_arg
1566         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1567       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1568       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1569
1570     case TRAIT_EXPR:
1571       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1572       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1573       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1574
1575     case BASELINK:
1576       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1577                                          val);
1578       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1579                                           val);
1580
1581     case MODOP_EXPR:
1582       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1583       code = TREE_CODE (TREE_OPERAND (arg, 1));
1584       val = iterative_hash_object (code, val);
1585       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1586
1587     case LAMBDA_EXPR:
1588       /* A lambda can't appear in a template arg, but don't crash on
1589          erroneous input.  */
1590       gcc_assert (seen_error ());
1591       return val;
1592
1593     case CAST_EXPR:
1594     case IMPLICIT_CONV_EXPR:
1595     case STATIC_CAST_EXPR:
1596     case REINTERPRET_CAST_EXPR:
1597     case CONST_CAST_EXPR:
1598     case DYNAMIC_CAST_EXPR:
1599     case NEW_EXPR:
1600       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1601       /* Now hash operands as usual.  */
1602       break;
1603
1604     default:
1605       break;
1606     }
1607
1608   switch (tclass)
1609     {
1610     case tcc_type:
1611       if (TYPE_CANONICAL (arg))
1612         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1613                                       val);
1614       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1615         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1616       /* Otherwise just compare the types during lookup.  */
1617       return val;
1618
1619     case tcc_declaration:
1620     case tcc_constant:
1621       return iterative_hash_expr (arg, val);
1622
1623     default:
1624       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1625       {
1626         unsigned n = cp_tree_operand_length (arg);
1627         for (i = 0; i < n; ++i)
1628           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1629         return val;
1630       }
1631     }
1632   gcc_unreachable ();
1633   return 0;
1634 }
1635
1636 /* Unregister the specialization SPEC as a specialization of TMPL.
1637    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1638    if the SPEC was listed as a specialization of TMPL.
1639
1640    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1641
1642 bool
1643 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1644 {
1645   spec_entry *entry;
1646   spec_entry elt;
1647
1648   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1649   elt.args = TI_ARGS (tinfo);
1650   elt.spec = NULL_TREE;
1651
1652   entry = (spec_entry *) htab_find (decl_specializations, &elt);
1653   if (entry != NULL)
1654     {
1655       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1656       gcc_assert (new_spec != NULL_TREE);
1657       entry->spec = new_spec;
1658       return 1;
1659     }
1660
1661   return 0;
1662 }
1663
1664 /* Compare an entry in the local specializations hash table P1 (which
1665    is really a pointer to a TREE_LIST) with P2 (which is really a
1666    DECL).  */
1667
1668 static int
1669 eq_local_specializations (const void *p1, const void *p2)
1670 {
1671   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1672 }
1673
1674 /* Hash P1, an entry in the local specializations table.  */
1675
1676 static hashval_t
1677 hash_local_specialization (const void* p1)
1678 {
1679   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1680 }
1681
1682 /* Like register_specialization, but for local declarations.  We are
1683    registering SPEC, an instantiation of TMPL.  */
1684
1685 static void
1686 register_local_specialization (tree spec, tree tmpl)
1687 {
1688   void **slot;
1689
1690   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1691                                    htab_hash_pointer (tmpl), INSERT);
1692   *slot = build_tree_list (spec, tmpl);
1693 }
1694
1695 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1696    specialized class.  */
1697
1698 bool
1699 explicit_class_specialization_p (tree type)
1700 {
1701   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1702     return false;
1703   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1704 }
1705
1706 /* Print the list of functions at FNS, going through all the overloads
1707    for each element of the list.  Alternatively, FNS can not be a
1708    TREE_LIST, in which case it will be printed together with all the
1709    overloads.
1710
1711    MORE and *STR should respectively be FALSE and NULL when the function
1712    is called from the outside.  They are used internally on recursive
1713    calls.  print_candidates manages the two parameters and leaves NULL
1714    in *STR when it ends.  */
1715
1716 static void
1717 print_candidates_1 (tree fns, bool more, const char **str)
1718 {
1719   tree fn, fn2;
1720   char *spaces = NULL;
1721
1722   for (fn = fns; fn; fn = OVL_NEXT (fn))
1723     if (TREE_CODE (fn) == TREE_LIST)
1724       {
1725         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1726           print_candidates_1 (TREE_VALUE (fn2),
1727                               TREE_CHAIN (fn2) || more, str);
1728       }
1729     else
1730       {
1731         if (!*str)
1732           {
1733             /* Pick the prefix string.  */
1734             if (!more && !OVL_NEXT (fns))
1735               {
1736                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1737                 continue;
1738               }
1739
1740             *str = _("candidates are:");
1741             spaces = get_spaces (*str);
1742           }
1743         error ("%s %+#D", *str, OVL_CURRENT (fn));
1744         *str = spaces ? spaces : *str;
1745       }
1746
1747   if (!more)
1748     {
1749       free (spaces);
1750       *str = NULL;
1751     }
1752 }
1753
1754 /* Print the list of candidate FNS in an error message.  FNS can also
1755    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1756
1757 void
1758 print_candidates (tree fns)
1759 {
1760   const char *str = NULL;
1761   print_candidates_1 (fns, false, &str);
1762   gcc_assert (str == NULL);
1763 }
1764
1765 /* Returns the template (one of the functions given by TEMPLATE_ID)
1766    which can be specialized to match the indicated DECL with the
1767    explicit template args given in TEMPLATE_ID.  The DECL may be
1768    NULL_TREE if none is available.  In that case, the functions in
1769    TEMPLATE_ID are non-members.
1770
1771    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1772    specialization of a member template.
1773
1774    The TEMPLATE_COUNT is the number of references to qualifying
1775    template classes that appeared in the name of the function. See
1776    check_explicit_specialization for a more accurate description.
1777
1778    TSK indicates what kind of template declaration (if any) is being
1779    declared.  TSK_TEMPLATE indicates that the declaration given by
1780    DECL, though a FUNCTION_DECL, has template parameters, and is
1781    therefore a template function.
1782
1783    The template args (those explicitly specified and those deduced)
1784    are output in a newly created vector *TARGS_OUT.
1785
1786    If it is impossible to determine the result, an error message is
1787    issued.  The error_mark_node is returned to indicate failure.  */
1788
1789 static tree
1790 determine_specialization (tree template_id,
1791                           tree decl,
1792                           tree* targs_out,
1793                           int need_member_template,
1794                           int template_count,
1795                           tmpl_spec_kind tsk)
1796 {
1797   tree fns;
1798   tree targs;
1799   tree explicit_targs;
1800   tree candidates = NULL_TREE;
1801   /* A TREE_LIST of templates of which DECL may be a specialization.
1802      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1803      corresponding TREE_PURPOSE is the set of template arguments that,
1804      when used to instantiate the template, would produce a function
1805      with the signature of DECL.  */
1806   tree templates = NULL_TREE;
1807   int header_count;
1808   cp_binding_level *b;
1809
1810   *targs_out = NULL_TREE;
1811
1812   if (template_id == error_mark_node || decl == error_mark_node)
1813     return error_mark_node;
1814
1815   fns = TREE_OPERAND (template_id, 0);
1816   explicit_targs = TREE_OPERAND (template_id, 1);
1817
1818   if (fns == error_mark_node)
1819     return error_mark_node;
1820
1821   /* Check for baselinks.  */
1822   if (BASELINK_P (fns))
1823     fns = BASELINK_FUNCTIONS (fns);
1824
1825   if (!is_overloaded_fn (fns))
1826     {
1827       error ("%qD is not a function template", fns);
1828       return error_mark_node;
1829     }
1830
1831   /* Count the number of template headers specified for this
1832      specialization.  */
1833   header_count = 0;
1834   for (b = current_binding_level;
1835        b->kind == sk_template_parms;
1836        b = b->level_chain)
1837     ++header_count;
1838
1839   for (; fns; fns = OVL_NEXT (fns))
1840     {
1841       tree fn = OVL_CURRENT (fns);
1842
1843       if (TREE_CODE (fn) == TEMPLATE_DECL)
1844         {
1845           tree decl_arg_types;
1846           tree fn_arg_types;
1847
1848           /* In case of explicit specialization, we need to check if
1849              the number of template headers appearing in the specialization
1850              is correct. This is usually done in check_explicit_specialization,
1851              but the check done there cannot be exhaustive when specializing
1852              member functions. Consider the following code:
1853
1854              template <> void A<int>::f(int);
1855              template <> template <> void A<int>::f(int);
1856
1857              Assuming that A<int> is not itself an explicit specialization
1858              already, the first line specializes "f" which is a non-template
1859              member function, whilst the second line specializes "f" which
1860              is a template member function. So both lines are syntactically
1861              correct, and check_explicit_specialization does not reject
1862              them.
1863
1864              Here, we can do better, as we are matching the specialization
1865              against the declarations. We count the number of template
1866              headers, and we check if they match TEMPLATE_COUNT + 1
1867              (TEMPLATE_COUNT is the number of qualifying template classes,
1868              plus there must be another header for the member template
1869              itself).
1870
1871              Notice that if header_count is zero, this is not a
1872              specialization but rather a template instantiation, so there
1873              is no check we can perform here.  */
1874           if (header_count && header_count != template_count + 1)
1875             continue;
1876
1877           /* Check that the number of template arguments at the
1878              innermost level for DECL is the same as for FN.  */
1879           if (current_binding_level->kind == sk_template_parms
1880               && !current_binding_level->explicit_spec_p
1881               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1882                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1883                                       (current_template_parms))))
1884             continue;
1885
1886           /* DECL might be a specialization of FN.  */
1887           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1888           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1889
1890           /* For a non-static member function, we need to make sure
1891              that the const qualification is the same.  Since
1892              get_bindings does not try to merge the "this" parameter,
1893              we must do the comparison explicitly.  */
1894           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1895               && !same_type_p (TREE_VALUE (fn_arg_types),
1896                                TREE_VALUE (decl_arg_types)))
1897             continue;
1898
1899           /* Skip the "this" parameter and, for constructors of
1900              classes with virtual bases, the VTT parameter.  A
1901              full specialization of a constructor will have a VTT
1902              parameter, but a template never will.  */ 
1903           decl_arg_types 
1904             = skip_artificial_parms_for (decl, decl_arg_types);
1905           fn_arg_types 
1906             = skip_artificial_parms_for (fn, fn_arg_types);
1907
1908           /* Check that the number of function parameters matches.
1909              For example,
1910                template <class T> void f(int i = 0);
1911                template <> void f<int>();
1912              The specialization f<int> is invalid but is not caught
1913              by get_bindings below.  */
1914           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1915             continue;
1916
1917           /* Function templates cannot be specializations; there are
1918              no partial specializations of functions.  Therefore, if
1919              the type of DECL does not match FN, there is no
1920              match.  */
1921           if (tsk == tsk_template)
1922             {
1923               if (compparms (fn_arg_types, decl_arg_types))
1924                 candidates = tree_cons (NULL_TREE, fn, candidates);
1925               continue;
1926             }
1927
1928           /* See whether this function might be a specialization of this
1929              template.  */
1930           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1931
1932           if (!targs)
1933             /* We cannot deduce template arguments that when used to
1934                specialize TMPL will produce DECL.  */
1935             continue;
1936
1937           /* Save this template, and the arguments deduced.  */
1938           templates = tree_cons (targs, fn, templates);
1939         }
1940       else if (need_member_template)
1941         /* FN is an ordinary member function, and we need a
1942            specialization of a member template.  */
1943         ;
1944       else if (TREE_CODE (fn) != FUNCTION_DECL)
1945         /* We can get IDENTIFIER_NODEs here in certain erroneous
1946            cases.  */
1947         ;
1948       else if (!DECL_FUNCTION_MEMBER_P (fn))
1949         /* This is just an ordinary non-member function.  Nothing can
1950            be a specialization of that.  */
1951         ;
1952       else if (DECL_ARTIFICIAL (fn))
1953         /* Cannot specialize functions that are created implicitly.  */
1954         ;
1955       else
1956         {
1957           tree decl_arg_types;
1958
1959           /* This is an ordinary member function.  However, since
1960              we're here, we can assume it's enclosing class is a
1961              template class.  For example,
1962
1963                template <typename T> struct S { void f(); };
1964                template <> void S<int>::f() {}
1965
1966              Here, S<int>::f is a non-template, but S<int> is a
1967              template class.  If FN has the same type as DECL, we
1968              might be in business.  */
1969
1970           if (!DECL_TEMPLATE_INFO (fn))
1971             /* Its enclosing class is an explicit specialization
1972                of a template class.  This is not a candidate.  */
1973             continue;
1974
1975           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1976                             TREE_TYPE (TREE_TYPE (fn))))
1977             /* The return types differ.  */
1978             continue;
1979
1980           /* Adjust the type of DECL in case FN is a static member.  */
1981           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1982           if (DECL_STATIC_FUNCTION_P (fn)
1983               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1984             decl_arg_types = TREE_CHAIN (decl_arg_types);
1985
1986           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1987                          decl_arg_types))
1988             /* They match!  */
1989             candidates = tree_cons (NULL_TREE, fn, candidates);
1990         }
1991     }
1992
1993   if (templates && TREE_CHAIN (templates))
1994     {
1995       /* We have:
1996
1997            [temp.expl.spec]
1998
1999            It is possible for a specialization with a given function
2000            signature to be instantiated from more than one function
2001            template.  In such cases, explicit specification of the
2002            template arguments must be used to uniquely identify the
2003            function template specialization being specialized.
2004
2005          Note that here, there's no suggestion that we're supposed to
2006          determine which of the candidate templates is most
2007          specialized.  However, we, also have:
2008
2009            [temp.func.order]
2010
2011            Partial ordering of overloaded function template
2012            declarations is used in the following contexts to select
2013            the function template to which a function template
2014            specialization refers:
2015
2016            -- when an explicit specialization refers to a function
2017               template.
2018
2019          So, we do use the partial ordering rules, at least for now.
2020          This extension can only serve to make invalid programs valid,
2021          so it's safe.  And, there is strong anecdotal evidence that
2022          the committee intended the partial ordering rules to apply;
2023          the EDG front end has that behavior, and John Spicer claims
2024          that the committee simply forgot to delete the wording in
2025          [temp.expl.spec].  */
2026       tree tmpl = most_specialized_instantiation (templates);
2027       if (tmpl != error_mark_node)
2028         {
2029           templates = tmpl;
2030           TREE_CHAIN (templates) = NULL_TREE;
2031         }
2032     }
2033
2034   if (templates == NULL_TREE && candidates == NULL_TREE)
2035     {
2036       error ("template-id %qD for %q+D does not match any template "
2037              "declaration", template_id, decl);
2038       if (header_count && header_count != template_count + 1)
2039         inform (input_location, "saw %d %<template<>%>, need %d for "
2040                 "specializing a member function template",
2041                 header_count, template_count + 1);
2042       return error_mark_node;
2043     }
2044   else if ((templates && TREE_CHAIN (templates))
2045            || (candidates && TREE_CHAIN (candidates))
2046            || (templates && candidates))
2047     {
2048       error ("ambiguous template specialization %qD for %q+D",
2049              template_id, decl);
2050       candidates = chainon (candidates, templates);
2051       print_candidates (candidates);
2052       return error_mark_node;
2053     }
2054
2055   /* We have one, and exactly one, match.  */
2056   if (candidates)
2057     {
2058       tree fn = TREE_VALUE (candidates);
2059       *targs_out = copy_node (DECL_TI_ARGS (fn));
2060       /* DECL is a re-declaration or partial instantiation of a template
2061          function.  */
2062       if (TREE_CODE (fn) == TEMPLATE_DECL)
2063         return fn;
2064       /* It was a specialization of an ordinary member function in a
2065          template class.  */
2066       return DECL_TI_TEMPLATE (fn);
2067     }
2068
2069   /* It was a specialization of a template.  */
2070   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2071   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2072     {
2073       *targs_out = copy_node (targs);
2074       SET_TMPL_ARGS_LEVEL (*targs_out,
2075                            TMPL_ARGS_DEPTH (*targs_out),
2076                            TREE_PURPOSE (templates));
2077     }
2078   else
2079     *targs_out = TREE_PURPOSE (templates);
2080   return TREE_VALUE (templates);
2081 }
2082
2083 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2084    but with the default argument values filled in from those in the
2085    TMPL_TYPES.  */
2086
2087 static tree
2088 copy_default_args_to_explicit_spec_1 (tree spec_types,
2089                                       tree tmpl_types)
2090 {
2091   tree new_spec_types;
2092
2093   if (!spec_types)
2094     return NULL_TREE;
2095
2096   if (spec_types == void_list_node)
2097     return void_list_node;
2098
2099   /* Substitute into the rest of the list.  */
2100   new_spec_types =
2101     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2102                                           TREE_CHAIN (tmpl_types));
2103
2104   /* Add the default argument for this parameter.  */
2105   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2106                          TREE_VALUE (spec_types),
2107                          new_spec_types);
2108 }
2109
2110 /* DECL is an explicit specialization.  Replicate default arguments
2111    from the template it specializes.  (That way, code like:
2112
2113      template <class T> void f(T = 3);
2114      template <> void f(double);
2115      void g () { f (); }
2116
2117    works, as required.)  An alternative approach would be to look up
2118    the correct default arguments at the call-site, but this approach
2119    is consistent with how implicit instantiations are handled.  */
2120
2121 static void
2122 copy_default_args_to_explicit_spec (tree decl)
2123 {
2124   tree tmpl;
2125   tree spec_types;
2126   tree tmpl_types;
2127   tree new_spec_types;
2128   tree old_type;
2129   tree new_type;
2130   tree t;
2131   tree object_type = NULL_TREE;
2132   tree in_charge = NULL_TREE;
2133   tree vtt = NULL_TREE;
2134
2135   /* See if there's anything we need to do.  */
2136   tmpl = DECL_TI_TEMPLATE (decl);
2137   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2138   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2139     if (TREE_PURPOSE (t))
2140       break;
2141   if (!t)
2142     return;
2143
2144   old_type = TREE_TYPE (decl);
2145   spec_types = TYPE_ARG_TYPES (old_type);
2146
2147   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2148     {
2149       /* Remove the this pointer, but remember the object's type for
2150          CV quals.  */
2151       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2152       spec_types = TREE_CHAIN (spec_types);
2153       tmpl_types = TREE_CHAIN (tmpl_types);
2154
2155       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2156         {
2157           /* DECL may contain more parameters than TMPL due to the extra
2158              in-charge parameter in constructors and destructors.  */
2159           in_charge = spec_types;
2160           spec_types = TREE_CHAIN (spec_types);
2161         }
2162       if (DECL_HAS_VTT_PARM_P (decl))
2163         {
2164           vtt = spec_types;
2165           spec_types = TREE_CHAIN (spec_types);
2166         }
2167     }
2168
2169   /* Compute the merged default arguments.  */
2170   new_spec_types =
2171     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2172
2173   /* Compute the new FUNCTION_TYPE.  */
2174   if (object_type)
2175     {
2176       if (vtt)
2177         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2178                                          TREE_VALUE (vtt),
2179                                          new_spec_types);
2180
2181       if (in_charge)
2182         /* Put the in-charge parameter back.  */
2183         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2184                                          TREE_VALUE (in_charge),
2185                                          new_spec_types);
2186
2187       new_type = build_method_type_directly (object_type,
2188                                              TREE_TYPE (old_type),
2189                                              new_spec_types);
2190     }
2191   else
2192     new_type = build_function_type (TREE_TYPE (old_type),
2193                                     new_spec_types);
2194   new_type = cp_build_type_attribute_variant (new_type,
2195                                               TYPE_ATTRIBUTES (old_type));
2196   new_type = build_exception_variant (new_type,
2197                                       TYPE_RAISES_EXCEPTIONS (old_type));
2198   TREE_TYPE (decl) = new_type;
2199 }
2200
2201 /* Check to see if the function just declared, as indicated in
2202    DECLARATOR, and in DECL, is a specialization of a function
2203    template.  We may also discover that the declaration is an explicit
2204    instantiation at this point.
2205
2206    Returns DECL, or an equivalent declaration that should be used
2207    instead if all goes well.  Issues an error message if something is
2208    amiss.  Returns error_mark_node if the error is not easily
2209    recoverable.
2210
2211    FLAGS is a bitmask consisting of the following flags:
2212
2213    2: The function has a definition.
2214    4: The function is a friend.
2215
2216    The TEMPLATE_COUNT is the number of references to qualifying
2217    template classes that appeared in the name of the function.  For
2218    example, in
2219
2220      template <class T> struct S { void f(); };
2221      void S<int>::f();
2222
2223    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2224    classes are not counted in the TEMPLATE_COUNT, so that in
2225
2226      template <class T> struct S {};
2227      template <> struct S<int> { void f(); }
2228      template <> void S<int>::f();
2229
2230    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2231    invalid; there should be no template <>.)
2232
2233    If the function is a specialization, it is marked as such via
2234    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2235    is set up correctly, and it is added to the list of specializations
2236    for that template.  */
2237
2238 tree
2239 check_explicit_specialization (tree declarator,
2240                                tree decl,
2241                                int template_count,
2242                                int flags)
2243 {
2244   int have_def = flags & 2;
2245   int is_friend = flags & 4;
2246   int specialization = 0;
2247   int explicit_instantiation = 0;
2248   int member_specialization = 0;
2249   tree ctype = DECL_CLASS_CONTEXT (decl);
2250   tree dname = DECL_NAME (decl);
2251   tmpl_spec_kind tsk;
2252
2253   if (is_friend)
2254     {
2255       if (!processing_specialization)
2256         tsk = tsk_none;
2257       else
2258         tsk = tsk_excessive_parms;
2259     }
2260   else
2261     tsk = current_tmpl_spec_kind (template_count);
2262
2263   switch (tsk)
2264     {
2265     case tsk_none:
2266       if (processing_specialization)
2267         {
2268           specialization = 1;
2269           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2270         }
2271       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2272         {
2273           if (is_friend)
2274             /* This could be something like:
2275
2276                template <class T> void f(T);
2277                class S { friend void f<>(int); }  */
2278             specialization = 1;
2279           else
2280             {
2281               /* This case handles bogus declarations like template <>
2282                  template <class T> void f<int>(); */
2283
2284               error ("template-id %qD in declaration of primary template",
2285                      declarator);
2286               return decl;
2287             }
2288         }
2289       break;
2290
2291     case tsk_invalid_member_spec:
2292       /* The error has already been reported in
2293          check_specialization_scope.  */
2294       return error_mark_node;
2295
2296     case tsk_invalid_expl_inst:
2297       error ("template parameter list used in explicit instantiation");
2298
2299       /* Fall through.  */
2300
2301     case tsk_expl_inst:
2302       if (have_def)
2303         error ("definition provided for explicit instantiation");
2304
2305       explicit_instantiation = 1;
2306       break;
2307
2308     case tsk_excessive_parms:
2309     case tsk_insufficient_parms:
2310       if (tsk == tsk_excessive_parms)
2311         error ("too many template parameter lists in declaration of %qD",
2312                decl);
2313       else if (template_header_count)
2314         error("too few template parameter lists in declaration of %qD", decl);
2315       else
2316         error("explicit specialization of %qD must be introduced by "
2317               "%<template <>%>", decl);
2318
2319       /* Fall through.  */
2320     case tsk_expl_spec:
2321       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2322       if (ctype)
2323         member_specialization = 1;
2324       else
2325         specialization = 1;
2326       break;
2327
2328     case tsk_template:
2329       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2330         {
2331           /* This case handles bogus declarations like template <>
2332              template <class T> void f<int>(); */
2333
2334           if (uses_template_parms (declarator))
2335             error ("function template partial specialization %qD "
2336                    "is not allowed", declarator);
2337           else
2338             error ("template-id %qD in declaration of primary template",
2339                    declarator);
2340           return decl;
2341         }
2342
2343       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2344         /* This is a specialization of a member template, without
2345            specialization the containing class.  Something like:
2346
2347              template <class T> struct S {
2348                template <class U> void f (U);
2349              };
2350              template <> template <class U> void S<int>::f(U) {}
2351
2352            That's a specialization -- but of the entire template.  */
2353         specialization = 1;
2354       break;
2355
2356     default:
2357       gcc_unreachable ();
2358     }
2359
2360   if (specialization || member_specialization)
2361     {
2362       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2363       for (; t; t = TREE_CHAIN (t))
2364         if (TREE_PURPOSE (t))
2365           {
2366             permerror (input_location, 
2367                        "default argument specified in explicit specialization");
2368             break;
2369           }
2370     }
2371
2372   if (specialization || member_specialization || explicit_instantiation)
2373     {
2374       tree tmpl = NULL_TREE;
2375       tree targs = NULL_TREE;
2376
2377       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2378       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2379         {
2380           tree fns;
2381
2382           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2383           if (ctype)
2384             fns = dname;
2385           else
2386             {
2387               /* If there is no class context, the explicit instantiation
2388                  must be at namespace scope.  */
2389               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2390
2391               /* Find the namespace binding, using the declaration
2392                  context.  */
2393               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2394                                            false, true);
2395               if (fns == error_mark_node || !is_overloaded_fn (fns))
2396                 {
2397                   error ("%qD is not a template function", dname);
2398                   fns = error_mark_node;
2399                 }
2400               else
2401                 {
2402                   tree fn = OVL_CURRENT (fns);
2403                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2404                                                 CP_DECL_CONTEXT (fn)))
2405                     error ("%qD is not declared in %qD",
2406                            decl, current_namespace);
2407                 }
2408             }
2409
2410           declarator = lookup_template_function (fns, NULL_TREE);
2411         }
2412
2413       if (declarator == error_mark_node)
2414         return error_mark_node;
2415
2416       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2417         {
2418           if (!explicit_instantiation)
2419             /* A specialization in class scope.  This is invalid,
2420                but the error will already have been flagged by
2421                check_specialization_scope.  */
2422             return error_mark_node;
2423           else
2424             {
2425               /* It's not valid to write an explicit instantiation in
2426                  class scope, e.g.:
2427
2428                    class C { template void f(); }
2429
2430                    This case is caught by the parser.  However, on
2431                    something like:
2432
2433                    template class C { void f(); };
2434
2435                    (which is invalid) we can get here.  The error will be
2436                    issued later.  */
2437               ;
2438             }
2439
2440           return decl;
2441         }
2442       else if (ctype != NULL_TREE
2443                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2444                    IDENTIFIER_NODE))
2445         {
2446           /* Find the list of functions in ctype that have the same
2447              name as the declared function.  */
2448           tree name = TREE_OPERAND (declarator, 0);
2449           tree fns = NULL_TREE;
2450           int idx;
2451
2452           if (constructor_name_p (name, ctype))
2453             {
2454               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2455
2456               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2457                   : !CLASSTYPE_DESTRUCTORS (ctype))
2458                 {
2459                   /* From [temp.expl.spec]:
2460
2461                      If such an explicit specialization for the member
2462                      of a class template names an implicitly-declared
2463                      special member function (clause _special_), the
2464                      program is ill-formed.
2465
2466                      Similar language is found in [temp.explicit].  */
2467                   error ("specialization of implicitly-declared special member function");
2468                   return error_mark_node;
2469                 }
2470
2471               name = is_constructor ? ctor_identifier : dtor_identifier;
2472             }
2473
2474           if (!DECL_CONV_FN_P (decl))
2475             {
2476               idx = lookup_fnfields_1 (ctype, name);
2477               if (idx >= 0)
2478                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2479             }
2480           else
2481             {
2482               VEC(tree,gc) *methods;
2483               tree ovl;
2484
2485               /* For a type-conversion operator, we cannot do a
2486                  name-based lookup.  We might be looking for `operator
2487                  int' which will be a specialization of `operator T'.
2488                  So, we find *all* the conversion operators, and then
2489                  select from them.  */
2490               fns = NULL_TREE;
2491
2492               methods = CLASSTYPE_METHOD_VEC (ctype);
2493               if (methods)
2494                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2495                      VEC_iterate (tree, methods, idx, ovl);
2496                      ++idx)
2497                   {
2498                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2499                       /* There are no more conversion functions.  */
2500                       break;
2501
2502                     /* Glue all these conversion functions together
2503                        with those we already have.  */
2504                     for (; ovl; ovl = OVL_NEXT (ovl))
2505                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2506                   }
2507             }
2508
2509           if (fns == NULL_TREE)
2510             {
2511               error ("no member function %qD declared in %qT", name, ctype);
2512               return error_mark_node;
2513             }
2514           else
2515             TREE_OPERAND (declarator, 0) = fns;
2516         }
2517
2518       /* Figure out what exactly is being specialized at this point.
2519          Note that for an explicit instantiation, even one for a
2520          member function, we cannot tell apriori whether the
2521          instantiation is for a member template, or just a member
2522          function of a template class.  Even if a member template is
2523          being instantiated, the member template arguments may be
2524          elided if they can be deduced from the rest of the
2525          declaration.  */
2526       tmpl = determine_specialization (declarator, decl,
2527                                        &targs,
2528                                        member_specialization,
2529                                        template_count,
2530                                        tsk);
2531
2532       if (!tmpl || tmpl == error_mark_node)
2533         /* We couldn't figure out what this declaration was
2534            specializing.  */
2535         return error_mark_node;
2536       else
2537         {
2538           tree gen_tmpl = most_general_template (tmpl);
2539
2540           if (explicit_instantiation)
2541             {
2542               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2543                  is done by do_decl_instantiation later.  */
2544
2545               int arg_depth = TMPL_ARGS_DEPTH (targs);
2546               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2547
2548               if (arg_depth > parm_depth)
2549                 {
2550                   /* If TMPL is not the most general template (for
2551                      example, if TMPL is a friend template that is
2552                      injected into namespace scope), then there will
2553                      be too many levels of TARGS.  Remove some of them
2554                      here.  */
2555                   int i;
2556                   tree new_targs;
2557
2558                   new_targs = make_tree_vec (parm_depth);
2559                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2560                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2561                       = TREE_VEC_ELT (targs, i);
2562                   targs = new_targs;
2563                 }
2564
2565               return instantiate_template (tmpl, targs, tf_error);
2566             }
2567
2568           /* If we thought that the DECL was a member function, but it
2569              turns out to be specializing a static member function,
2570              make DECL a static member function as well.  */
2571           if (DECL_STATIC_FUNCTION_P (tmpl)
2572               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2573             revert_static_member_fn (decl);
2574
2575           /* If this is a specialization of a member template of a
2576              template class, we want to return the TEMPLATE_DECL, not
2577              the specialization of it.  */
2578           if (tsk == tsk_template)
2579             {
2580               tree result = DECL_TEMPLATE_RESULT (tmpl);
2581               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2582               DECL_INITIAL (result) = NULL_TREE;
2583               if (have_def)
2584                 {
2585                   tree parm;
2586                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2587                   DECL_SOURCE_LOCATION (result)
2588                     = DECL_SOURCE_LOCATION (decl);
2589                   /* We want to use the argument list specified in the
2590                      definition, not in the original declaration.  */
2591                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2592                   for (parm = DECL_ARGUMENTS (result); parm;
2593                        parm = DECL_CHAIN (parm))
2594                     DECL_CONTEXT (parm) = result;
2595                 }
2596               return register_specialization (tmpl, gen_tmpl, targs,
2597                                               is_friend, 0);
2598             }
2599
2600           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2601           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2602
2603           /* Inherit default function arguments from the template
2604              DECL is specializing.  */
2605           copy_default_args_to_explicit_spec (decl);
2606
2607           /* This specialization has the same protection as the
2608              template it specializes.  */
2609           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2610           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2611
2612           /* 7.1.1-1 [dcl.stc]
2613
2614              A storage-class-specifier shall not be specified in an
2615              explicit specialization...
2616
2617              The parser rejects these, so unless action is taken here,
2618              explicit function specializations will always appear with
2619              global linkage.
2620
2621              The action recommended by the C++ CWG in response to C++
2622              defect report 605 is to make the storage class and linkage
2623              of the explicit specialization match the templated function:
2624
2625              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2626            */
2627           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2628             {
2629               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2630               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2631
2632               /* This specialization has the same linkage and visibility as
2633                  the function template it specializes.  */
2634               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2635               if (! TREE_PUBLIC (decl))
2636                 {
2637                   DECL_INTERFACE_KNOWN (decl) = 1;
2638                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2639                 }
2640               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2641               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2642                 {
2643                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2644                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2645                 }
2646             }
2647
2648           /* If DECL is a friend declaration, declared using an
2649              unqualified name, the namespace associated with DECL may
2650              have been set incorrectly.  For example, in:
2651
2652                template <typename T> void f(T);
2653                namespace N {
2654                  struct S { friend void f<int>(int); }
2655                }
2656
2657              we will have set the DECL_CONTEXT for the friend
2658              declaration to N, rather than to the global namespace.  */
2659           if (DECL_NAMESPACE_SCOPE_P (decl))
2660             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2661
2662           if (is_friend && !have_def)
2663             /* This is not really a declaration of a specialization.
2664                It's just the name of an instantiation.  But, it's not
2665                a request for an instantiation, either.  */
2666             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2667           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2668             /* This is indeed a specialization.  In case of constructors
2669                and destructors, we need in-charge and not-in-charge
2670                versions in V3 ABI.  */
2671             clone_function_decl (decl, /*update_method_vec_p=*/0);
2672
2673           /* Register this specialization so that we can find it
2674              again.  */
2675           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2676         }
2677     }
2678
2679   return decl;
2680 }
2681
2682 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2683    parameters.  These are represented in the same format used for
2684    DECL_TEMPLATE_PARMS.  */
2685
2686 int
2687 comp_template_parms (const_tree parms1, const_tree parms2)
2688 {
2689   const_tree p1;
2690   const_tree p2;
2691
2692   if (parms1 == parms2)
2693     return 1;
2694
2695   for (p1 = parms1, p2 = parms2;
2696        p1 != NULL_TREE && p2 != NULL_TREE;
2697        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2698     {
2699       tree t1 = TREE_VALUE (p1);
2700       tree t2 = TREE_VALUE (p2);
2701       int i;
2702
2703       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2704       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2705
2706       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2707         return 0;
2708
2709       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2710         {
2711           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2712           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2713
2714           /* If either of the template parameters are invalid, assume
2715              they match for the sake of error recovery. */
2716           if (parm1 == error_mark_node || parm2 == error_mark_node)
2717             return 1;
2718
2719           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2720             return 0;
2721
2722           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2723               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2724                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2725             continue;
2726           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2727             return 0;
2728         }
2729     }
2730
2731   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2732     /* One set of parameters has more parameters lists than the
2733        other.  */
2734     return 0;
2735
2736   return 1;
2737 }
2738
2739 /* Determine whether PARM is a parameter pack.  */
2740
2741 bool 
2742 template_parameter_pack_p (const_tree parm)
2743 {
2744   /* Determine if we have a non-type template parameter pack.  */
2745   if (TREE_CODE (parm) == PARM_DECL)
2746     return (DECL_TEMPLATE_PARM_P (parm) 
2747             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2748   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2749     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2750
2751   /* If this is a list of template parameters, we could get a
2752      TYPE_DECL or a TEMPLATE_DECL.  */ 
2753   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2754     parm = TREE_TYPE (parm);
2755
2756   /* Otherwise it must be a type template parameter.  */
2757   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2758            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2759           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2760 }
2761
2762 /* Determine if T is a function parameter pack.  */
2763
2764 bool
2765 function_parameter_pack_p (const_tree t)
2766 {
2767   if (t && TREE_CODE (t) == PARM_DECL)
2768     return FUNCTION_PARAMETER_PACK_P (t);
2769   return false;
2770 }
2771
2772 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2773    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2774
2775 tree
2776 get_function_template_decl (const_tree primary_func_tmpl_inst)
2777 {
2778   if (! primary_func_tmpl_inst
2779       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2780       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2781     return NULL;
2782
2783   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2784 }
2785
2786 /* Return true iff the function parameter PARAM_DECL was expanded
2787    from the function parameter pack PACK.  */
2788
2789 bool
2790 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2791 {
2792   if (DECL_ARTIFICIAL (param_decl)
2793       || !function_parameter_pack_p (pack))
2794     return false;
2795
2796   /* The parameter pack and its pack arguments have the same
2797      DECL_PARM_INDEX.  */
2798   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2799 }
2800
2801 /* Determine whether ARGS describes a variadic template args list,
2802    i.e., one that is terminated by a template argument pack.  */
2803
2804 static bool 
2805 template_args_variadic_p (tree args)
2806 {
2807   int nargs;
2808   tree last_parm;
2809
2810   if (args == NULL_TREE)
2811     return false;
2812
2813   args = INNERMOST_TEMPLATE_ARGS (args);
2814   nargs = TREE_VEC_LENGTH (args);
2815
2816   if (nargs == 0)
2817     return false;
2818
2819   last_parm = TREE_VEC_ELT (args, nargs - 1);
2820
2821   return ARGUMENT_PACK_P (last_parm);
2822 }
2823
2824 /* Generate a new name for the parameter pack name NAME (an
2825    IDENTIFIER_NODE) that incorporates its */
2826
2827 static tree
2828 make_ith_pack_parameter_name (tree name, int i)
2829 {
2830   /* Munge the name to include the parameter index.  */
2831 #define NUMBUF_LEN 128
2832   char numbuf[NUMBUF_LEN];
2833   char* newname;
2834   int newname_len;
2835
2836   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2837   newname_len = IDENTIFIER_LENGTH (name)
2838                 + strlen (numbuf) + 2;
2839   newname = (char*)alloca (newname_len);
2840   snprintf (newname, newname_len,
2841             "%s#%i", IDENTIFIER_POINTER (name), i);
2842   return get_identifier (newname);
2843 }
2844
2845 /* Return true if T is a primary function
2846    or class template instantiation.  */
2847
2848 bool
2849 primary_template_instantiation_p (const_tree t)
2850 {
2851   if (!t)
2852     return false;
2853
2854   if (TREE_CODE (t) == FUNCTION_DECL)
2855     return DECL_LANG_SPECIFIC (t)
2856            && DECL_TEMPLATE_INSTANTIATION (t)
2857            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2858   else if (CLASS_TYPE_P (t))
2859     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2860            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2861   return false;
2862 }
2863
2864 /* Return true if PARM is a template template parameter.  */
2865
2866 bool
2867 template_template_parameter_p (const_tree parm)
2868 {
2869   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2870 }
2871
2872 /* Return the template parameters of T if T is a
2873    primary template instantiation, NULL otherwise.  */
2874
2875 tree
2876 get_primary_template_innermost_parameters (const_tree t)
2877 {
2878   tree parms = NULL, template_info = NULL;
2879
2880   if ((template_info = get_template_info (t))
2881       && primary_template_instantiation_p (t))
2882     parms = INNERMOST_TEMPLATE_PARMS
2883         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2884
2885   return parms;
2886 }
2887
2888 /* Return the template parameters of the LEVELth level from the full list
2889    of template parameters PARMS.  */
2890
2891 tree
2892 get_template_parms_at_level (tree parms, int level)
2893 {
2894   tree p;
2895   if (!parms
2896       || TREE_CODE (parms) != TREE_LIST
2897       || level > TMPL_PARMS_DEPTH (parms))
2898     return NULL_TREE;
2899
2900   for (p = parms; p; p = TREE_CHAIN (p))
2901     if (TMPL_PARMS_DEPTH (p) == level)
2902       return p;
2903
2904   return NULL_TREE;
2905 }
2906
2907 /* Returns the template arguments of T if T is a template instantiation,
2908    NULL otherwise.  */
2909
2910 tree
2911 get_template_innermost_arguments (const_tree t)
2912 {
2913   tree args = NULL, template_info = NULL;
2914
2915   if ((template_info = get_template_info (t))
2916       && TI_ARGS (template_info))
2917     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2918
2919   return args;
2920 }
2921
2922 /* Return the argument pack elements of T if T is a template argument pack,
2923    NULL otherwise.  */
2924
2925 tree
2926 get_template_argument_pack_elems (const_tree t)
2927 {
2928   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2929       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2930     return NULL;
2931
2932   return ARGUMENT_PACK_ARGS (t);
2933 }
2934
2935 /* Structure used to track the progress of find_parameter_packs_r.  */
2936 struct find_parameter_pack_data 
2937 {
2938   /* TREE_LIST that will contain all of the parameter packs found by
2939      the traversal.  */
2940   tree* parameter_packs;
2941
2942   /* Set of AST nodes that have been visited by the traversal.  */
2943   struct pointer_set_t *visited;
2944 };
2945
2946 /* Identifies all of the argument packs that occur in a template
2947    argument and appends them to the TREE_LIST inside DATA, which is a
2948    find_parameter_pack_data structure. This is a subroutine of
2949    make_pack_expansion and uses_parameter_packs.  */
2950 static tree
2951 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2952 {
2953   tree t = *tp;
2954   struct find_parameter_pack_data* ppd = 
2955     (struct find_parameter_pack_data*)data;
2956   bool parameter_pack_p = false;
2957
2958   /* Identify whether this is a parameter pack or not.  */
2959   switch (TREE_CODE (t))
2960     {
2961     case TEMPLATE_PARM_INDEX:
2962       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2963         parameter_pack_p = true;
2964       break;
2965
2966     case TEMPLATE_TYPE_PARM:
2967       t = TYPE_MAIN_VARIANT (t);
2968     case TEMPLATE_TEMPLATE_PARM:
2969       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2970         parameter_pack_p = true;
2971       break;
2972
2973     case PARM_DECL:
2974       if (FUNCTION_PARAMETER_PACK_P (t))
2975         {
2976           /* We don't want to walk into the type of a PARM_DECL,
2977              because we don't want to see the type parameter pack.  */
2978           *walk_subtrees = 0;
2979           parameter_pack_p = true;
2980         }
2981       break;
2982
2983     case BASES:
2984       parameter_pack_p = true;
2985       break;
2986     default:
2987       /* Not a parameter pack.  */
2988       break;
2989     }
2990
2991   if (parameter_pack_p)
2992     {
2993       /* Add this parameter pack to the list.  */
2994       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2995     }
2996
2997   if (TYPE_P (t))
2998     cp_walk_tree (&TYPE_CONTEXT (t), 
2999                   &find_parameter_packs_r, ppd, ppd->visited);
3000
3001   /* This switch statement will return immediately if we don't find a
3002      parameter pack.  */
3003   switch (TREE_CODE (t)) 
3004     {
3005     case TEMPLATE_PARM_INDEX:
3006       return NULL_TREE;
3007
3008     case BOUND_TEMPLATE_TEMPLATE_PARM:
3009       /* Check the template itself.  */
3010       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3011                     &find_parameter_packs_r, ppd, ppd->visited);
3012       /* Check the template arguments.  */
3013       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3014                     ppd->visited);
3015       *walk_subtrees = 0;
3016       return NULL_TREE;
3017
3018     case TEMPLATE_TYPE_PARM:
3019     case TEMPLATE_TEMPLATE_PARM:
3020       return NULL_TREE;
3021
3022     case PARM_DECL:
3023       return NULL_TREE;
3024
3025     case RECORD_TYPE:
3026       if (TYPE_PTRMEMFUNC_P (t))
3027         return NULL_TREE;
3028       /* Fall through.  */
3029
3030     case UNION_TYPE:
3031     case ENUMERAL_TYPE:
3032       if (TYPE_TEMPLATE_INFO (t))
3033         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3034                       &find_parameter_packs_r, ppd, ppd->visited);
3035
3036       *walk_subtrees = 0;
3037       return NULL_TREE;
3038
3039     case CONSTRUCTOR:
3040     case TEMPLATE_DECL:
3041       cp_walk_tree (&TREE_TYPE (t),
3042                     &find_parameter_packs_r, ppd, ppd->visited);
3043       return NULL_TREE;
3044  
3045     case TYPENAME_TYPE:
3046       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3047                    ppd, ppd->visited);
3048       *walk_subtrees = 0;
3049       return NULL_TREE;
3050       
3051     case TYPE_PACK_EXPANSION:
3052     case EXPR_PACK_EXPANSION:
3053       *walk_subtrees = 0;
3054       return NULL_TREE;
3055
3056     case INTEGER_TYPE:
3057       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3058                     ppd, ppd->visited);
3059       *walk_subtrees = 0;
3060       return NULL_TREE;
3061
3062     case IDENTIFIER_NODE:
3063       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3064                     ppd->visited);
3065       *walk_subtrees = 0;
3066       return NULL_TREE;
3067
3068     default:
3069       return NULL_TREE;
3070     }
3071
3072   return NULL_TREE;
3073 }
3074
3075 /* Determines if the expression or type T uses any parameter packs.  */
3076 bool
3077 uses_parameter_packs (tree t)
3078 {
3079   tree parameter_packs = NULL_TREE;
3080   struct find_parameter_pack_data ppd;
3081   ppd.parameter_packs = &parameter_packs;
3082   ppd.visited = pointer_set_create ();
3083   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3084   pointer_set_destroy (ppd.visited);
3085   return parameter_packs != NULL_TREE;
3086 }
3087
3088 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3089    representation a base-class initializer into a parameter pack
3090    expansion. If all goes well, the resulting node will be an
3091    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3092    respectively.  */
3093 tree 
3094 make_pack_expansion (tree arg)
3095 {
3096   tree result;
3097   tree parameter_packs = NULL_TREE;
3098   bool for_types = false;
3099   struct find_parameter_pack_data ppd;
3100
3101   if (!arg || arg == error_mark_node)
3102     return arg;
3103
3104   if (TREE_CODE (arg) == TREE_LIST)
3105     {
3106       /* The only time we will see a TREE_LIST here is for a base
3107          class initializer.  In this case, the TREE_PURPOSE will be a
3108          _TYPE node (representing the base class expansion we're
3109          initializing) and the TREE_VALUE will be a TREE_LIST
3110          containing the initialization arguments. 
3111
3112          The resulting expansion looks somewhat different from most
3113          expansions. Rather than returning just one _EXPANSION, we
3114          return a TREE_LIST whose TREE_PURPOSE is a
3115          TYPE_PACK_EXPANSION containing the bases that will be
3116          initialized.  The TREE_VALUE will be identical to the
3117          original TREE_VALUE, which is a list of arguments that will
3118          be passed to each base.  We do not introduce any new pack
3119          expansion nodes into the TREE_VALUE (although it is possible
3120          that some already exist), because the TREE_PURPOSE and
3121          TREE_VALUE all need to be expanded together with the same
3122          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3123          resulting TREE_PURPOSE will mention the parameter packs in
3124          both the bases and the arguments to the bases.  */
3125       tree purpose;
3126       tree value;
3127       tree parameter_packs = NULL_TREE;
3128
3129       /* Determine which parameter packs will be used by the base
3130          class expansion.  */
3131       ppd.visited = pointer_set_create ();
3132       ppd.parameter_packs = &parameter_packs;
3133       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3134                     &ppd, ppd.visited);
3135
3136       if (parameter_packs == NULL_TREE)
3137         {
3138           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3139           pointer_set_destroy (ppd.visited);
3140           return error_mark_node;
3141         }
3142
3143       if (TREE_VALUE (arg) != void_type_node)
3144         {
3145           /* Collect the sets of parameter packs used in each of the
3146              initialization arguments.  */
3147           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3148             {
3149               /* Determine which parameter packs will be expanded in this
3150                  argument.  */
3151               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3152                             &ppd, ppd.visited);
3153             }
3154         }
3155
3156       pointer_set_destroy (ppd.visited);
3157
3158       /* Create the pack expansion type for the base type.  */
3159       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3160       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3161       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3162
3163       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3164          they will rarely be compared to anything.  */
3165       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3166
3167       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3168     }
3169
3170   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3171     for_types = true;
3172
3173   /* Build the PACK_EXPANSION_* node.  */
3174   result = for_types
3175      ? cxx_make_type (TYPE_PACK_EXPANSION)
3176      : make_node (EXPR_PACK_EXPANSION);
3177   SET_PACK_EXPANSION_PATTERN (result, arg);
3178   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3179     {
3180       /* Propagate type and const-expression information.  */
3181       TREE_TYPE (result) = TREE_TYPE (arg);
3182       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3183     }
3184   else
3185     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3186        they will rarely be compared to anything.  */
3187     SET_TYPE_STRUCTURAL_EQUALITY (result);
3188
3189   /* Determine which parameter packs will be expanded.  */
3190   ppd.parameter_packs = &parameter_packs;
3191   ppd.visited = pointer_set_create ();
3192   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3193   pointer_set_destroy (ppd.visited);
3194
3195   /* Make sure we found some parameter packs.  */
3196   if (parameter_packs == NULL_TREE)
3197     {
3198       if (TYPE_P (arg))
3199         error ("expansion pattern %<%T%> contains no argument packs", arg);
3200       else
3201         error ("expansion pattern %<%E%> contains no argument packs", arg);
3202       return error_mark_node;
3203     }
3204   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3205
3206   return result;
3207 }
3208
3209 /* Checks T for any "bare" parameter packs, which have not yet been
3210    expanded, and issues an error if any are found. This operation can
3211    only be done on full expressions or types (e.g., an expression
3212    statement, "if" condition, etc.), because we could have expressions like:
3213
3214      foo(f(g(h(args)))...)
3215
3216    where "args" is a parameter pack. check_for_bare_parameter_packs
3217    should not be called for the subexpressions args, h(args),
3218    g(h(args)), or f(g(h(args))), because we would produce erroneous
3219    error messages. 
3220
3221    Returns TRUE and emits an error if there were bare parameter packs,
3222    returns FALSE otherwise.  */
3223 bool 
3224 check_for_bare_parameter_packs (tree t)
3225 {
3226   tree parameter_packs = NULL_TREE;
3227   struct find_parameter_pack_data ppd;
3228
3229   if (!processing_template_decl || !t || t == error_mark_node)
3230     return false;
3231
3232   if (TREE_CODE (t) == TYPE_DECL)
3233     t = TREE_TYPE (t);
3234
3235   ppd.parameter_packs = &parameter_packs;
3236   ppd.visited = pointer_set_create ();
3237   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3238   pointer_set_destroy (ppd.visited);
3239
3240   if (parameter_packs) 
3241     {
3242       error ("parameter packs not expanded with %<...%>:");
3243       while (parameter_packs)
3244         {
3245           tree pack = TREE_VALUE (parameter_packs);
3246           tree name = NULL_TREE;
3247
3248           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3249               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3250             name = TYPE_NAME (pack);
3251           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3252             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3253           else
3254             name = DECL_NAME (pack);
3255
3256           if (name)
3257             inform (input_location, "        %qD", name);
3258           else
3259             inform (input_location, "        <anonymous>");
3260
3261           parameter_packs = TREE_CHAIN (parameter_packs);
3262         }
3263
3264       return true;
3265     }
3266
3267   return false;
3268 }
3269
3270 /* Expand any parameter packs that occur in the template arguments in
3271    ARGS.  */
3272 tree
3273 expand_template_argument_pack (tree args)
3274 {
3275   tree result_args = NULL_TREE;
3276   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3277   int num_result_args = -1;
3278   int non_default_args_count = -1;
3279
3280   /* First, determine if we need to expand anything, and the number of
3281      slots we'll need.  */
3282   for (in_arg = 0; in_arg < nargs; ++in_arg)
3283     {
3284       tree arg = TREE_VEC_ELT (args, in_arg);
3285       if (arg == NULL_TREE)
3286         return args;
3287       if (ARGUMENT_PACK_P (arg))
3288         {
3289           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3290           if (num_result_args < 0)
3291             num_result_args = in_arg + num_packed;
3292           else
3293             num_result_args += num_packed;
3294         }
3295       else
3296         {
3297           if (num_result_args >= 0)
3298             num_result_args++;
3299         }
3300     }
3301
3302   /* If no expansion is necessary, we're done.  */
3303   if (num_result_args < 0)
3304     return args;
3305
3306   /* Expand arguments.  */
3307   result_args = make_tree_vec (num_result_args);
3308   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3309     non_default_args_count =
3310       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3311   for (in_arg = 0; in_arg < nargs; ++in_arg)
3312     {
3313       tree arg = TREE_VEC_ELT (args, in_arg);
3314       if (ARGUMENT_PACK_P (arg))
3315         {
3316           tree packed = ARGUMENT_PACK_ARGS (arg);
3317           int i, num_packed = TREE_VEC_LENGTH (packed);
3318           for (i = 0; i < num_packed; ++i, ++out_arg)
3319             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3320           if (non_default_args_count > 0)
3321             non_default_args_count += num_packed;
3322         }
3323       else
3324         {
3325           TREE_VEC_ELT (result_args, out_arg) = arg;
3326           ++out_arg;
3327         }
3328     }
3329   if (non_default_args_count >= 0)
3330     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3331   return result_args;
3332 }
3333
3334 /* Checks if DECL shadows a template parameter.
3335
3336    [temp.local]: A template-parameter shall not be redeclared within its
3337    scope (including nested scopes).
3338
3339    Emits an error and returns TRUE if the DECL shadows a parameter,
3340    returns FALSE otherwise.  */
3341
3342 bool
3343 check_template_shadow (tree decl)
3344 {
3345   tree olddecl;
3346
3347   /* If we're not in a template, we can't possibly shadow a template
3348      parameter.  */
3349   if (!current_template_parms)
3350     return true;
3351
3352   /* Figure out what we're shadowing.  */
3353   if (TREE_CODE (decl) == OVERLOAD)
3354     decl = OVL_CURRENT (decl);
3355   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3356
3357   /* If there's no previous binding for this name, we're not shadowing
3358      anything, let alone a template parameter.  */
3359   if (!olddecl)
3360     return true;
3361
3362   /* If we're not shadowing a template parameter, we're done.  Note
3363      that OLDDECL might be an OVERLOAD (or perhaps even an
3364      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3365      node.  */
3366   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3367     return true;
3368
3369   /* We check for decl != olddecl to avoid bogus errors for using a
3370      name inside a class.  We check TPFI to avoid duplicate errors for
3371      inline member templates.  */
3372   if (decl == olddecl
3373       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3374     return true;
3375
3376   error ("declaration of %q+#D", decl);
3377   error (" shadows template parm %q+#D", olddecl);
3378   return false;
3379 }
3380
3381 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3382    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3383    template parameters.  */
3384
3385 static tree
3386 build_template_parm_index (int index,
3387                            int level,
3388                            int orig_level,
3389                            int num_siblings,
3390                            tree decl,
3391                            tree type)
3392 {
3393   tree t = make_node (TEMPLATE_PARM_INDEX);
3394   TEMPLATE_PARM_IDX (t) = index;
3395   TEMPLATE_PARM_LEVEL (t) = level;
3396   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3397   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3398   TEMPLATE_PARM_DECL (t) = decl;
3399   TREE_TYPE (t) = type;
3400   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3401   TREE_READONLY (t) = TREE_READONLY (decl);
3402
3403   return t;
3404 }
3405
3406 /* Find the canonical type parameter for the given template type
3407    parameter.  Returns the canonical type parameter, which may be TYPE
3408    if no such parameter existed.  */
3409
3410 static tree
3411 canonical_type_parameter (tree type)
3412 {
3413   tree list;
3414   int idx = TEMPLATE_TYPE_IDX (type);
3415   if (!canonical_template_parms)
3416     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3417
3418   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3419     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3420
3421   list = VEC_index (tree, canonical_template_parms, idx);
3422   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3423     list = TREE_CHAIN (list);
3424
3425   if (list)
3426     return TREE_VALUE (list);
3427   else
3428     {
3429       VEC_replace(tree, canonical_template_parms, idx,
3430                   tree_cons (NULL_TREE, type, 
3431                              VEC_index (tree, canonical_template_parms, idx)));
3432       return type;
3433     }
3434 }
3435
3436 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3437    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3438    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3439    new one is created.  */
3440
3441 static tree
3442 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3443                             tsubst_flags_t complain)
3444 {
3445   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3446       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3447           != TEMPLATE_PARM_LEVEL (index) - levels)
3448       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3449     {
3450       tree orig_decl = TEMPLATE_PARM_DECL (index);
3451       tree decl, t;
3452
3453       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3454                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3455       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3456       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3457       DECL_ARTIFICIAL (decl) = 1;
3458       SET_DECL_TEMPLATE_PARM_P (decl);
3459
3460       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3461                                      TEMPLATE_PARM_LEVEL (index) - levels,
3462                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3463                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3464                                      decl, type);
3465       TEMPLATE_PARM_DESCENDANTS (index) = t;
3466       TEMPLATE_PARM_PARAMETER_PACK (t) 
3467         = TEMPLATE_PARM_PARAMETER_PACK (index);
3468
3469         /* Template template parameters need this.  */
3470       if (TREE_CODE (decl) == TEMPLATE_DECL)
3471         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3472           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3473            args, complain);
3474     }
3475
3476   return TEMPLATE_PARM_DESCENDANTS (index);
3477 }
3478
3479 /* Process information from new template parameter PARM and append it
3480    to the LIST being built.  This new parameter is a non-type
3481    parameter iff IS_NON_TYPE is true. This new parameter is a
3482    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3483    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3484    parameter list PARM belongs to. This is used used to create a
3485    proper canonical type for the type of PARM that is to be created,
3486    iff PARM is a type.  If the size is not known, this parameter shall
3487    be set to 0.  */
3488
3489 tree
3490 process_template_parm (tree list, location_t parm_loc, tree parm,
3491                        bool is_non_type, bool is_parameter_pack,
3492                        unsigned num_template_parms)
3493 {
3494   tree decl = 0;
3495   tree defval;
3496   tree err_parm_list;
3497   int idx = 0;
3498
3499   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3500   defval = TREE_PURPOSE (parm);
3501
3502   if (list)
3503     {
3504       tree p = tree_last (list);
3505
3506       if (p && TREE_VALUE (p) != error_mark_node)
3507         {
3508           p = TREE_VALUE (p);
3509           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3510             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3511           else
3512             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3513         }
3514
3515       ++idx;
3516     }
3517   else
3518     idx = 0;
3519
3520   if (is_non_type)
3521     {
3522       parm = TREE_VALUE (parm);
3523
3524       SET_DECL_TEMPLATE_PARM_P (parm);
3525
3526       if (TREE_TYPE (parm) == error_mark_node)
3527         {
3528           err_parm_list = build_tree_list (defval, parm);
3529           TREE_VALUE (err_parm_list) = error_mark_node;
3530            return chainon (list, err_parm_list);
3531         }
3532       else
3533       {
3534         /* [temp.param]
3535
3536            The top-level cv-qualifiers on the template-parameter are
3537            ignored when determining its type.  */
3538         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3539         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3540           {
3541             err_parm_list = build_tree_list (defval, parm);
3542             TREE_VALUE (err_parm_list) = error_mark_node;
3543              return chainon (list, err_parm_list);
3544           }
3545
3546         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3547           {
3548             /* This template parameter is not a parameter pack, but it
3549                should be. Complain about "bare" parameter packs.  */
3550             check_for_bare_parameter_packs (TREE_TYPE (parm));
3551             
3552             /* Recover by calling this a parameter pack.  */
3553             is_parameter_pack = true;
3554           }
3555       }
3556
3557       /* A template parameter is not modifiable.  */
3558       TREE_CONSTANT (parm) = 1;
3559       TREE_READONLY (parm) = 1;
3560       decl = build_decl (parm_loc,
3561                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3562       TREE_CONSTANT (decl) = 1;
3563       TREE_READONLY (decl) = 1;
3564       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3565         = build_template_parm_index (idx, processing_template_decl,
3566                                      processing_template_decl,
3567                                      num_template_parms,
3568                                      decl, TREE_TYPE (parm));
3569
3570       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3571         = is_parameter_pack;
3572     }
3573   else
3574     {
3575       tree t;
3576       parm = TREE_VALUE (TREE_VALUE (parm));
3577
3578       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3579         {
3580           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3581           /* This is for distinguishing between real templates and template
3582              template parameters */
3583           TREE_TYPE (parm) = t;
3584           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3585           decl = parm;
3586         }
3587       else
3588         {
3589           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3590           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3591           decl = build_decl (parm_loc,
3592                              TYPE_DECL, parm, t);
3593         }
3594
3595       TYPE_NAME (t) = decl;
3596       TYPE_STUB_DECL (t) = decl;
3597       parm = decl;
3598       TEMPLATE_TYPE_PARM_INDEX (t)
3599         = build_template_parm_index (idx, processing_template_decl,
3600                                      processing_template_decl,
3601                                      num_template_parms,
3602                                      decl, TREE_TYPE (parm));
3603       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3604       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3605     }
3606   DECL_ARTIFICIAL (decl) = 1;
3607   SET_DECL_TEMPLATE_PARM_P (decl);
3608   pushdecl (decl);
3609   parm = build_tree_list (defval, parm);
3610   return chainon (list, parm);
3611 }
3612
3613 /* The end of a template parameter list has been reached.  Process the
3614    tree list into a parameter vector, converting each parameter into a more
3615    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3616    as PARM_DECLs.  */
3617
3618 tree
3619 end_template_parm_list (tree parms)
3620 {
3621   int nparms;
3622   tree parm, next;
3623   tree saved_parmlist = make_tree_vec (list_length (parms));
3624
3625   current_template_parms
3626     = tree_cons (size_int (processing_template_decl),
3627                  saved_parmlist, current_template_parms);
3628
3629   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3630     {
3631       next = TREE_CHAIN (parm);
3632       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3633       TREE_CHAIN (parm) = NULL_TREE;
3634     }
3635
3636   --processing_template_parmlist;
3637
3638   return saved_parmlist;
3639 }
3640
3641 /* Create a new type almost identical to TYPE but which has the
3642    following differences:
3643
3644      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3645      template sibling parameters of T.
3646
3647      2/ T has a new canonical type that matches the new number
3648      of sibling parms.
3649
3650      3/ From now on, T is going to be what lookups referring to the
3651      name of TYPE will return. No lookup should return TYPE anymore.
3652
3653    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3654
3655    This is a subroutine of fixup_template_parms.  */
3656
3657 static tree
3658 fixup_template_type_parm_type (tree type, int num_parms)
3659 {
3660   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3661   tree t;
3662   /* This is the decl which name is inserted into the symbol table for
3663      the template parm type. So whenever we lookup the type name, this
3664      is the DECL we get.  */
3665   tree decl;
3666
3667   /* Do not fix up the type twice.  */
3668   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3669     return type;
3670
3671   t = copy_type (type);
3672   decl = TYPE_NAME (t);
3673
3674   TYPE_MAIN_VARIANT (t) = t;
3675   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3676   TYPE_POINTER_TO (t) = 0;
3677   TYPE_REFERENCE_TO (t) = 0;
3678
3679   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3680                                    TEMPLATE_PARM_LEVEL (orig_idx),
3681                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3682                                    num_parms,
3683                                    decl, t);
3684   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3685   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3686   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3687
3688   TYPE_STUB_DECL (t) = decl;
3689   TEMPLATE_TYPE_DECL (t) = decl;
3690   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3691     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3692
3693   /* Update the type associated to the type name stored in the symbol
3694      table. Now, whenever the type name is looked up, the resulting
3695      type is properly fixed up.  */
3696   TREE_TYPE (decl) = t;
3697
3698   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3699
3700   return t;
3701 }
3702
3703 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3704    identical to I, but that is fixed up as to:
3705
3706    1/ carry the number of sibling parms (NUM_PARMS) of the template
3707    parm represented by I.
3708
3709    2/ replace all references to template parm types declared before I
3710    (in the same template parm list as I) by references to template
3711    parm types contained in ARGS. ARGS should contain the list of
3712    template parms that have been fixed up so far, in a form suitable
3713    to be passed to tsubst.
3714
3715    This is a subroutine of fixup_template_parms.  */
3716
3717 static tree
3718 fixup_template_parm_index (tree i, tree args, int num_parms)
3719 {
3720   tree index, decl, type;
3721
3722   if (i == NULL_TREE
3723       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3724       /* Do not fix up the index twice.  */
3725       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3726     return i;
3727
3728   decl = TEMPLATE_PARM_DECL (i);
3729   type = TREE_TYPE (decl);
3730
3731   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3732                                      TEMPLATE_PARM_LEVEL (i),
3733                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3734                                      num_parms,
3735                                      decl, type);
3736
3737   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3738   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3739
3740   type = tsubst (type, args, tf_none, NULL_TREE);
3741   
3742   TREE_TYPE (decl) = type;
3743   TREE_TYPE (index) = type;
3744
3745   return index;
3746 }
3747
3748 /* 
3749    This is a subroutine of fixup_template_parms.
3750
3751    It computes the canonical type of the type of the template
3752    parameter PARM_DESC and update all references to that type so that
3753    they use the newly computed canonical type. No access check is
3754    performed during the fixup. PARM_DESC is a TREE_LIST which
3755    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3756    default argument of the template parm if any. IDX is the index of
3757    the template parameter, starting at 0. NUM_PARMS is the number of
3758    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3759    TREE_VEC containing the full set of template parameters in a form
3760    suitable to be passed to substs functions as their ARGS
3761    argument. This is what current_template_args returns for a given
3762    template. The innermost vector of args in ARGLIST is the set of
3763    template parms that have been fixed up so far. This function adds
3764    the fixed up parameter into that vector.  */
3765
3766 static void
3767 fixup_template_parm (tree parm_desc,
3768                      int idx,
3769                      int num_parms,
3770                      tree arglist)
3771 {
3772   tree parm = TREE_VALUE (parm_desc);
3773   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3774
3775   push_deferring_access_checks (dk_no_check);
3776
3777   if (TREE_CODE (parm) == TYPE_DECL)
3778     {
3779       /* PARM is a template type parameter. Fix up its type, add
3780          the fixed-up template parm to the vector of fixed-up
3781          template parms so far, and substitute the fixed-up
3782          template parms into the default argument of this
3783          parameter.  */
3784       tree t =
3785         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3786       TREE_TYPE (parm) = t;
3787
3788       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3789     }
3790   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3791     {
3792       /* PARM is a template template parameter. This is going to
3793          be interesting.  */
3794       tree tparms, targs, innermost_args, t;
3795       int j;
3796
3797       /* First, fix up the parms of the template template parm
3798          because the parms are involved in defining the new canonical
3799          type of the template template parm.  */
3800
3801       /* So we need to substitute the template parm types that have
3802          been fixed up so far into the template parms of this template
3803          template parm. E.g, consider this:
3804
3805          template<class T, template<T u> class TT> class S;
3806
3807          In this case we want to substitute T into the
3808          template parameters of TT.
3809
3810          So let's walk the template parms of PARM here, and
3811          tsubst ARGLIST into into each of the template
3812          parms.   */
3813
3814       /* For this substitution we need to build the full set of
3815          template parameters and use that as arguments for the
3816          tsubsting function.  */
3817       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3818
3819       /* This will contain the innermost parms of PARM into which
3820          we have substituted so far.  */
3821       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3822       targs = add_to_template_args (arglist, innermost_args);
3823       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3824         {
3825           tree parameter;
3826
3827           parameter = TREE_VEC_ELT (tparms, j);
3828
3829           /* INNERMOST_ARGS needs to have at least the same number
3830              of elements as the index PARAMETER, ortherwise
3831              tsubsting into PARAMETER will result in partially
3832              instantiating it, reducing its tempate parm
3833              level. Let's tactically fill INNERMOST_ARGS for that
3834              purpose.  */
3835           TREE_VEC_ELT (innermost_args, j) =
3836             template_parm_to_arg (parameter);
3837
3838           fixup_template_parm (parameter, j,
3839                                TREE_VEC_LENGTH (tparms),
3840                                targs);
3841         }
3842
3843       /* Now fix up the type of the template template parm.  */
3844
3845       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3846       TREE_TYPE (parm) = t;
3847
3848       TREE_VEC_ELT (fixedup_args, idx) =
3849         template_parm_to_arg (parm_desc);
3850     }
3851   else if (TREE_CODE (parm) == PARM_DECL)
3852     {
3853       /* PARM is a non-type template parameter. We need to:
3854
3855        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3856        proper number of sibling parameters.
3857
3858        * Make lookups of the template parameter return a reference
3859        to the fixed-up index. No lookup should return references
3860        to the former index anymore.
3861
3862        * Substitute the template parms that got fixed up so far
3863
3864        * into the type of PARM.  */
3865
3866       tree index = DECL_INITIAL (parm);
3867
3868       /* PUSHED_DECL is the decl added to the symbol table with
3869          the name of the parameter. E,g:
3870              
3871          template<class T, T u> //#0
3872          auto my_function(T t) -> decltype(u); //#1
3873
3874          Here, when looking up u at //#1, we get the decl of u
3875          resulting from the declaration in #0. This is what
3876          PUSHED_DECL is. We need to replace the reference to the
3877          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3878          fixed-up TEMPLATE_PARM_INDEX.  */
3879       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3880
3881       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3882          fixup the type of PUSHED_DECL as well and luckily
3883          fixup_template_parm_index does it for us too.  */
3884       tree fixed_up_index =
3885         fixup_template_parm_index (index, arglist, num_parms);
3886
3887       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3888
3889       /* Add this fixed up PARM to the template parms we've fixed
3890          up so far and use that to substitute the fixed-up
3891          template parms into the type of PARM.  */
3892       TREE_VEC_ELT (fixedup_args, idx) =
3893         template_parm_to_arg (parm_desc);
3894       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3895                                  tf_none, NULL_TREE);
3896     }
3897
3898   TREE_PURPOSE (parm_desc) =
3899     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3900                          arglist, tf_none, parm);
3901
3902   pop_deferring_access_checks ();
3903 }
3904
3905 /* Walk the current template parms and properly compute the canonical
3906    types of the dependent types created during
3907    cp_parser_template_parameter_list.  */
3908
3909 void
3910 fixup_template_parms (void)
3911 {
3912   tree arglist;
3913   tree parameter_vec;
3914   tree fixedup_args;
3915   int i, num_parms;
3916
3917   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3918   if (parameter_vec == NULL_TREE)
3919     return;
3920
3921   num_parms = TREE_VEC_LENGTH (parameter_vec);
3922
3923   /* This vector contains the current innermost template parms that
3924      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3925      to be passed to tsubst* functions as their ARGS argument.  */
3926   fixedup_args = make_tree_vec (num_parms);
3927
3928   /* This vector contains the full set of template parms in a form
3929      suitable to be passed to substs functions as their ARGS
3930      argument.  */
3931   arglist = current_template_args ();
3932   arglist = add_outermost_template_args (arglist, fixedup_args);
3933
3934   /* Let's do the proper fixup now.  */
3935   for (i = 0; i < num_parms; ++i)
3936     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3937                          i, num_parms, arglist);
3938 }
3939
3940 /* end_template_decl is called after a template declaration is seen.  */
3941
3942 void
3943 end_template_decl (void)
3944 {
3945   reset_specialization ();
3946
3947   if (! processing_template_decl)
3948     return;
3949
3950   /* This matches the pushlevel in begin_template_parm_list.  */
3951   finish_scope ();
3952
3953   --processing_template_decl;
3954   current_template_parms = TREE_CHAIN (current_template_parms);
3955 }
3956
3957 /* Takes a TREE_LIST representing a template parameter and convert it
3958    into an argument suitable to be passed to the type substitution
3959    functions.  Note that If the TREE_LIST contains an error_mark
3960    node, the returned argument is error_mark_node.  */
3961
3962 static tree
3963 template_parm_to_arg (tree t)
3964 {
3965
3966   if (t == NULL_TREE
3967       || TREE_CODE (t) != TREE_LIST)
3968     return t;
3969
3970   if (error_operand_p (TREE_VALUE (t)))
3971     return error_mark_node;
3972
3973   t = TREE_VALUE (t);
3974
3975   if (TREE_CODE (t) == TYPE_DECL
3976       || TREE_CODE (t) == TEMPLATE_DECL)
3977     {
3978       t = TREE_TYPE (t);
3979
3980       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3981         {
3982           /* Turn this argument into a TYPE_ARGUMENT_PACK
3983              with a single element, which expands T.  */
3984           tree vec = make_tree_vec (1);
3985 #ifdef ENABLE_CHECKING
3986           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3987             (vec, TREE_VEC_LENGTH (vec));
3988 #endif
3989           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3990
3991           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3992           SET_ARGUMENT_PACK_ARGS (t, vec);
3993         }
3994     }
3995   else
3996     {
3997       t = DECL_INITIAL (t);
3998
3999       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4000         {
4001           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4002              with a single element, which expands T.  */
4003           tree vec = make_tree_vec (1);
4004           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
4005 #ifdef ENABLE_CHECKING
4006           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
4007             (vec, TREE_VEC_LENGTH (vec));
4008 #endif
4009           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4010
4011           t  = make_node (NONTYPE_ARGUMENT_PACK);
4012           SET_ARGUMENT_PACK_ARGS (t, vec);
4013           TREE_TYPE (t) = type;
4014         }
4015     }
4016   return t;
4017 }
4018
4019 /* This function returns TRUE if PARM_PACK is a template parameter
4020    pack and if ARG_PACK is what template_parm_to_arg returned when
4021    passed PARM_PACK.  */
4022
4023 static bool
4024 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
4025 {
4026   /* For clarity in the comments below let's use the representation
4027      argument_pack<elements>' to denote an argument pack and its
4028      elements.
4029
4030      In the 'if' block below, we want to detect cases where
4031      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
4032      check if ARG_PACK is an argument pack which sole element is
4033      the expansion of PARM_PACK.  That argument pack is typically
4034      created by template_parm_to_arg when passed a parameter
4035      pack.  */
4036
4037   if (arg_pack
4038       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
4039       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
4040     {
4041       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
4042       tree pattern = PACK_EXPANSION_PATTERN (expansion);
4043       /* So we have an argument_pack<P...>.  We want to test if P
4044          is actually PARM_PACK.  We will not use cp_tree_equal to
4045          test P and PARM_PACK because during type fixup (by
4046          fixup_template_parm) P can be a pre-fixup version of a
4047          type and PARM_PACK be its post-fixup version.
4048          cp_tree_equal would consider them as different even
4049          though we would want to consider them compatible for our
4050          precise purpose here.
4051
4052          Thus we are going to consider that P and PARM_PACK are
4053          compatible if they have the same DECL.  */
4054       if ((/* If ARG_PACK is a type parameter pack named by the
4055               same DECL as parm_pack ...  */
4056            (TYPE_P (pattern)
4057             && TYPE_P (parm_pack)
4058             && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
4059            /* ... or if PARM_PACK is a non-type parameter named by the
4060               same DECL as ARG_PACK.  Note that PARM_PACK being a
4061               non-type parameter means it's either a PARM_DECL or a
4062               TEMPLATE_PARM_INDEX.  */
4063            || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
4064                && ((TREE_CODE (parm_pack) == PARM_DECL
4065                     && (TEMPLATE_PARM_DECL (pattern)
4066                         == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
4067                    || (TREE_CODE (parm_pack) == TEMPLATE_PARM_INDEX
4068                        && (TEMPLATE_PARM_DECL (pattern)
4069                            == TEMPLATE_PARM_DECL (parm_pack))))))
4070           && template_parameter_pack_p (pattern))
4071         return true;
4072     }
4073   return false;
4074 }
4075
4076 /* Within the declaration of a template, return all levels of template
4077    parameters that apply.  The template parameters are represented as
4078    a TREE_VEC, in the form documented in cp-tree.h for template
4079    arguments.  */
4080
4081 static tree
4082 current_template_args (void)
4083 {
4084   tree header;
4085   tree args = NULL_TREE;
4086   int length = TMPL_PARMS_DEPTH (current_template_parms);
4087   int l = length;
4088
4089   /* If there is only one level of template parameters, we do not
4090      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4091      TREE_VEC containing the arguments.  */
4092   if (length > 1)
4093     args = make_tree_vec (length);
4094
4095   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4096     {
4097       tree a = copy_node (TREE_VALUE (header));
4098       int i;
4099
4100       TREE_TYPE (a) = NULL_TREE;
4101       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4102         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4103
4104 #ifdef ENABLE_CHECKING
4105       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4106 #endif
4107
4108       if (length > 1)
4109         TREE_VEC_ELT (args, --l) = a;
4110       else
4111         args = a;
4112     }
4113
4114     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4115       /* This can happen for template parms of a template template
4116          parameter, e.g:
4117
4118          template<template<class T, class U> class TT> struct S;
4119
4120          Consider the level of the parms of TT; T and U both have
4121          level 2; TT has no template parm of level 1. So in this case
4122          the first element of full_template_args is NULL_TREE. If we
4123          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4124          of 2. This will make tsubst wrongly consider that T and U
4125          have level 1. Instead, let's create a dummy vector as the
4126          first element of full_template_args so that TMPL_ARG_DEPTH
4127          returns the correct depth for args.  */
4128       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4129   return args;
4130 }
4131
4132 /* Update the declared TYPE by doing any lookups which were thought to be
4133    dependent, but are not now that we know the SCOPE of the declarator.  */
4134
4135 tree
4136 maybe_update_decl_type (tree orig_type, tree scope)
4137 {
4138   tree type = orig_type;
4139
4140   if (type == NULL_TREE)
4141     return type;
4142
4143   if (TREE_CODE (orig_type) == TYPE_DECL)
4144     type = TREE_TYPE (type);
4145
4146   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4147       && dependent_type_p (type)
4148       /* Don't bother building up the args in this case.  */
4149       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4150     {
4151       /* tsubst in the args corresponding to the template parameters,
4152          including auto if present.  Most things will be unchanged, but
4153          make_typename_type and tsubst_qualified_id will resolve
4154          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4155       tree args = current_template_args ();
4156       tree auto_node = type_uses_auto (type);
4157       tree pushed;
4158       if (auto_node)
4159         {
4160           tree auto_vec = make_tree_vec (1);
4161           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4162           args = add_to_template_args (args, auto_vec);
4163         }
4164       pushed = push_scope (scope);
4165       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4166       if (pushed)
4167         pop_scope (scope);
4168     }
4169
4170   if (type == error_mark_node)
4171     return orig_type;
4172
4173   if (TREE_CODE (orig_type) == TYPE_DECL)
4174     {
4175       if (same_type_p (type, TREE_TYPE (orig_type)))
4176         type = orig_type;
4177       else
4178         type = TYPE_NAME (type);
4179     }
4180   return type;
4181 }
4182
4183 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4184    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4185    a member template.  Used by push_template_decl below.  */
4186
4187 static tree
4188 build_template_decl (tree decl, tree parms, bool member_template_p)
4189 {
4190   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4191   DECL_TEMPLATE_PARMS (tmpl) = parms;
4192   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4193   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4194   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4195
4196   return tmpl;
4197 }
4198
4199 struct template_parm_data
4200 {
4201   /* The level of the template parameters we are currently
4202      processing.  */
4203   int level;
4204
4205   /* The index of the specialization argument we are currently
4206      processing.  */
4207   int current_arg;
4208
4209   /* An array whose size is the number of template parameters.  The
4210      elements are nonzero if the parameter has been used in any one
4211      of the arguments processed so far.  */
4212   int* parms;
4213
4214   /* An array whose size is the number of template arguments.  The
4215      elements are nonzero if the argument makes use of template
4216      parameters of this level.  */
4217   int* arg_uses_template_parms;
4218 };
4219
4220 /* Subroutine of push_template_decl used to see if each template
4221    parameter in a partial specialization is used in the explicit
4222    argument list.  If T is of the LEVEL given in DATA (which is
4223    treated as a template_parm_data*), then DATA->PARMS is marked
4224    appropriately.  */
4225
4226 static int
4227 mark_template_parm (tree t, void* data)
4228 {
4229   int level;
4230   int idx;
4231   struct template_parm_data* tpd = (struct template_parm_data*) data;
4232
4233   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4234     {
4235       level = TEMPLATE_PARM_LEVEL (t);
4236       idx = TEMPLATE_PARM_IDX (t);
4237     }
4238   else
4239     {
4240       level = TEMPLATE_TYPE_LEVEL (t);
4241       idx = TEMPLATE_TYPE_IDX (t);
4242     }
4243
4244   if (level == tpd->level)
4245     {
4246       tpd->parms[idx] = 1;
4247       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4248     }
4249
4250   /* Return zero so that for_each_template_parm will continue the
4251      traversal of the tree; we want to mark *every* template parm.  */
4252   return 0;
4253 }
4254
4255 /* Process the partial specialization DECL.  */
4256
4257 static tree
4258 process_partial_specialization (tree decl)
4259 {
4260   tree type = TREE_TYPE (decl);
4261   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4262   tree specargs = CLASSTYPE_TI_ARGS (type);
4263   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4264   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4265   tree inner_parms;
4266   tree inst;
4267   int nargs = TREE_VEC_LENGTH (inner_args);
4268   int ntparms;
4269   int  i;
4270   bool did_error_intro = false;
4271   struct template_parm_data tpd;
4272   struct template_parm_data tpd2;
4273
4274   gcc_assert (current_template_parms);
4275
4276   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4277   ntparms = TREE_VEC_LENGTH (inner_parms);
4278
4279   /* We check that each of the template parameters given in the
4280      partial specialization is used in the argument list to the
4281      specialization.  For example:
4282
4283        template <class T> struct S;
4284        template <class T> struct S<T*>;
4285
4286      The second declaration is OK because `T*' uses the template
4287      parameter T, whereas
4288
4289        template <class T> struct S<int>;
4290
4291      is no good.  Even trickier is:
4292
4293        template <class T>
4294        struct S1
4295        {
4296           template <class U>
4297           struct S2;
4298           template <class U>
4299           struct S2<T>;
4300        };
4301
4302      The S2<T> declaration is actually invalid; it is a
4303      full-specialization.  Of course,
4304
4305           template <class U>
4306           struct S2<T (*)(U)>;
4307
4308      or some such would have been OK.  */
4309   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4310   tpd.parms = XALLOCAVEC (int, ntparms);
4311   memset (tpd.parms, 0, sizeof (int) * ntparms);
4312
4313   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4314   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4315   for (i = 0; i < nargs; ++i)
4316     {
4317       tpd.current_arg = i;
4318       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4319                               &mark_template_parm,
4320                               &tpd,
4321                               NULL,
4322                               /*include_nondeduced_p=*/false);
4323     }
4324   for (i = 0; i < ntparms; ++i)
4325     if (tpd.parms[i] == 0)
4326       {
4327         /* One of the template parms was not used in the
4328            specialization.  */
4329         if (!did_error_intro)
4330           {
4331             error ("template parameters not used in partial specialization:");
4332             did_error_intro = true;
4333           }
4334
4335         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4336       }
4337
4338   if (did_error_intro)
4339     return error_mark_node;
4340
4341   /* [temp.class.spec]
4342
4343      The argument list of the specialization shall not be identical to
4344      the implicit argument list of the primary template.  */
4345   if (comp_template_args
4346       (inner_args,
4347        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4348                                                    (maintmpl)))))
4349     error ("partial specialization %qT does not specialize any template arguments", type);
4350
4351   /* [temp.class.spec]
4352
4353      A partially specialized non-type argument expression shall not
4354      involve template parameters of the partial specialization except
4355      when the argument expression is a simple identifier.
4356
4357      The type of a template parameter corresponding to a specialized
4358      non-type argument shall not be dependent on a parameter of the
4359      specialization. 
4360
4361      Also, we verify that pack expansions only occur at the
4362      end of the argument list.  */
4363   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4364   tpd2.parms = 0;
4365   for (i = 0; i < nargs; ++i)
4366     {
4367       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4368       tree arg = TREE_VEC_ELT (inner_args, i);
4369       tree packed_args = NULL_TREE;
4370       int j, len = 1;
4371
4372       if (ARGUMENT_PACK_P (arg))
4373         {
4374           /* Extract the arguments from the argument pack. We'll be
4375              iterating over these in the following loop.  */
4376           packed_args = ARGUMENT_PACK_ARGS (arg);
4377           len = TREE_VEC_LENGTH (packed_args);
4378         }
4379
4380       for (j = 0; j < len; j++)
4381         {
4382           if (packed_args)
4383             /* Get the Jth argument in the parameter pack.  */
4384             arg = TREE_VEC_ELT (packed_args, j);
4385
4386           if (PACK_EXPANSION_P (arg))
4387             {
4388               /* Pack expansions must come at the end of the
4389                  argument list.  */
4390               if ((packed_args && j < len - 1)
4391                   || (!packed_args && i < nargs - 1))
4392                 {
4393                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4394                     error ("parameter pack argument %qE must be at the "
4395                            "end of the template argument list", arg);
4396                   else
4397                     error ("parameter pack argument %qT must be at the "
4398                            "end of the template argument list", arg);
4399                 }
4400             }
4401
4402           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4403             /* We only care about the pattern.  */
4404             arg = PACK_EXPANSION_PATTERN (arg);
4405
4406           if (/* These first two lines are the `non-type' bit.  */
4407               !TYPE_P (arg)
4408               && TREE_CODE (arg) != TEMPLATE_DECL
4409               /* This next line is the `argument expression is not just a
4410                  simple identifier' condition and also the `specialized
4411                  non-type argument' bit.  */
4412               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4413             {
4414               if ((!packed_args && tpd.arg_uses_template_parms[i])
4415                   || (packed_args && uses_template_parms (arg)))
4416                 error ("template argument %qE involves template parameter(s)",
4417                        arg);
4418               else 
4419                 {
4420                   /* Look at the corresponding template parameter,
4421                      marking which template parameters its type depends
4422                      upon.  */
4423                   tree type = TREE_TYPE (parm);
4424
4425                   if (!tpd2.parms)
4426                     {
4427                       /* We haven't yet initialized TPD2.  Do so now.  */
4428                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4429                       /* The number of parameters here is the number in the
4430                          main template, which, as checked in the assertion
4431                          above, is NARGS.  */
4432                       tpd2.parms = XALLOCAVEC (int, nargs);
4433                       tpd2.level = 
4434                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4435                     }
4436
4437                   /* Mark the template parameters.  But this time, we're
4438                      looking for the template parameters of the main
4439                      template, not in the specialization.  */
4440                   tpd2.current_arg = i;
4441                   tpd2.arg_uses_template_parms[i] = 0;
4442                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4443                   for_each_template_parm (type,
4444                                           &mark_template_parm,
4445                                           &tpd2,
4446                                           NULL,
4447                                           /*include_nondeduced_p=*/false);
4448
4449                   if (tpd2.arg_uses_template_parms [i])
4450                     {
4451                       /* The type depended on some template parameters.
4452                          If they are fully specialized in the
4453                          specialization, that's OK.  */
4454                       int j;
4455                       int count = 0;
4456                       for (j = 0; j < nargs; ++j)
4457                         if (tpd2.parms[j] != 0
4458                             && tpd.arg_uses_template_parms [j])
4459                           ++count;
4460                       if (count != 0)
4461                         error_n (input_location, count,
4462                                  "type %qT of template argument %qE depends "
4463                                  "on a template parameter",
4464                                  "type %qT of template argument %qE depends "
4465                                  "on template parameters",
4466                                  type,
4467                                  arg);
4468                     }
4469                 }
4470             }
4471         }
4472     }
4473
4474   /* We should only get here once.  */
4475   gcc_assert (!COMPLETE_TYPE_P (type));
4476
4477   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4478     = tree_cons (specargs, inner_parms,
4479                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4480   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4481
4482   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4483        inst = TREE_CHAIN (inst))
4484     {
4485       tree inst_type = TREE_VALUE (inst);
4486       if (COMPLETE_TYPE_P (inst_type)
4487           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4488         {
4489           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4490           if (spec && TREE_TYPE (spec) == type)
4491             permerror (input_location,
4492                        "partial specialization of %qT after instantiation "
4493                        "of %qT", type, inst_type);
4494         }
4495     }
4496
4497   return decl;
4498 }
4499
4500 /* Check that a template declaration's use of default arguments and
4501    parameter packs is not invalid.  Here, PARMS are the template
4502    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4503    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4504    specialization.
4505    
4506
4507    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4508    declaration (but not a definition); 1 indicates a declaration, 2
4509    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4510    emitted for extraneous default arguments.
4511
4512    Returns TRUE if there were no errors found, FALSE otherwise. */
4513
4514 bool
4515 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4516                          int is_partial, int is_friend_decl)
4517 {
4518   const char *msg;
4519   int last_level_to_check;
4520   tree parm_level;
4521   bool no_errors = true;
4522
4523   /* [temp.param]
4524
4525      A default template-argument shall not be specified in a
4526      function template declaration or a function template definition, nor
4527      in the template-parameter-list of the definition of a member of a
4528      class template.  */
4529
4530   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4531     /* You can't have a function template declaration in a local
4532        scope, nor you can you define a member of a class template in a
4533        local scope.  */
4534     return true;
4535
4536   if (current_class_type
4537       && !TYPE_BEING_DEFINED (current_class_type)
4538       && DECL_LANG_SPECIFIC (decl)
4539       && DECL_DECLARES_FUNCTION_P (decl)
4540       /* If this is either a friend defined in the scope of the class
4541          or a member function.  */
4542       && (DECL_FUNCTION_MEMBER_P (decl)
4543           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4544           : DECL_FRIEND_CONTEXT (decl)
4545           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4546           : false)
4547       /* And, if it was a member function, it really was defined in
4548          the scope of the class.  */
4549       && (!DECL_FUNCTION_MEMBER_P (decl)
4550           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4551     /* We already checked these parameters when the template was
4552        declared, so there's no need to do it again now.  This function
4553        was defined in class scope, but we're processing it's body now
4554        that the class is complete.  */
4555     return true;
4556
4557   /* Core issue 226 (C++0x only): the following only applies to class
4558      templates.  */
4559   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4560     {
4561       /* [temp.param]
4562
4563          If a template-parameter has a default template-argument, all
4564          subsequent template-parameters shall have a default
4565          template-argument supplied.  */
4566       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4567         {
4568           tree inner_parms = TREE_VALUE (parm_level);
4569           int ntparms = TREE_VEC_LENGTH (inner_parms);
4570           int seen_def_arg_p = 0;
4571           int i;
4572
4573           for (i = 0; i < ntparms; ++i)
4574             {
4575               tree parm = TREE_VEC_ELT (inner_parms, i);
4576
4577               if (parm == error_mark_node)
4578                 continue;
4579
4580               if (TREE_PURPOSE (parm))
4581                 seen_def_arg_p = 1;
4582               else if (seen_def_arg_p
4583                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4584                 {
4585                   error ("no default argument for %qD", TREE_VALUE (parm));
4586                   /* For better subsequent error-recovery, we indicate that
4587                      there should have been a default argument.  */
4588                   TREE_PURPOSE (parm) = error_mark_node;
4589                   no_errors = false;
4590                 }
4591               else if (is_primary
4592                        && !is_partial
4593                        && !is_friend_decl
4594                        /* Don't complain about an enclosing partial
4595                           specialization.  */
4596                        && parm_level == parms
4597                        && TREE_CODE (decl) == TYPE_DECL
4598                        && i < ntparms - 1
4599                        && template_parameter_pack_p (TREE_VALUE (parm)))
4600                 {
4601                   /* A primary class template can only have one
4602                      parameter pack, at the end of the template
4603                      parameter list.  */
4604
4605                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4606                     error ("parameter pack %qE must be at the end of the"
4607                            " template parameter list", TREE_VALUE (parm));
4608                   else
4609                     error ("parameter pack %qT must be at the end of the"
4610                            " template parameter list", 
4611                            TREE_TYPE (TREE_VALUE (parm)));
4612
4613                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4614                     = error_mark_node;
4615                   no_errors = false;
4616                 }
4617             }
4618         }
4619     }
4620
4621   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4622       || is_partial 
4623       || !is_primary
4624       || is_friend_decl)
4625     /* For an ordinary class template, default template arguments are
4626        allowed at the innermost level, e.g.:
4627          template <class T = int>
4628          struct S {};
4629        but, in a partial specialization, they're not allowed even
4630        there, as we have in [temp.class.spec]:
4631
4632          The template parameter list of a specialization shall not
4633          contain default template argument values.
4634
4635        So, for a partial specialization, or for a function template
4636        (in C++98/C++03), we look at all of them.  */
4637     ;
4638   else
4639     /* But, for a primary class template that is not a partial
4640        specialization we look at all template parameters except the
4641        innermost ones.  */
4642     parms = TREE_CHAIN (parms);
4643
4644   /* Figure out what error message to issue.  */
4645   if (is_friend_decl == 2)
4646     msg = G_("default template arguments may not be used in function template "
4647              "friend re-declaration");
4648   else if (is_friend_decl)
4649     msg = G_("default template arguments may not be used in function template "
4650              "friend declarations");
4651   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4652     msg = G_("default template arguments may not be used in function templates "
4653              "without -std=c++0x or -std=gnu++0x");
4654   else if (is_partial)
4655     msg = G_("default template arguments may not be used in "
4656              "partial specializations");
4657   else
4658     msg = G_("default argument for template parameter for class enclosing %qD");
4659
4660   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4661     /* If we're inside a class definition, there's no need to
4662        examine the parameters to the class itself.  On the one
4663        hand, they will be checked when the class is defined, and,
4664        on the other, default arguments are valid in things like:
4665          template <class T = double>
4666          struct S { template <class U> void f(U); };
4667        Here the default argument for `S' has no bearing on the
4668        declaration of `f'.  */
4669     last_level_to_check = template_class_depth (current_class_type) + 1;
4670   else
4671     /* Check everything.  */
4672     last_level_to_check = 0;
4673
4674   for (parm_level = parms;
4675        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4676        parm_level = TREE_CHAIN (parm_level))
4677     {
4678       tree inner_parms = TREE_VALUE (parm_level);
4679       int i;
4680       int ntparms;
4681
4682       ntparms = TREE_VEC_LENGTH (inner_parms);
4683       for (i = 0; i < ntparms; ++i)
4684         {
4685           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4686             continue;
4687
4688           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4689             {
4690               if (msg)
4691                 {
4692                   no_errors = false;
4693                   if (is_friend_decl == 2)
4694                     return no_errors;
4695
4696                   error (msg, decl);
4697                   msg = 0;
4698                 }
4699
4700               /* Clear out the default argument so that we are not
4701                  confused later.  */
4702               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4703             }
4704         }
4705
4706       /* At this point, if we're still interested in issuing messages,
4707          they must apply to classes surrounding the object declared.  */
4708       if (msg)
4709         msg = G_("default argument for template parameter for class "
4710                  "enclosing %qD");
4711     }
4712
4713   return no_errors;
4714 }
4715
4716 /* Worker for push_template_decl_real, called via
4717    for_each_template_parm.  DATA is really an int, indicating the
4718    level of the parameters we are interested in.  If T is a template
4719    parameter of that level, return nonzero.  */
4720
4721 static int
4722 template_parm_this_level_p (tree t, void* data)
4723 {
4724   int this_level = *(int *)data;
4725   int level;
4726
4727   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4728     level = TEMPLATE_PARM_LEVEL (t);
4729   else
4730     level = TEMPLATE_TYPE_LEVEL (t);
4731   return level == this_level;
4732 }
4733
4734 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4735    parameters given by current_template_args, or reuses a
4736    previously existing one, if appropriate.  Returns the DECL, or an
4737    equivalent one, if it is replaced via a call to duplicate_decls.
4738
4739    If IS_FRIEND is true, DECL is a friend declaration.  */
4740
4741 tree
4742 push_template_decl_real (tree decl, bool is_friend)
4743 {
4744   tree tmpl;
4745   tree args;
4746   tree info;
4747   tree ctx;
4748   int primary;
4749   int is_partial;
4750   int new_template_p = 0;
4751   /* True if the template is a member template, in the sense of
4752      [temp.mem].  */
4753   bool member_template_p = false;
4754
4755   if (decl == error_mark_node || !current_template_parms)
4756     return error_mark_node;
4757
4758   /* See if this is a partial specialization.  */
4759   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4760                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4761                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4762
4763   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4764     is_friend = true;
4765
4766   if (is_friend)
4767     /* For a friend, we want the context of the friend function, not
4768        the type of which it is a friend.  */
4769     ctx = CP_DECL_CONTEXT (decl);
4770   else if (CP_DECL_CONTEXT (decl)
4771            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4772     /* In the case of a virtual function, we want the class in which
4773        it is defined.  */
4774     ctx = CP_DECL_CONTEXT (decl);
4775   else
4776     /* Otherwise, if we're currently defining some class, the DECL
4777        is assumed to be a member of the class.  */
4778     ctx = current_scope ();
4779
4780   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4781     ctx = NULL_TREE;
4782
4783   if (!DECL_CONTEXT (decl))
4784     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4785
4786   /* See if this is a primary template.  */
4787   if (is_friend && ctx)
4788     /* A friend template that specifies a class context, i.e.
4789          template <typename T> friend void A<T>::f();
4790        is not primary.  */
4791     primary = 0;
4792   else
4793     primary = template_parm_scope_p ();
4794
4795   if (primary)
4796     {
4797       if (DECL_CLASS_SCOPE_P (decl))
4798         member_template_p = true;
4799       if (TREE_CODE (decl) == TYPE_DECL
4800           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4801         {
4802           error ("template class without a name");
4803           return error_mark_node;
4804         }
4805       else if (TREE_CODE (decl) == FUNCTION_DECL)
4806         {
4807           if (DECL_DESTRUCTOR_P (decl))
4808             {
4809               /* [temp.mem]
4810
4811                  A destructor shall not be a member template.  */
4812               error ("destructor %qD declared as member template", decl);
4813               return error_mark_node;
4814             }
4815           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4816               && (!prototype_p (TREE_TYPE (decl))
4817                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4818                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4819                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4820                       == void_list_node)))
4821             {
4822               /* [basic.stc.dynamic.allocation]
4823
4824                  An allocation function can be a function
4825                  template. ... Template allocation functions shall
4826                  have two or more parameters.  */
4827               error ("invalid template declaration of %qD", decl);
4828               return error_mark_node;
4829             }
4830         }
4831       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4832                && CLASS_TYPE_P (TREE_TYPE (decl)))
4833         /* OK */;
4834       else
4835         {
4836           error ("template declaration of %q#D", decl);
4837           return error_mark_node;
4838         }
4839     }
4840
4841   /* Check to see that the rules regarding the use of default
4842      arguments are not being violated.  */
4843   check_default_tmpl_args (decl, current_template_parms,
4844                            primary, is_partial, /*is_friend_decl=*/0);
4845
4846   /* Ensure that there are no parameter packs in the type of this
4847      declaration that have not been expanded.  */
4848   if (TREE_CODE (decl) == FUNCTION_DECL)
4849     {
4850       /* Check each of the arguments individually to see if there are
4851          any bare parameter packs.  */
4852       tree type = TREE_TYPE (decl);
4853       tree arg = DECL_ARGUMENTS (decl);
4854       tree argtype = TYPE_ARG_TYPES (type);
4855
4856       while (arg && argtype)
4857         {
4858           if (!FUNCTION_PARAMETER_PACK_P (arg)
4859               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4860             {
4861             /* This is a PARM_DECL that contains unexpanded parameter
4862                packs. We have already complained about this in the
4863                check_for_bare_parameter_packs call, so just replace
4864                these types with ERROR_MARK_NODE.  */
4865               TREE_TYPE (arg) = error_mark_node;
4866               TREE_VALUE (argtype) = error_mark_node;
4867             }
4868
4869           arg = DECL_CHAIN (arg);
4870           argtype = TREE_CHAIN (argtype);
4871         }
4872
4873       /* Check for bare parameter packs in the return type and the
4874          exception specifiers.  */
4875       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4876         /* Errors were already issued, set return type to int
4877            as the frontend doesn't expect error_mark_node as
4878            the return type.  */
4879         TREE_TYPE (type) = integer_type_node;
4880       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4881         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4882     }
4883   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4884     {
4885       TREE_TYPE (decl) = error_mark_node;
4886       return error_mark_node;
4887     }
4888
4889   if (is_partial)
4890     return process_partial_specialization (decl);
4891
4892   args = current_template_args ();
4893
4894   if (!ctx
4895       || TREE_CODE (ctx) == FUNCTION_DECL
4896       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4897       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4898     {
4899       if (DECL_LANG_SPECIFIC (decl)
4900           && DECL_TEMPLATE_INFO (decl)
4901           && DECL_TI_TEMPLATE (decl))
4902         tmpl = DECL_TI_TEMPLATE (decl);
4903       /* If DECL is a TYPE_DECL for a class-template, then there won't
4904          be DECL_LANG_SPECIFIC.  The information equivalent to
4905          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4906       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4907                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4908                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4909         {
4910           /* Since a template declaration already existed for this
4911              class-type, we must be redeclaring it here.  Make sure
4912              that the redeclaration is valid.  */
4913           redeclare_class_template (TREE_TYPE (decl),
4914                                     current_template_parms);
4915           /* We don't need to create a new TEMPLATE_DECL; just use the
4916              one we already had.  */
4917           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4918         }
4919       else
4920         {
4921           tmpl = build_template_decl (decl, current_template_parms,
4922                                       member_template_p);
4923           new_template_p = 1;
4924
4925           if (DECL_LANG_SPECIFIC (decl)
4926               && DECL_TEMPLATE_SPECIALIZATION (decl))
4927             {
4928               /* A specialization of a member template of a template
4929                  class.  */
4930               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4931               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4932               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4933             }
4934         }
4935     }
4936   else
4937     {
4938       tree a, t, current, parms;
4939       int i;
4940       tree tinfo = get_template_info (decl);
4941
4942       if (!tinfo)
4943         {
4944           error ("template definition of non-template %q#D", decl);
4945           return error_mark_node;
4946         }
4947
4948       tmpl = TI_TEMPLATE (tinfo);
4949
4950       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4951           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4952           && DECL_TEMPLATE_SPECIALIZATION (decl)
4953           && DECL_MEMBER_TEMPLATE_P (tmpl))
4954         {
4955           tree new_tmpl;
4956
4957           /* The declaration is a specialization of a member
4958              template, declared outside the class.  Therefore, the
4959              innermost template arguments will be NULL, so we
4960              replace them with the arguments determined by the
4961              earlier call to check_explicit_specialization.  */
4962           args = DECL_TI_ARGS (decl);
4963
4964           new_tmpl
4965             = build_template_decl (decl, current_template_parms,
4966                                    member_template_p);
4967           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4968           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4969           DECL_TI_TEMPLATE (decl) = new_tmpl;
4970           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4971           DECL_TEMPLATE_INFO (new_tmpl)
4972             = build_template_info (tmpl, args);
4973
4974           register_specialization (new_tmpl,
4975                                    most_general_template (tmpl),
4976                                    args,
4977                                    is_friend, 0);
4978           return decl;
4979         }
4980
4981       /* Make sure the template headers we got make sense.  */
4982
4983       parms = DECL_TEMPLATE_PARMS (tmpl);
4984       i = TMPL_PARMS_DEPTH (parms);
4985       if (TMPL_ARGS_DEPTH (args) != i)
4986         {
4987           error ("expected %d levels of template parms for %q#D, got %d",
4988                  i, decl, TMPL_ARGS_DEPTH (args));
4989         }
4990       else
4991         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4992           {
4993             a = TMPL_ARGS_LEVEL (args, i);
4994             t = INNERMOST_TEMPLATE_PARMS (parms);
4995
4996             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4997               {
4998                 if (current == decl)
4999                   error ("got %d template parameters for %q#D",
5000                          TREE_VEC_LENGTH (a), decl);
5001                 else
5002                   error ("got %d template parameters for %q#T",
5003                          TREE_VEC_LENGTH (a), current);
5004                 error ("  but %d required", TREE_VEC_LENGTH (t));
5005                 return error_mark_node;
5006               }
5007
5008             if (current == decl)
5009               current = ctx;
5010             else if (current == NULL_TREE)
5011               /* Can happen in erroneous input.  */
5012               break;
5013             else
5014               current = (TYPE_P (current)
5015                          ? TYPE_CONTEXT (current)
5016                          : DECL_CONTEXT (current));
5017           }
5018
5019       /* Check that the parms are used in the appropriate qualifying scopes
5020          in the declarator.  */
5021       if (!comp_template_args
5022           (TI_ARGS (tinfo),
5023            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5024         {
5025           error ("\
5026 template arguments to %qD do not match original template %qD",
5027                  decl, DECL_TEMPLATE_RESULT (tmpl));
5028           if (!uses_template_parms (TI_ARGS (tinfo)))
5029             inform (input_location, "use template<> for an explicit specialization");
5030           /* Avoid crash in import_export_decl.  */
5031           DECL_INTERFACE_KNOWN (decl) = 1;
5032           return error_mark_node;
5033         }
5034     }
5035
5036   DECL_TEMPLATE_RESULT (tmpl) = decl;
5037   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5038
5039   /* Push template declarations for global functions and types.  Note
5040      that we do not try to push a global template friend declared in a
5041      template class; such a thing may well depend on the template
5042      parameters of the class.  */
5043   if (new_template_p && !ctx
5044       && !(is_friend && template_class_depth (current_class_type) > 0))
5045     {
5046       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5047       if (tmpl == error_mark_node)
5048         return error_mark_node;
5049
5050       /* Hide template friend classes that haven't been declared yet.  */
5051       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5052         {
5053           DECL_ANTICIPATED (tmpl) = 1;
5054           DECL_FRIEND_P (tmpl) = 1;
5055         }
5056     }
5057
5058   if (primary)
5059     {
5060       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5061       int i;
5062
5063       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5064       if (DECL_CONV_FN_P (tmpl))
5065         {
5066           int depth = TMPL_PARMS_DEPTH (parms);
5067
5068           /* It is a conversion operator. See if the type converted to
5069              depends on innermost template operands.  */
5070
5071           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5072                                          depth))
5073             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5074         }
5075
5076       /* Give template template parms a DECL_CONTEXT of the template
5077          for which they are a parameter.  */
5078       parms = INNERMOST_TEMPLATE_PARMS (parms);
5079       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5080         {
5081           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5082           if (TREE_CODE (parm) == TEMPLATE_DECL)
5083             DECL_CONTEXT (parm) = tmpl;
5084         }
5085     }
5086
5087   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5088      back to its most general template.  If TMPL is a specialization,
5089      ARGS may only have the innermost set of arguments.  Add the missing
5090      argument levels if necessary.  */
5091   if (DECL_TEMPLATE_INFO (tmpl))
5092     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5093
5094   info = build_template_info (tmpl, args);
5095
5096   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5097     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5098   else if (DECL_LANG_SPECIFIC (decl))
5099     DECL_TEMPLATE_INFO (decl) = info;
5100
5101   return DECL_TEMPLATE_RESULT (tmpl);
5102 }
5103
5104 tree
5105 push_template_decl (tree decl)
5106 {
5107   return push_template_decl_real (decl, false);
5108 }
5109
5110 /* Called when a class template TYPE is redeclared with the indicated
5111    template PARMS, e.g.:
5112
5113      template <class T> struct S;
5114      template <class T> struct S {};  */
5115
5116 bool
5117 redeclare_class_template (tree type, tree parms)
5118 {
5119   tree tmpl;
5120   tree tmpl_parms;
5121   int i;
5122
5123   if (!TYPE_TEMPLATE_INFO (type))
5124     {
5125       error ("%qT is not a template type", type);
5126       return false;
5127     }
5128
5129   tmpl = TYPE_TI_TEMPLATE (type);
5130   if (!PRIMARY_TEMPLATE_P (tmpl))
5131     /* The type is nested in some template class.  Nothing to worry
5132        about here; there are no new template parameters for the nested
5133        type.  */
5134     return true;
5135
5136   if (!parms)
5137     {
5138       error ("template specifiers not specified in declaration of %qD",
5139              tmpl);
5140       return false;
5141     }
5142
5143   parms = INNERMOST_TEMPLATE_PARMS (parms);
5144   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5145
5146   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5147     {
5148       error_n (input_location, TREE_VEC_LENGTH (parms),
5149                "redeclared with %d template parameter",
5150                "redeclared with %d template parameters",
5151                TREE_VEC_LENGTH (parms));
5152       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5153                 "previous declaration %q+D used %d template parameter",
5154                 "previous declaration %q+D used %d template parameters",
5155                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5156       return false;
5157     }
5158
5159   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5160     {
5161       tree tmpl_parm;
5162       tree parm;
5163       tree tmpl_default;
5164       tree parm_default;
5165
5166       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5167           || TREE_VEC_ELT (parms, i) == error_mark_node)
5168         continue;
5169
5170       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5171       if (tmpl_parm == error_mark_node)
5172         return false;
5173
5174       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5175       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5176       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5177
5178       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5179          TEMPLATE_DECL.  */
5180       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5181           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5182               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5183           || (TREE_CODE (tmpl_parm) != PARM_DECL
5184               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5185                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5186           || (TREE_CODE (tmpl_parm) == PARM_DECL
5187               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5188                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5189         {
5190           error ("template parameter %q+#D", tmpl_parm);
5191           error ("redeclared here as %q#D", parm);
5192           return false;
5193         }
5194
5195       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5196         {
5197           /* We have in [temp.param]:
5198
5199              A template-parameter may not be given default arguments
5200              by two different declarations in the same scope.  */
5201           error_at (input_location, "redefinition of default argument for %q#D", parm);
5202           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5203                   "original definition appeared here");
5204           return false;
5205         }
5206
5207       if (parm_default != NULL_TREE)
5208         /* Update the previous template parameters (which are the ones
5209            that will really count) with the new default value.  */
5210         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5211       else if (tmpl_default != NULL_TREE)
5212         /* Update the new parameters, too; they'll be used as the
5213            parameters for any members.  */
5214         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5215     }
5216
5217     return true;
5218 }
5219
5220 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5221    (possibly simplified) expression.  */
5222
5223 static tree
5224 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5225 {
5226   if (expr == NULL_TREE)
5227     return NULL_TREE;
5228
5229   /* If we're in a template, but EXPR isn't value dependent, simplify
5230      it.  We're supposed to treat:
5231
5232        template <typename T> void f(T[1 + 1]);
5233        template <typename T> void f(T[2]);
5234
5235      as two declarations of the same function, for example.  */
5236   if (processing_template_decl
5237       && !type_dependent_expression_p (expr)
5238       && potential_constant_expression (expr)
5239       && !value_dependent_expression_p (expr))
5240     {
5241       HOST_WIDE_INT saved_processing_template_decl;
5242
5243       saved_processing_template_decl = processing_template_decl;
5244       processing_template_decl = 0;
5245       expr = tsubst_copy_and_build (expr,
5246                                     /*args=*/NULL_TREE,
5247                                     complain,
5248                                     /*in_decl=*/NULL_TREE,
5249                                     /*function_p=*/false,
5250                                     /*integral_constant_expression_p=*/true);
5251       processing_template_decl = saved_processing_template_decl;
5252     }
5253   return expr;
5254 }
5255
5256 tree
5257 fold_non_dependent_expr (tree expr)
5258 {
5259   return fold_non_dependent_expr_sfinae (expr, tf_error);
5260 }
5261
5262 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5263    must be a function or a pointer-to-function type, as specified
5264    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5265    and check that the resulting function has external linkage.  */
5266
5267 static tree
5268 convert_nontype_argument_function (tree type, tree expr)
5269 {
5270   tree fns = expr;
5271   tree fn, fn_no_ptr;
5272
5273   fn = instantiate_type (type, fns, tf_none);
5274   if (fn == error_mark_node)
5275     return error_mark_node;
5276
5277   fn_no_ptr = fn;
5278   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5279     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5280   if (BASELINK_P (fn_no_ptr))
5281     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5282  
5283   /* [temp.arg.nontype]/1
5284
5285      A template-argument for a non-type, non-template template-parameter
5286      shall be one of:
5287      [...]
5288      -- the address of an object or function with external linkage.  */
5289   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5290     {
5291       error ("%qE is not a valid template argument for type %qT "
5292              "because function %qD has not external linkage",
5293              expr, type, fn_no_ptr);
5294       return NULL_TREE;
5295     }
5296
5297   return fn;
5298 }
5299
5300 /* Subroutine of convert_nontype_argument.
5301    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5302    Emit an error otherwise.  */
5303
5304 static bool
5305 check_valid_ptrmem_cst_expr (tree type, tree expr,
5306                              tsubst_flags_t complain)
5307 {
5308   STRIP_NOPS (expr);
5309   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5310     return true;
5311   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5312     return true;
5313   if (complain & tf_error)
5314     {
5315       error ("%qE is not a valid template argument for type %qT",
5316              expr, type);
5317       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5318     }
5319   return false;
5320 }
5321
5322 /* Returns TRUE iff the address of OP is value-dependent.
5323
5324    14.6.2.4 [temp.dep.temp]:
5325    A non-integral non-type template-argument is dependent if its type is
5326    dependent or it has either of the following forms
5327      qualified-id
5328      & qualified-id
5329    and contains a nested-name-specifier which specifies a class-name that
5330    names a dependent type.
5331
5332    We generalize this to just say that the address of a member of a
5333    dependent class is value-dependent; the above doesn't cover the
5334    address of a static data member named with an unqualified-id.  */
5335
5336 static bool
5337 has_value_dependent_address (tree op)
5338 {
5339   /* We could use get_inner_reference here, but there's no need;
5340      this is only relevant for template non-type arguments, which
5341      can only be expressed as &id-expression.  */
5342   if (DECL_P (op))
5343     {
5344       tree ctx = CP_DECL_CONTEXT (op);
5345       if (TYPE_P (ctx) && dependent_type_p (ctx))
5346         return true;
5347     }
5348
5349   return false;
5350 }
5351
5352 /* The next set of functions are used for providing helpful explanatory
5353    diagnostics for failed overload resolution.  Their messages should be
5354    indented by two spaces for consistency with the messages in
5355    call.c  */
5356
5357 static int
5358 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5359 {
5360   return 0;
5361 }
5362
5363 static int
5364 unify_parameter_deduction_failure (bool explain_p, tree parm)
5365 {
5366   if (explain_p)
5367     inform (input_location,
5368             "  couldn't deduce template parameter %qD", parm);
5369   return 1;
5370 }
5371
5372 static int
5373 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5374 {
5375   return 1;
5376 }
5377
5378 static int
5379 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5380 {
5381   if (explain_p)
5382     inform (input_location,
5383             "  types %qT and %qT have incompatible cv-qualifiers",
5384             parm, arg);
5385   return 1;
5386 }
5387
5388 static int
5389 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5390 {
5391   if (explain_p)
5392     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5393   return 1;
5394 }
5395
5396 static int
5397 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5398 {
5399   if (explain_p)
5400     inform (input_location,
5401             "  template parameter %qD is not a parameter pack, but "
5402             "argument %qD is",
5403             parm, arg);
5404   return 1;
5405 }
5406
5407 static int
5408 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5409 {
5410   if (explain_p)
5411     inform (input_location,
5412             "  template argument %qE does not match "
5413             "pointer-to-member constant %qE",
5414             arg, parm);
5415   return 1;
5416 }
5417
5418 static int
5419 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5420 {
5421   if (explain_p)
5422     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5423   return 1;
5424 }
5425
5426 static int
5427 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5428 {
5429   if (explain_p)
5430     inform (input_location,
5431             "  inconsistent parameter pack deduction with %qT and %qT",
5432             old_arg, new_arg);
5433   return 1;
5434 }
5435
5436 static int
5437 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5438 {
5439   if (explain_p)
5440     inform (input_location,
5441             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5442             parm, first, second);
5443   return 1;
5444 }
5445
5446 static int
5447 unify_vla_arg (bool explain_p, tree arg)
5448 {
5449   if (explain_p)
5450     inform (input_location,
5451             "  variable-sized array type %qT is not "
5452             "a valid template argument",
5453             arg);
5454   return 1;
5455 }
5456
5457 static int
5458 unify_method_type_error (bool explain_p, tree arg)
5459 {
5460   if (explain_p)
5461     inform (input_location,
5462             "  member function type %qT is not a valid template argument",
5463             arg);
5464   return 1;
5465 }
5466
5467 static int
5468 unify_arity (bool explain_p, int have, int wanted)
5469 {
5470   if (explain_p)
5471     inform_n (input_location, wanted,
5472               "  candidate expects %d argument, %d provided",
5473               "  candidate expects %d arguments, %d provided",
5474               wanted, have);
5475   return 1;
5476 }
5477
5478 static int
5479 unify_too_many_arguments (bool explain_p, int have, int wanted)
5480 {
5481   return unify_arity (explain_p, have, wanted);
5482 }
5483
5484 static int
5485 unify_too_few_arguments (bool explain_p, int have, int wanted)
5486 {
5487   return unify_arity (explain_p, have, wanted);
5488 }
5489
5490 static int
5491 unify_arg_conversion (bool explain_p, tree to_type,
5492                       tree from_type, tree arg)
5493 {
5494   if (explain_p)
5495     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5496             arg, from_type, to_type);
5497   return 1;
5498 }
5499
5500 static int
5501 unify_no_common_base (bool explain_p, enum template_base_result r,
5502                       tree parm, tree arg)
5503 {
5504   if (explain_p)
5505     switch (r)
5506       {
5507       case tbr_ambiguous_baseclass:
5508         inform (input_location, "  %qT is an ambiguous base class of %qT",
5509                 arg, parm);
5510         break;
5511       default:
5512         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5513         break;
5514       }
5515   return 1;
5516 }
5517
5518 static int
5519 unify_inconsistent_template_template_parameters (bool explain_p)
5520 {
5521   if (explain_p)
5522     inform (input_location,
5523             "  template parameters of a template template argument are "
5524             "inconsistent with other deduced template arguments");
5525   return 1;
5526 }
5527
5528 static int
5529 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5530 {
5531   if (explain_p)
5532     inform (input_location,
5533             "  can't deduce a template for %qT from non-template type %qT",
5534             parm, arg);
5535   return 1;
5536 }
5537
5538 static int
5539 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5540 {
5541   if (explain_p)
5542     inform (input_location,
5543             "  template argument %qE does not match %qD", arg, parm);
5544   return 1;
5545 }
5546
5547 static int
5548 unify_overload_resolution_failure (bool explain_p, tree arg)
5549 {
5550   if (explain_p)
5551     inform (input_location,
5552             "  could not resolve address from overloaded function %qE",
5553             arg);
5554   return 1;
5555 }
5556
5557 /* Attempt to convert the non-type template parameter EXPR to the
5558    indicated TYPE.  If the conversion is successful, return the
5559    converted value.  If the conversion is unsuccessful, return
5560    NULL_TREE if we issued an error message, or error_mark_node if we
5561    did not.  We issue error messages for out-and-out bad template
5562    parameters, but not simply because the conversion failed, since we
5563    might be just trying to do argument deduction.  Both TYPE and EXPR
5564    must be non-dependent.
5565
5566    The conversion follows the special rules described in
5567    [temp.arg.nontype], and it is much more strict than an implicit
5568    conversion.
5569
5570    This function is called twice for each template argument (see
5571    lookup_template_class for a more accurate description of this
5572    problem). This means that we need to handle expressions which
5573    are not valid in a C++ source, but can be created from the
5574    first call (for instance, casts to perform conversions). These
5575    hacks can go away after we fix the double coercion problem.  */
5576
5577 static tree
5578 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5579 {
5580   tree expr_type;
5581
5582   /* Detect immediately string literals as invalid non-type argument.
5583      This special-case is not needed for correctness (we would easily
5584      catch this later), but only to provide better diagnostic for this
5585      common user mistake. As suggested by DR 100, we do not mention
5586      linkage issues in the diagnostic as this is not the point.  */
5587   /* FIXME we're making this OK.  */
5588   if (TREE_CODE (expr) == STRING_CST)
5589     {
5590       if (complain & tf_error)
5591         error ("%qE is not a valid template argument for type %qT "
5592                "because string literals can never be used in this context",
5593                expr, type);
5594       return NULL_TREE;
5595     }
5596
5597   /* Add the ADDR_EXPR now for the benefit of
5598      value_dependent_expression_p.  */
5599   if (TYPE_PTROBV_P (type)
5600       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5601     expr = decay_conversion (expr);
5602
5603   /* If we are in a template, EXPR may be non-dependent, but still
5604      have a syntactic, rather than semantic, form.  For example, EXPR
5605      might be a SCOPE_REF, rather than the VAR_DECL to which the
5606      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5607      so that access checking can be performed when the template is
5608      instantiated -- but here we need the resolved form so that we can
5609      convert the argument.  */
5610   if (TYPE_REF_OBJ_P (type)
5611       && has_value_dependent_address (expr))
5612     /* If we want the address and it's value-dependent, don't fold.  */;
5613   else if (!type_unknown_p (expr))
5614     expr = fold_non_dependent_expr_sfinae (expr, complain);
5615   if (error_operand_p (expr))
5616     return error_mark_node;
5617   expr_type = TREE_TYPE (expr);
5618   if (TREE_CODE (type) == REFERENCE_TYPE)
5619     expr = mark_lvalue_use (expr);
5620   else
5621     expr = mark_rvalue_use (expr);
5622
5623   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5624      to a non-type argument of "nullptr".  */
5625   if (expr == nullptr_node
5626       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5627     expr = convert (type, expr);
5628
5629   /* In C++11, non-type template arguments can be arbitrary constant
5630      expressions.  But don't fold a PTRMEM_CST to a CONSTRUCTOR yet.  */
5631   if (cxx_dialect >= cxx0x && TREE_CODE (expr) != PTRMEM_CST)
5632     expr = maybe_constant_value (expr);
5633
5634   /* HACK: Due to double coercion, we can get a
5635      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5636      which is the tree that we built on the first call (see
5637      below when coercing to reference to object or to reference to
5638      function). We just strip everything and get to the arg.
5639      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5640      for examples.  */
5641   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5642     {
5643       tree probe_type, probe = expr;
5644       if (REFERENCE_REF_P (probe))
5645         probe = TREE_OPERAND (probe, 0);
5646       probe_type = TREE_TYPE (probe);
5647       if (TREE_CODE (probe) == NOP_EXPR)
5648         {
5649           /* ??? Maybe we could use convert_from_reference here, but we
5650              would need to relax its constraints because the NOP_EXPR
5651              could actually change the type to something more cv-qualified,
5652              and this is not folded by convert_from_reference.  */
5653           tree addr = TREE_OPERAND (probe, 0);
5654           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5655           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5656           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5657           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5658                       (TREE_TYPE (probe_type),
5659                        TREE_TYPE (TREE_TYPE (addr))));
5660
5661           expr = TREE_OPERAND (addr, 0);
5662           expr_type = TREE_TYPE (expr);
5663         }
5664     }
5665
5666   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5667      parameter is a pointer to object, through decay and
5668      qualification conversion. Let's strip everything.  */
5669   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5670     {
5671       STRIP_NOPS (expr);
5672       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5673       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5674       /* Skip the ADDR_EXPR only if it is part of the decay for
5675          an array. Otherwise, it is part of the original argument
5676          in the source code.  */
5677       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5678         expr = TREE_OPERAND (expr, 0);
5679       expr_type = TREE_TYPE (expr);
5680     }
5681
5682   /* [temp.arg.nontype]/5, bullet 1
5683
5684      For a non-type template-parameter of integral or enumeration type,
5685      integral promotions (_conv.prom_) and integral conversions
5686      (_conv.integral_) are applied.  */
5687   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5688     {
5689       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5690       t = maybe_constant_value (t);
5691       if (t != error_mark_node)
5692         expr = t;
5693
5694       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5695         return error_mark_node;
5696
5697       /* Notice that there are constant expressions like '4 % 0' which
5698          do not fold into integer constants.  */
5699       if (TREE_CODE (expr) != INTEGER_CST)
5700         {
5701           if (complain & tf_error)
5702             {
5703               int errs = errorcount, warns = warningcount;
5704               expr = cxx_constant_value (expr);
5705               if (errorcount > errs || warningcount > warns)
5706                 inform (EXPR_LOC_OR_HERE (expr),
5707                         "in template argument for type %qT ", type);
5708               if (expr == error_mark_node)
5709                 return NULL_TREE;
5710               /* else cxx_constant_value complained but gave us
5711                  a real constant, so go ahead.  */
5712               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5713             }
5714           else
5715             return NULL_TREE;
5716         }
5717     }
5718   /* [temp.arg.nontype]/5, bullet 2
5719
5720      For a non-type template-parameter of type pointer to object,
5721      qualification conversions (_conv.qual_) and the array-to-pointer
5722      conversion (_conv.array_) are applied.  */
5723   else if (TYPE_PTROBV_P (type))
5724     {
5725       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5726
5727          A template-argument for a non-type, non-template template-parameter
5728          shall be one of: [...]
5729
5730          -- the name of a non-type template-parameter;
5731          -- the address of an object or function with external linkage, [...]
5732             expressed as "& id-expression" where the & is optional if the name
5733             refers to a function or array, or if the corresponding
5734             template-parameter is a reference.
5735
5736         Here, we do not care about functions, as they are invalid anyway
5737         for a parameter of type pointer-to-object.  */
5738
5739       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5740         /* Non-type template parameters are OK.  */
5741         ;
5742       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5743         /* Null pointer values are OK in C++11.  */;
5744       else if (TREE_CODE (expr) != ADDR_EXPR
5745                && TREE_CODE (expr_type) != ARRAY_TYPE)
5746         {
5747           if (TREE_CODE (expr) == VAR_DECL)
5748             {
5749               error ("%qD is not a valid template argument "
5750                      "because %qD is a variable, not the address of "
5751                      "a variable",
5752                      expr, expr);
5753               return NULL_TREE;
5754             }
5755           /* Other values, like integer constants, might be valid
5756              non-type arguments of some other type.  */
5757           return error_mark_node;
5758         }
5759       else
5760         {
5761           tree decl;
5762
5763           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5764                   ? TREE_OPERAND (expr, 0) : expr);
5765           if (TREE_CODE (decl) != VAR_DECL)
5766             {
5767               error ("%qE is not a valid template argument of type %qT "
5768                      "because %qE is not a variable",
5769                      expr, type, decl);
5770               return NULL_TREE;
5771             }
5772           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5773             {
5774               error ("%qE is not a valid template argument of type %qT "
5775                      "because %qD does not have external linkage",
5776                      expr, type, decl);
5777               return NULL_TREE;
5778             }
5779         }
5780
5781       expr = decay_conversion (expr);
5782       if (expr == error_mark_node)
5783         return error_mark_node;
5784
5785       expr = perform_qualification_conversions (type, expr);
5786       if (expr == error_mark_node)
5787         return error_mark_node;
5788     }
5789   /* [temp.arg.nontype]/5, bullet 3
5790
5791      For a non-type template-parameter of type reference to object, no
5792      conversions apply. The type referred to by the reference may be more
5793      cv-qualified than the (otherwise identical) type of the
5794      template-argument. The template-parameter is bound directly to the
5795      template-argument, which must be an lvalue.  */
5796   else if (TYPE_REF_OBJ_P (type))
5797     {
5798       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5799                                                       expr_type))
5800         return error_mark_node;
5801
5802       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5803         {
5804           error ("%qE is not a valid template argument for type %qT "
5805                  "because of conflicts in cv-qualification", expr, type);
5806           return NULL_TREE;
5807         }
5808
5809       if (!real_lvalue_p (expr))
5810         {
5811           error ("%qE is not a valid template argument for type %qT "
5812                  "because it is not an lvalue", expr, type);
5813           return NULL_TREE;
5814         }
5815
5816       /* [temp.arg.nontype]/1
5817
5818          A template-argument for a non-type, non-template template-parameter
5819          shall be one of: [...]
5820
5821          -- the address of an object or function with external linkage.  */
5822       if (TREE_CODE (expr) == INDIRECT_REF
5823           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5824         {
5825           expr = TREE_OPERAND (expr, 0);
5826           if (DECL_P (expr))
5827             {
5828               error ("%q#D is not a valid template argument for type %qT "
5829                      "because a reference variable does not have a constant "
5830                      "address", expr, type);
5831               return NULL_TREE;
5832             }
5833         }
5834
5835       if (!DECL_P (expr))
5836         {
5837           error ("%qE is not a valid template argument for type %qT "
5838                  "because it is not an object with external linkage",
5839                  expr, type);
5840           return NULL_TREE;
5841         }
5842
5843       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5844         {
5845           error ("%qE is not a valid template argument for type %qT "
5846                  "because object %qD has not external linkage",
5847                  expr, type, expr);
5848           return NULL_TREE;
5849         }
5850
5851       expr = build_nop (type, build_address (expr));
5852     }
5853   /* [temp.arg.nontype]/5, bullet 4
5854
5855      For a non-type template-parameter of type pointer to function, only
5856      the function-to-pointer conversion (_conv.func_) is applied. If the
5857      template-argument represents a set of overloaded functions (or a
5858      pointer to such), the matching function is selected from the set
5859      (_over.over_).  */
5860   else if (TYPE_PTRFN_P (type))
5861     {
5862       /* If the argument is a template-id, we might not have enough
5863          context information to decay the pointer.  */
5864       if (!type_unknown_p (expr_type))
5865         {
5866           expr = decay_conversion (expr);
5867           if (expr == error_mark_node)
5868             return error_mark_node;
5869         }
5870
5871       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5872         /* Null pointer values are OK in C++11.  */
5873         return perform_qualification_conversions (type, expr);
5874
5875       expr = convert_nontype_argument_function (type, expr);
5876       if (!expr || expr == error_mark_node)
5877         return expr;
5878
5879       if (TREE_CODE (expr) != ADDR_EXPR)
5880         {
5881           error ("%qE is not a valid template argument for type %qT", expr, type);
5882           error ("it must be the address of a function with external linkage");
5883           return NULL_TREE;
5884         }
5885     }
5886   /* [temp.arg.nontype]/5, bullet 5
5887
5888      For a non-type template-parameter of type reference to function, no
5889      conversions apply. If the template-argument represents a set of
5890      overloaded functions, the matching function is selected from the set
5891      (_over.over_).  */
5892   else if (TYPE_REFFN_P (type))
5893     {
5894       if (TREE_CODE (expr) == ADDR_EXPR)
5895         {
5896           error ("%qE is not a valid template argument for type %qT "
5897                  "because it is a pointer", expr, type);
5898           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5899           return NULL_TREE;
5900         }
5901
5902       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5903       if (!expr || expr == error_mark_node)
5904         return expr;
5905
5906       expr = build_nop (type, build_address (expr));
5907     }
5908   /* [temp.arg.nontype]/5, bullet 6
5909
5910      For a non-type template-parameter of type pointer to member function,
5911      no conversions apply. If the template-argument represents a set of
5912      overloaded member functions, the matching member function is selected
5913      from the set (_over.over_).  */
5914   else if (TYPE_PTRMEMFUNC_P (type))
5915     {
5916       expr = instantiate_type (type, expr, tf_none);
5917       if (expr == error_mark_node)
5918         return error_mark_node;
5919
5920       /* [temp.arg.nontype] bullet 1 says the pointer to member
5921          expression must be a pointer-to-member constant.  */
5922       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5923         return error_mark_node;
5924
5925       /* There is no way to disable standard conversions in
5926          resolve_address_of_overloaded_function (called by
5927          instantiate_type). It is possible that the call succeeded by
5928          converting &B::I to &D::I (where B is a base of D), so we need
5929          to reject this conversion here.
5930
5931          Actually, even if there was a way to disable standard conversions,
5932          it would still be better to reject them here so that we can
5933          provide a superior diagnostic.  */
5934       if (!same_type_p (TREE_TYPE (expr), type))
5935         {
5936           error ("%qE is not a valid template argument for type %qT "
5937                  "because it is of type %qT", expr, type,
5938                  TREE_TYPE (expr));
5939           /* If we are just one standard conversion off, explain.  */
5940           if (can_convert (type, TREE_TYPE (expr)))
5941             inform (input_location,
5942                     "standard conversions are not allowed in this context");
5943           return NULL_TREE;
5944         }
5945     }
5946   /* [temp.arg.nontype]/5, bullet 7
5947
5948      For a non-type template-parameter of type pointer to data member,
5949      qualification conversions (_conv.qual_) are applied.  */
5950   else if (TYPE_PTRMEM_P (type))
5951     {
5952       /* [temp.arg.nontype] bullet 1 says the pointer to member
5953          expression must be a pointer-to-member constant.  */
5954       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5955         return error_mark_node;
5956
5957       expr = perform_qualification_conversions (type, expr);
5958       if (expr == error_mark_node)
5959         return expr;
5960     }
5961   else if (NULLPTR_TYPE_P (type))
5962     {
5963       if (expr != nullptr_node)
5964         {
5965           error ("%qE is not a valid template argument for type %qT "
5966                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
5967           return NULL_TREE;
5968         }
5969       return expr;
5970     }
5971   /* A template non-type parameter must be one of the above.  */
5972   else
5973     gcc_unreachable ();
5974
5975   /* Sanity check: did we actually convert the argument to the
5976      right type?  */
5977   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5978               (type, TREE_TYPE (expr)));
5979   return expr;
5980 }
5981
5982 /* Subroutine of coerce_template_template_parms, which returns 1 if
5983    PARM_PARM and ARG_PARM match using the rule for the template
5984    parameters of template template parameters. Both PARM and ARG are
5985    template parameters; the rest of the arguments are the same as for
5986    coerce_template_template_parms.
5987  */
5988 static int
5989 coerce_template_template_parm (tree parm,
5990                               tree arg,
5991                               tsubst_flags_t complain,
5992                               tree in_decl,
5993                               tree outer_args)
5994 {
5995   if (arg == NULL_TREE || arg == error_mark_node
5996       || parm == NULL_TREE || parm == error_mark_node)
5997     return 0;
5998   
5999   if (TREE_CODE (arg) != TREE_CODE (parm))
6000     return 0;
6001   
6002   switch (TREE_CODE (parm))
6003     {
6004     case TEMPLATE_DECL:
6005       /* We encounter instantiations of templates like
6006          template <template <template <class> class> class TT>
6007          class C;  */
6008       {
6009         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6010         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6011         
6012         if (!coerce_template_template_parms
6013             (parmparm, argparm, complain, in_decl, outer_args))
6014           return 0;
6015       }
6016       /* Fall through.  */
6017       
6018     case TYPE_DECL:
6019       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6020           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6021         /* Argument is a parameter pack but parameter is not.  */
6022         return 0;
6023       break;
6024       
6025     case PARM_DECL:
6026       /* The tsubst call is used to handle cases such as
6027          
6028            template <int> class C {};
6029            template <class T, template <T> class TT> class D {};
6030            D<int, C> d;
6031
6032          i.e. the parameter list of TT depends on earlier parameters.  */
6033       if (!uses_template_parms (TREE_TYPE (arg))
6034           && !same_type_p
6035                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6036                  TREE_TYPE (arg)))
6037         return 0;
6038       
6039       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6040           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6041         /* Argument is a parameter pack but parameter is not.  */
6042         return 0;
6043       
6044       break;
6045
6046     default:
6047       gcc_unreachable ();
6048     }
6049
6050   return 1;
6051 }
6052
6053
6054 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6055    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6056    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6057    or PARM_DECL.
6058
6059    Consider the example:
6060      template <class T> class A;
6061      template<template <class U> class TT> class B;
6062
6063    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6064    the parameters to A, and OUTER_ARGS contains A.  */
6065
6066 static int
6067 coerce_template_template_parms (tree parm_parms,
6068                                 tree arg_parms,
6069                                 tsubst_flags_t complain,
6070                                 tree in_decl,
6071                                 tree outer_args)
6072 {
6073   int nparms, nargs, i;
6074   tree parm, arg;
6075   int variadic_p = 0;
6076
6077   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6078   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6079
6080   nparms = TREE_VEC_LENGTH (parm_parms);
6081   nargs = TREE_VEC_LENGTH (arg_parms);
6082
6083   /* Determine whether we have a parameter pack at the end of the
6084      template template parameter's template parameter list.  */
6085   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6086     {
6087       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6088       
6089       if (parm == error_mark_node)
6090         return 0;
6091
6092       switch (TREE_CODE (parm))
6093         {
6094         case TEMPLATE_DECL:
6095         case TYPE_DECL:
6096           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6097             variadic_p = 1;
6098           break;
6099           
6100         case PARM_DECL:
6101           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6102             variadic_p = 1;
6103           break;
6104           
6105         default:
6106           gcc_unreachable ();
6107         }
6108     }
6109  
6110   if (nargs != nparms
6111       && !(variadic_p && nargs >= nparms - 1))
6112     return 0;
6113
6114   /* Check all of the template parameters except the parameter pack at
6115      the end (if any).  */
6116   for (i = 0; i < nparms - variadic_p; ++i)
6117     {
6118       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6119           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6120         continue;
6121
6122       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6123       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6124
6125       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6126                                           outer_args))
6127         return 0;
6128
6129     }
6130
6131   if (variadic_p)
6132     {
6133       /* Check each of the template parameters in the template
6134          argument against the template parameter pack at the end of
6135          the template template parameter.  */
6136       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6137         return 0;
6138
6139       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6140
6141       for (; i < nargs; ++i)
6142         {
6143           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6144             continue;
6145  
6146           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6147  
6148           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6149                                               outer_args))
6150             return 0;
6151         }
6152     }
6153
6154   return 1;
6155 }
6156
6157 /* Verifies that the deduced template arguments (in TARGS) for the
6158    template template parameters (in TPARMS) represent valid bindings,
6159    by comparing the template parameter list of each template argument
6160    to the template parameter list of its corresponding template
6161    template parameter, in accordance with DR150. This
6162    routine can only be called after all template arguments have been
6163    deduced. It will return TRUE if all of the template template
6164    parameter bindings are okay, FALSE otherwise.  */
6165 bool 
6166 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6167 {
6168   int i, ntparms = TREE_VEC_LENGTH (tparms);
6169   bool ret = true;
6170
6171   /* We're dealing with template parms in this process.  */
6172   ++processing_template_decl;
6173
6174   targs = INNERMOST_TEMPLATE_ARGS (targs);
6175
6176   for (i = 0; i < ntparms; ++i)
6177     {
6178       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6179       tree targ = TREE_VEC_ELT (targs, i);
6180
6181       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6182         {
6183           tree packed_args = NULL_TREE;
6184           int idx, len = 1;
6185
6186           if (ARGUMENT_PACK_P (targ))
6187             {
6188               /* Look inside the argument pack.  */
6189               packed_args = ARGUMENT_PACK_ARGS (targ);
6190               len = TREE_VEC_LENGTH (packed_args);
6191             }
6192
6193           for (idx = 0; idx < len; ++idx)
6194             {
6195               tree targ_parms = NULL_TREE;
6196
6197               if (packed_args)
6198                 /* Extract the next argument from the argument
6199                    pack.  */
6200                 targ = TREE_VEC_ELT (packed_args, idx);
6201
6202               if (PACK_EXPANSION_P (targ))
6203                 /* Look at the pattern of the pack expansion.  */
6204                 targ = PACK_EXPANSION_PATTERN (targ);
6205
6206               /* Extract the template parameters from the template
6207                  argument.  */
6208               if (TREE_CODE (targ) == TEMPLATE_DECL)
6209                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6210               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6211                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6212
6213               /* Verify that we can coerce the template template
6214                  parameters from the template argument to the template
6215                  parameter.  This requires an exact match.  */
6216               if (targ_parms
6217                   && !coerce_template_template_parms
6218                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6219                         targ_parms,
6220                         tf_none,
6221                         tparm,
6222                         targs))
6223                 {
6224                   ret = false;
6225                   goto out;
6226                 }
6227             }
6228         }
6229     }
6230
6231  out:
6232
6233   --processing_template_decl;
6234   return ret;
6235 }
6236
6237 /* Since type attributes aren't mangled, we need to strip them from
6238    template type arguments.  */
6239
6240 static tree
6241 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6242 {
6243   tree mv;
6244   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6245     return arg;
6246   mv = TYPE_MAIN_VARIANT (arg);
6247   arg = strip_typedefs (arg);
6248   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6249       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6250     {
6251       if (complain & tf_warning)
6252         warning (0, "ignoring attributes on template argument %qT", arg);
6253       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6254       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6255     }
6256   return arg;
6257 }
6258
6259 /* Convert the indicated template ARG as necessary to match the
6260    indicated template PARM.  Returns the converted ARG, or
6261    error_mark_node if the conversion was unsuccessful.  Error and
6262    warning messages are issued under control of COMPLAIN.  This
6263    conversion is for the Ith parameter in the parameter list.  ARGS is
6264    the full set of template arguments deduced so far.  */
6265
6266 static tree
6267 convert_template_argument (tree parm,
6268                            tree arg,
6269                            tree args,
6270                            tsubst_flags_t complain,
6271                            int i,
6272                            tree in_decl)
6273 {
6274   tree orig_arg;
6275   tree val;
6276   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6277
6278   if (TREE_CODE (arg) == TREE_LIST
6279       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6280     {
6281       /* The template argument was the name of some
6282          member function.  That's usually
6283          invalid, but static members are OK.  In any
6284          case, grab the underlying fields/functions
6285          and issue an error later if required.  */
6286       orig_arg = TREE_VALUE (arg);
6287       TREE_TYPE (arg) = unknown_type_node;
6288     }
6289
6290   orig_arg = arg;
6291
6292   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6293   requires_type = (TREE_CODE (parm) == TYPE_DECL
6294                    || requires_tmpl_type);
6295
6296   /* When determining whether an argument pack expansion is a template,
6297      look at the pattern.  */
6298   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6299     arg = PACK_EXPANSION_PATTERN (arg);
6300
6301   /* Deal with an injected-class-name used as a template template arg.  */
6302   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6303     {
6304       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6305       if (TREE_CODE (t) == TEMPLATE_DECL)
6306         {
6307           if (cxx_dialect >= cxx0x)
6308             /* OK under DR 1004.  */;
6309           else if (complain & tf_warning_or_error)
6310             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6311                      " used as template template argument", TYPE_NAME (arg));
6312           else if (flag_pedantic_errors)
6313             t = arg;
6314
6315           arg = t;
6316         }
6317     }
6318
6319   is_tmpl_type = 
6320     ((TREE_CODE (arg) == TEMPLATE_DECL
6321       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6322      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6323      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6324
6325   if (is_tmpl_type
6326       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6327           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6328     arg = TYPE_STUB_DECL (arg);
6329
6330   is_type = TYPE_P (arg) || is_tmpl_type;
6331
6332   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6333       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6334     {
6335       permerror (input_location, "to refer to a type member of a template parameter, "
6336                  "use %<typename %E%>", orig_arg);
6337
6338       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6339                                      TREE_OPERAND (arg, 1),
6340                                      typename_type,
6341                                      complain & tf_error);
6342       arg = orig_arg;
6343       is_type = 1;
6344     }
6345   if (is_type != requires_type)
6346     {
6347       if (in_decl)
6348         {
6349           if (complain & tf_error)
6350             {
6351               error ("type/value mismatch at argument %d in template "
6352                      "parameter list for %qD",
6353                      i + 1, in_decl);
6354               if (is_type)
6355                 error ("  expected a constant of type %qT, got %qT",
6356                        TREE_TYPE (parm),
6357                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6358               else if (requires_tmpl_type)
6359                 error ("  expected a class template, got %qE", orig_arg);
6360               else
6361                 error ("  expected a type, got %qE", orig_arg);
6362             }
6363         }
6364       return error_mark_node;
6365     }
6366   if (is_tmpl_type ^ requires_tmpl_type)
6367     {
6368       if (in_decl && (complain & tf_error))
6369         {
6370           error ("type/value mismatch at argument %d in template "
6371                  "parameter list for %qD",
6372                  i + 1, in_decl);
6373           if (is_tmpl_type)
6374             error ("  expected a type, got %qT", DECL_NAME (arg));
6375           else
6376             error ("  expected a class template, got %qT", orig_arg);
6377         }
6378       return error_mark_node;
6379     }
6380
6381   if (is_type)
6382     {
6383       if (requires_tmpl_type)
6384         {
6385           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6386             /* The number of argument required is not known yet.
6387                Just accept it for now.  */
6388             val = TREE_TYPE (arg);
6389           else
6390             {
6391               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6392               tree argparm;
6393
6394               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6395
6396               if (coerce_template_template_parms (parmparm, argparm,
6397                                                   complain, in_decl,
6398                                                   args))
6399                 {
6400                   val = arg;
6401
6402                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6403                      TEMPLATE_DECL.  */
6404                   if (val != error_mark_node)
6405                     {
6406                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6407                         val = TREE_TYPE (val);
6408                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6409                         val = make_pack_expansion (val);
6410                     }
6411                 }
6412               else
6413                 {
6414                   if (in_decl && (complain & tf_error))
6415                     {
6416                       error ("type/value mismatch at argument %d in "
6417                              "template parameter list for %qD",
6418                              i + 1, in_decl);
6419                       error ("  expected a template of type %qD, got %qT",
6420                              parm, orig_arg);
6421                     }
6422
6423                   val = error_mark_node;
6424                 }
6425             }
6426         }
6427       else
6428         val = orig_arg;
6429       /* We only form one instance of each template specialization.
6430          Therefore, if we use a non-canonical variant (i.e., a
6431          typedef), any future messages referring to the type will use
6432          the typedef, which is confusing if those future uses do not
6433          themselves also use the typedef.  */
6434       if (TYPE_P (val))
6435         val = canonicalize_type_argument (val, complain);
6436     }
6437   else
6438     {
6439       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6440
6441       if (invalid_nontype_parm_type_p (t, complain))
6442         return error_mark_node;
6443
6444       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6445         {
6446           if (same_type_p (t, TREE_TYPE (orig_arg)))
6447             val = orig_arg;
6448           else
6449             {
6450               /* Not sure if this is reachable, but it doesn't hurt
6451                  to be robust.  */
6452               error ("type mismatch in nontype parameter pack");
6453               val = error_mark_node;
6454             }
6455         }
6456       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6457         /* We used to call digest_init here.  However, digest_init
6458            will report errors, which we don't want when complain
6459            is zero.  More importantly, digest_init will try too
6460            hard to convert things: for example, `0' should not be
6461            converted to pointer type at this point according to
6462            the standard.  Accepting this is not merely an
6463            extension, since deciding whether or not these
6464            conversions can occur is part of determining which
6465            function template to call, or whether a given explicit
6466            argument specification is valid.  */
6467         val = convert_nontype_argument (t, orig_arg, complain);
6468       else
6469         val = orig_arg;
6470
6471       if (val == NULL_TREE)
6472         val = error_mark_node;
6473       else if (val == error_mark_node && (complain & tf_error))
6474         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6475
6476       if (TREE_CODE (val) == SCOPE_REF)
6477         {
6478           /* Strip typedefs from the SCOPE_REF.  */
6479           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6480           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6481                                                    complain);
6482           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6483                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6484         }
6485     }
6486
6487   return val;
6488 }
6489
6490 /* Coerces the remaining template arguments in INNER_ARGS (from
6491    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6492    Returns the coerced argument pack. PARM_IDX is the position of this
6493    parameter in the template parameter list. ARGS is the original
6494    template argument list.  */
6495 static tree
6496 coerce_template_parameter_pack (tree parms,
6497                                 int parm_idx,
6498                                 tree args,
6499                                 tree inner_args,
6500                                 int arg_idx,
6501                                 tree new_args,
6502                                 int* lost,
6503                                 tree in_decl,
6504                                 tsubst_flags_t complain)
6505 {
6506   tree parm = TREE_VEC_ELT (parms, parm_idx);
6507   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6508   tree packed_args;
6509   tree argument_pack;
6510   tree packed_types = NULL_TREE;
6511
6512   if (arg_idx > nargs)
6513     arg_idx = nargs;
6514
6515   packed_args = make_tree_vec (nargs - arg_idx);
6516
6517   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6518       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6519     {
6520       /* When the template parameter is a non-type template
6521          parameter pack whose type uses parameter packs, we need
6522          to look at each of the template arguments
6523          separately. Build a vector of the types for these
6524          non-type template parameters in PACKED_TYPES.  */
6525       tree expansion 
6526         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6527       packed_types = tsubst_pack_expansion (expansion, args,
6528                                             complain, in_decl);
6529
6530       if (packed_types == error_mark_node)
6531         return error_mark_node;
6532
6533       /* Check that we have the right number of arguments.  */
6534       if (arg_idx < nargs
6535           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6536           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6537         {
6538           int needed_parms 
6539             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6540           error ("wrong number of template arguments (%d, should be %d)",
6541                  nargs, needed_parms);
6542           return error_mark_node;
6543         }
6544
6545       /* If we aren't able to check the actual arguments now
6546          (because they haven't been expanded yet), we can at least
6547          verify that all of the types used for the non-type
6548          template parameter pack are, in fact, valid for non-type
6549          template parameters.  */
6550       if (arg_idx < nargs 
6551           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6552         {
6553           int j, len = TREE_VEC_LENGTH (packed_types);
6554           for (j = 0; j < len; ++j)
6555             {
6556               tree t = TREE_VEC_ELT (packed_types, j);
6557               if (invalid_nontype_parm_type_p (t, complain))
6558                 return error_mark_node;
6559             }
6560         }
6561     }
6562
6563   /* Convert the remaining arguments, which will be a part of the
6564      parameter pack "parm".  */
6565   for (; arg_idx < nargs; ++arg_idx)
6566     {
6567       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6568       tree actual_parm = TREE_VALUE (parm);
6569
6570       if (packed_types && !PACK_EXPANSION_P (arg))
6571         {
6572           /* When we have a vector of types (corresponding to the
6573              non-type template parameter pack that uses parameter
6574              packs in its type, as mention above), and the
6575              argument is not an expansion (which expands to a
6576              currently unknown number of arguments), clone the
6577              parm and give it the next type in PACKED_TYPES.  */
6578           actual_parm = copy_node (actual_parm);
6579           TREE_TYPE (actual_parm) = 
6580             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6581         }
6582
6583       if (arg != error_mark_node)
6584         arg = convert_template_argument (actual_parm, 
6585                                          arg, new_args, complain, parm_idx,
6586                                          in_decl);
6587       if (arg == error_mark_node)
6588         (*lost)++;
6589       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6590     }
6591
6592   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6593       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6594     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6595   else
6596     {
6597       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6598       TREE_TYPE (argument_pack) 
6599         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6600       TREE_CONSTANT (argument_pack) = 1;
6601     }
6602
6603   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6604 #ifdef ENABLE_CHECKING
6605   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6606                                        TREE_VEC_LENGTH (packed_args));
6607 #endif
6608   return argument_pack;
6609 }
6610
6611 /* Convert all template arguments to their appropriate types, and
6612    return a vector containing the innermost resulting template
6613    arguments.  If any error occurs, return error_mark_node. Error and
6614    warning messages are issued under control of COMPLAIN.
6615
6616    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6617    for arguments not specified in ARGS.  Otherwise, if
6618    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6619    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6620    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6621    ARGS.  */
6622
6623 static tree
6624 coerce_template_parms (tree parms,
6625                        tree args,
6626                        tree in_decl,
6627                        tsubst_flags_t complain,
6628                        bool require_all_args,
6629                        bool use_default_args)
6630 {
6631   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6632   tree inner_args;
6633   tree new_args;
6634   tree new_inner_args;
6635   int saved_unevaluated_operand;
6636   int saved_inhibit_evaluation_warnings;
6637
6638   /* When used as a boolean value, indicates whether this is a
6639      variadic template parameter list. Since it's an int, we can also
6640      subtract it from nparms to get the number of non-variadic
6641      parameters.  */
6642   int variadic_p = 0;
6643   int post_variadic_parms = 0;
6644
6645   if (args == error_mark_node)
6646     return error_mark_node;
6647
6648   nparms = TREE_VEC_LENGTH (parms);
6649
6650   /* Determine if there are any parameter packs.  */
6651   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6652     {
6653       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6654       if (variadic_p)
6655         ++post_variadic_parms;
6656       if (template_parameter_pack_p (tparm))
6657         ++variadic_p;
6658     }
6659
6660   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6661   /* If there are no parameters that follow a parameter pack, we need to
6662      expand any argument packs so that we can deduce a parameter pack from
6663      some non-packed args followed by an argument pack, as in variadic85.C.
6664      If there are such parameters, we need to leave argument packs intact
6665      so the arguments are assigned properly.  This can happen when dealing
6666      with a nested class inside a partial specialization of a class
6667      template, as in variadic92.C, or when deducing a template parameter pack
6668      from a sub-declarator, as in variadic114.C.  */
6669   if (!post_variadic_parms)
6670     inner_args = expand_template_argument_pack (inner_args);
6671
6672   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6673   if ((nargs > nparms && !variadic_p)
6674       || (nargs < nparms - variadic_p
6675           && require_all_args
6676           && (!use_default_args
6677               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6678                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6679     {
6680       if (complain & tf_error)
6681         {
6682           if (variadic_p)
6683             {
6684               nparms -= variadic_p;
6685               error ("wrong number of template arguments "
6686                      "(%d, should be %d or more)", nargs, nparms);
6687             }
6688           else
6689              error ("wrong number of template arguments "
6690                     "(%d, should be %d)", nargs, nparms);
6691
6692           if (in_decl)
6693             error ("provided for %q+D", in_decl);
6694         }
6695
6696       return error_mark_node;
6697     }
6698
6699   /* We need to evaluate the template arguments, even though this
6700      template-id may be nested within a "sizeof".  */
6701   saved_unevaluated_operand = cp_unevaluated_operand;
6702   cp_unevaluated_operand = 0;
6703   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6704   c_inhibit_evaluation_warnings = 0;
6705   new_inner_args = make_tree_vec (nparms);
6706   new_args = add_outermost_template_args (args, new_inner_args);
6707   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6708     {
6709       tree arg;
6710       tree parm;
6711
6712       /* Get the Ith template parameter.  */
6713       parm = TREE_VEC_ELT (parms, parm_idx);
6714  
6715       if (parm == error_mark_node)
6716       {
6717         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6718         continue;
6719       }
6720
6721       /* Calculate the next argument.  */
6722       if (arg_idx < nargs)
6723         arg = TREE_VEC_ELT (inner_args, arg_idx);
6724       else
6725         arg = NULL_TREE;
6726
6727       if (template_parameter_pack_p (TREE_VALUE (parm))
6728           && !(arg && ARGUMENT_PACK_P (arg)))
6729         {
6730           /* All remaining arguments will be placed in the
6731              template parameter pack PARM.  */
6732           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6733                                                 inner_args, arg_idx,
6734                                                 new_args, &lost,
6735                                                 in_decl, complain);
6736
6737           /* Store this argument.  */
6738           if (arg == error_mark_node)
6739             lost++;
6740           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6741
6742           /* We are done with all of the arguments.  */
6743           arg_idx = nargs;
6744           
6745           continue;
6746         }
6747       else if (arg)
6748         {
6749           if (PACK_EXPANSION_P (arg))
6750             {
6751               /* We don't know how many args we have yet, just
6752                  use the unconverted ones for now.  */
6753               new_inner_args = args;
6754               break;
6755             }
6756         }
6757       else if (require_all_args)
6758         {
6759           /* There must be a default arg in this case.  */
6760           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6761                                      complain, in_decl);
6762           /* The position of the first default template argument,
6763              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6764              Record that.  */
6765           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6766             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6767         }
6768       else
6769         break;
6770
6771       if (arg == error_mark_node)
6772         {
6773           if (complain & tf_error)
6774             error ("template argument %d is invalid", arg_idx + 1);
6775         }
6776       else if (!arg)
6777         /* This only occurs if there was an error in the template
6778            parameter list itself (which we would already have
6779            reported) that we are trying to recover from, e.g., a class
6780            template with a parameter list such as
6781            template<typename..., typename>.  */
6782         ++lost;
6783       else
6784         arg = convert_template_argument (TREE_VALUE (parm),
6785                                          arg, new_args, complain, 
6786                                          parm_idx, in_decl);
6787
6788       if (arg == error_mark_node)
6789         lost++;
6790       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6791     }
6792   cp_unevaluated_operand = saved_unevaluated_operand;
6793   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6794
6795   if (lost)
6796     return error_mark_node;
6797
6798 #ifdef ENABLE_CHECKING
6799   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6800     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6801                                          TREE_VEC_LENGTH (new_inner_args));
6802 #endif
6803
6804   return new_inner_args;
6805 }
6806
6807 /* Returns 1 if template args OT and NT are equivalent.  */
6808
6809 static int
6810 template_args_equal (tree ot, tree nt)
6811 {
6812   if (nt == ot)
6813     return 1;
6814   if (nt == NULL_TREE || ot == NULL_TREE)
6815     return false;
6816
6817   if (TREE_CODE (nt) == TREE_VEC)
6818     /* For member templates */
6819     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6820   else if (PACK_EXPANSION_P (ot))
6821     return PACK_EXPANSION_P (nt) 
6822       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6823                               PACK_EXPANSION_PATTERN (nt));
6824   else if (ARGUMENT_PACK_P (ot))
6825     {
6826       int i, len;
6827       tree opack, npack;
6828
6829       if (!ARGUMENT_PACK_P (nt))
6830         return 0;
6831
6832       opack = ARGUMENT_PACK_ARGS (ot);
6833       npack = ARGUMENT_PACK_ARGS (nt);
6834       len = TREE_VEC_LENGTH (opack);
6835       if (TREE_VEC_LENGTH (npack) != len)
6836         return 0;
6837       for (i = 0; i < len; ++i)
6838         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6839                                   TREE_VEC_ELT (npack, i)))
6840           return 0;
6841       return 1;
6842     }
6843   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6844     {
6845       /* We get here probably because we are in the middle of substituting
6846          into the pattern of a pack expansion. In that case the
6847          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6848          interested in. So we want to use the initial pack argument for
6849          the comparison.  */
6850       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6851       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6852         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6853       return template_args_equal (ot, nt);
6854     }
6855   else if (TYPE_P (nt))
6856     return TYPE_P (ot) && same_type_p (ot, nt);
6857   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6858     return 0;
6859   else
6860     return cp_tree_equal (ot, nt);
6861 }
6862
6863 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6864    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6865    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6866
6867 static int
6868 comp_template_args_with_info (tree oldargs, tree newargs,
6869                               tree *oldarg_ptr, tree *newarg_ptr)
6870 {
6871   int i;
6872
6873   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6874     return 0;
6875
6876   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6877     {
6878       tree nt = TREE_VEC_ELT (newargs, i);
6879       tree ot = TREE_VEC_ELT (oldargs, i);
6880
6881       if (! template_args_equal (ot, nt))
6882         {
6883           if (oldarg_ptr != NULL)
6884             *oldarg_ptr = ot;
6885           if (newarg_ptr != NULL)
6886             *newarg_ptr = nt;
6887           return 0;
6888         }
6889     }
6890   return 1;
6891 }
6892
6893 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6894    of template arguments.  Returns 0 otherwise.  */
6895
6896 int
6897 comp_template_args (tree oldargs, tree newargs)
6898 {
6899   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6900 }
6901
6902 static void
6903 add_pending_template (tree d)
6904 {
6905   tree ti = (TYPE_P (d)
6906              ? CLASSTYPE_TEMPLATE_INFO (d)
6907              : DECL_TEMPLATE_INFO (d));
6908   struct pending_template *pt;
6909   int level;
6910
6911   if (TI_PENDING_TEMPLATE_FLAG (ti))
6912     return;
6913
6914   /* We are called both from instantiate_decl, where we've already had a
6915      tinst_level pushed, and instantiate_template, where we haven't.
6916      Compensate.  */
6917   level = !current_tinst_level || current_tinst_level->decl != d;
6918
6919   if (level)
6920     push_tinst_level (d);
6921
6922   pt = ggc_alloc_pending_template ();
6923   pt->next = NULL;
6924   pt->tinst = current_tinst_level;
6925   if (last_pending_template)
6926     last_pending_template->next = pt;
6927   else
6928     pending_templates = pt;
6929
6930   last_pending_template = pt;
6931
6932   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6933
6934   if (level)
6935     pop_tinst_level ();
6936 }
6937
6938
6939 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6940    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6941    documentation for TEMPLATE_ID_EXPR.  */
6942
6943 tree
6944 lookup_template_function (tree fns, tree arglist)
6945 {
6946   tree type;
6947
6948   if (fns == error_mark_node || arglist == error_mark_node)
6949     return error_mark_node;
6950
6951   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6952
6953   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6954     {
6955       error ("%q#D is not a function template", fns);
6956       return error_mark_node;
6957     }
6958
6959   if (BASELINK_P (fns))
6960     {
6961       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6962                                          unknown_type_node,
6963                                          BASELINK_FUNCTIONS (fns),
6964                                          arglist);
6965       return fns;
6966     }
6967
6968   type = TREE_TYPE (fns);
6969   if (TREE_CODE (fns) == OVERLOAD || !type)
6970     type = unknown_type_node;
6971
6972   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6973 }
6974
6975 /* Within the scope of a template class S<T>, the name S gets bound
6976    (in build_self_reference) to a TYPE_DECL for the class, not a
6977    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6978    or one of its enclosing classes, and that type is a template,
6979    return the associated TEMPLATE_DECL.  Otherwise, the original
6980    DECL is returned.
6981
6982    Also handle the case when DECL is a TREE_LIST of ambiguous
6983    injected-class-names from different bases.  */
6984
6985 tree
6986 maybe_get_template_decl_from_type_decl (tree decl)
6987 {
6988   if (decl == NULL_TREE)
6989     return decl;
6990
6991   /* DR 176: A lookup that finds an injected-class-name (10.2
6992      [class.member.lookup]) can result in an ambiguity in certain cases
6993      (for example, if it is found in more than one base class). If all of
6994      the injected-class-names that are found refer to specializations of
6995      the same class template, and if the name is followed by a
6996      template-argument-list, the reference refers to the class template
6997      itself and not a specialization thereof, and is not ambiguous.  */
6998   if (TREE_CODE (decl) == TREE_LIST)
6999     {
7000       tree t, tmpl = NULL_TREE;
7001       for (t = decl; t; t = TREE_CHAIN (t))
7002         {
7003           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7004           if (!tmpl)
7005             tmpl = elt;
7006           else if (tmpl != elt)
7007             break;
7008         }
7009       if (tmpl && t == NULL_TREE)
7010         return tmpl;
7011       else
7012         return decl;
7013     }
7014
7015   return (decl != NULL_TREE
7016           && DECL_SELF_REFERENCE_P (decl)
7017           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7018     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7019 }
7020
7021 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
7022    parameters, find the desired type.
7023
7024    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7025
7026    IN_DECL, if non-NULL, is the template declaration we are trying to
7027    instantiate.
7028
7029    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7030    the class we are looking up.
7031
7032    Issue error and warning messages under control of COMPLAIN.
7033
7034    If the template class is really a local class in a template
7035    function, then the FUNCTION_CONTEXT is the function in which it is
7036    being instantiated.
7037
7038    ??? Note that this function is currently called *twice* for each
7039    template-id: the first time from the parser, while creating the
7040    incomplete type (finish_template_type), and the second type during the
7041    real instantiation (instantiate_template_class). This is surely something
7042    that we want to avoid. It also causes some problems with argument
7043    coercion (see convert_nontype_argument for more information on this).  */
7044
7045 static tree
7046 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7047                          int entering_scope, tsubst_flags_t complain)
7048 {
7049   tree templ = NULL_TREE, parmlist;
7050   tree t;
7051   void **slot;
7052   spec_entry *entry;
7053   spec_entry elt;
7054   hashval_t hash;
7055
7056   if (TREE_CODE (d1) == IDENTIFIER_NODE)
7057     {
7058       tree value = innermost_non_namespace_value (d1);
7059       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7060         templ = value;
7061       else
7062         {
7063           if (context)
7064             push_decl_namespace (context);
7065           templ = lookup_name (d1);
7066           templ = maybe_get_template_decl_from_type_decl (templ);
7067           if (context)
7068             pop_decl_namespace ();
7069         }
7070       if (templ)
7071         context = DECL_CONTEXT (templ);
7072     }
7073   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7074     {
7075       tree type = TREE_TYPE (d1);
7076
7077       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7078          an implicit typename for the second A.  Deal with it.  */
7079       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7080         type = TREE_TYPE (type);
7081
7082       if (CLASSTYPE_TEMPLATE_INFO (type))
7083         {
7084           templ = CLASSTYPE_TI_TEMPLATE (type);
7085           d1 = DECL_NAME (templ);
7086         }
7087     }
7088   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7089            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7090     {
7091       templ = TYPE_TI_TEMPLATE (d1);
7092       d1 = DECL_NAME (templ);
7093     }
7094   else if (TREE_CODE (d1) == TEMPLATE_DECL
7095            && DECL_TEMPLATE_RESULT (d1)
7096            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7097     {
7098       templ = d1;
7099       d1 = DECL_NAME (templ);
7100       context = DECL_CONTEXT (templ);
7101     }
7102
7103   /* Issue an error message if we didn't find a template.  */
7104   if (! templ)
7105     {
7106       if (complain & tf_error)
7107         error ("%qT is not a template", d1);
7108       return error_mark_node;
7109     }
7110
7111   if (TREE_CODE (templ) != TEMPLATE_DECL
7112          /* Make sure it's a user visible template, if it was named by
7113             the user.  */
7114       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7115           && !PRIMARY_TEMPLATE_P (templ)))
7116     {
7117       if (complain & tf_error)
7118         {
7119           error ("non-template type %qT used as a template", d1);
7120           if (in_decl)
7121             error ("for template declaration %q+D", in_decl);
7122         }
7123       return error_mark_node;
7124     }
7125
7126   complain &= ~tf_user;
7127
7128   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7129     {
7130       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7131          template arguments */
7132
7133       tree parm;
7134       tree arglist2;
7135       tree outer;
7136
7137       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7138
7139       /* Consider an example where a template template parameter declared as
7140
7141            template <class T, class U = std::allocator<T> > class TT
7142
7143          The template parameter level of T and U are one level larger than
7144          of TT.  To proper process the default argument of U, say when an
7145          instantiation `TT<int>' is seen, we need to build the full
7146          arguments containing {int} as the innermost level.  Outer levels,
7147          available when not appearing as default template argument, can be
7148          obtained from the arguments of the enclosing template.
7149
7150          Suppose that TT is later substituted with std::vector.  The above
7151          instantiation is `TT<int, std::allocator<T> >' with TT at
7152          level 1, and T at level 2, while the template arguments at level 1
7153          becomes {std::vector} and the inner level 2 is {int}.  */
7154
7155       outer = DECL_CONTEXT (templ);
7156       if (outer)
7157         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7158       else if (current_template_parms)
7159         /* This is an argument of the current template, so we haven't set
7160            DECL_CONTEXT yet.  */
7161         outer = current_template_args ();
7162
7163       if (outer)
7164         arglist = add_to_template_args (outer, arglist);
7165
7166       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7167                                         complain,
7168                                         /*require_all_args=*/true,
7169                                         /*use_default_args=*/true);
7170       if (arglist2 == error_mark_node
7171           || (!uses_template_parms (arglist2)
7172               && check_instantiated_args (templ, arglist2, complain)))
7173         return error_mark_node;
7174
7175       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7176       return parm;
7177     }
7178   else
7179     {
7180       tree template_type = TREE_TYPE (templ);
7181       tree gen_tmpl;
7182       tree type_decl;
7183       tree found = NULL_TREE;
7184       int arg_depth;
7185       int parm_depth;
7186       int is_dependent_type;
7187       int use_partial_inst_tmpl = false;
7188
7189       gen_tmpl = most_general_template (templ);
7190       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7191       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7192       arg_depth = TMPL_ARGS_DEPTH (arglist);
7193
7194       if (arg_depth == 1 && parm_depth > 1)
7195         {
7196           /* We've been given an incomplete set of template arguments.
7197              For example, given:
7198
7199                template <class T> struct S1 {
7200                  template <class U> struct S2 {};
7201                  template <class U> struct S2<U*> {};
7202                 };
7203
7204              we will be called with an ARGLIST of `U*', but the
7205              TEMPLATE will be `template <class T> template
7206              <class U> struct S1<T>::S2'.  We must fill in the missing
7207              arguments.  */
7208           arglist
7209             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7210                                            arglist);
7211           arg_depth = TMPL_ARGS_DEPTH (arglist);
7212         }
7213
7214       /* Now we should have enough arguments.  */
7215       gcc_assert (parm_depth == arg_depth);
7216
7217       /* From here on, we're only interested in the most general
7218          template.  */
7219
7220       /* Calculate the BOUND_ARGS.  These will be the args that are
7221          actually tsubst'd into the definition to create the
7222          instantiation.  */
7223       if (parm_depth > 1)
7224         {
7225           /* We have multiple levels of arguments to coerce, at once.  */
7226           int i;
7227           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7228
7229           tree bound_args = make_tree_vec (parm_depth);
7230
7231           for (i = saved_depth,
7232                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7233                i > 0 && t != NULL_TREE;
7234                --i, t = TREE_CHAIN (t))
7235             {
7236               tree a;
7237               if (i == saved_depth)
7238                 a = coerce_template_parms (TREE_VALUE (t),
7239                                            arglist, gen_tmpl,
7240                                            complain,
7241                                            /*require_all_args=*/true,
7242                                            /*use_default_args=*/true);
7243               else
7244                 /* Outer levels should have already been coerced.  */
7245                 a = TMPL_ARGS_LEVEL (arglist, i);
7246
7247               /* Don't process further if one of the levels fails.  */
7248               if (a == error_mark_node)
7249                 {
7250                   /* Restore the ARGLIST to its full size.  */
7251                   TREE_VEC_LENGTH (arglist) = saved_depth;
7252                   return error_mark_node;
7253                 }
7254
7255               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7256
7257               /* We temporarily reduce the length of the ARGLIST so
7258                  that coerce_template_parms will see only the arguments
7259                  corresponding to the template parameters it is
7260                  examining.  */
7261               TREE_VEC_LENGTH (arglist)--;
7262             }
7263
7264           /* Restore the ARGLIST to its full size.  */
7265           TREE_VEC_LENGTH (arglist) = saved_depth;
7266
7267           arglist = bound_args;
7268         }
7269       else
7270         arglist
7271           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7272                                    INNERMOST_TEMPLATE_ARGS (arglist),
7273                                    gen_tmpl,
7274                                    complain,
7275                                    /*require_all_args=*/true,
7276                                    /*use_default_args=*/true);
7277
7278       if (arglist == error_mark_node)
7279         /* We were unable to bind the arguments.  */
7280         return error_mark_node;
7281
7282       /* In the scope of a template class, explicit references to the
7283          template class refer to the type of the template, not any
7284          instantiation of it.  For example, in:
7285
7286            template <class T> class C { void f(C<T>); }
7287
7288          the `C<T>' is just the same as `C'.  Outside of the
7289          class, however, such a reference is an instantiation.  */
7290       if ((entering_scope
7291            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7292            || currently_open_class (template_type))
7293           /* comp_template_args is expensive, check it last.  */
7294           && comp_template_args (TYPE_TI_ARGS (template_type),
7295                                  arglist))
7296         return template_type;
7297
7298       /* If we already have this specialization, return it.  */
7299       elt.tmpl = gen_tmpl;
7300       elt.args = arglist;
7301       hash = hash_specialization (&elt);
7302       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7303                                                   &elt, hash);
7304
7305       if (entry)
7306         return entry->spec;
7307
7308       is_dependent_type = uses_template_parms (arglist);
7309
7310       /* If the deduced arguments are invalid, then the binding
7311          failed.  */
7312       if (!is_dependent_type
7313           && check_instantiated_args (gen_tmpl,
7314                                       INNERMOST_TEMPLATE_ARGS (arglist),
7315                                       complain))
7316         return error_mark_node;
7317
7318       if (!is_dependent_type
7319           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7320           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7321           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7322         {
7323           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7324                                       DECL_NAME (gen_tmpl),
7325                                       /*tag_scope=*/ts_global);
7326           return found;
7327         }
7328
7329       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7330                         complain, in_decl);
7331       if (!context)
7332         context = global_namespace;
7333
7334       /* Create the type.  */
7335       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7336         {
7337           if (!is_dependent_type)
7338             {
7339               set_current_access_from_decl (TYPE_NAME (template_type));
7340               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7341                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7342                                       arglist, complain, in_decl),
7343                               SCOPED_ENUM_P (template_type), NULL);
7344             }
7345           else
7346             {
7347               /* We don't want to call start_enum for this type, since
7348                  the values for the enumeration constants may involve
7349                  template parameters.  And, no one should be interested
7350                  in the enumeration constants for such a type.  */
7351               t = cxx_make_type (ENUMERAL_TYPE);
7352               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7353             }
7354           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7355           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7356             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7357         }
7358       else
7359         {
7360           t = make_class_type (TREE_CODE (template_type));
7361           CLASSTYPE_DECLARED_CLASS (t)
7362             = CLASSTYPE_DECLARED_CLASS (template_type);
7363           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7364           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7365
7366           /* A local class.  Make sure the decl gets registered properly.  */
7367           if (context == current_function_decl)
7368             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7369
7370           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7371             /* This instantiation is another name for the primary
7372                template type. Set the TYPE_CANONICAL field
7373                appropriately. */
7374             TYPE_CANONICAL (t) = template_type;
7375           else if (any_template_arguments_need_structural_equality_p (arglist))
7376             /* Some of the template arguments require structural
7377                equality testing, so this template class requires
7378                structural equality testing. */
7379             SET_TYPE_STRUCTURAL_EQUALITY (t);
7380         }
7381
7382       /* If we called start_enum or pushtag above, this information
7383          will already be set up.  */
7384       if (!TYPE_NAME (t))
7385         {
7386           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7387
7388           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7389           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7390           DECL_SOURCE_LOCATION (type_decl)
7391             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7392         }
7393       else
7394         type_decl = TYPE_NAME (t);
7395
7396       TREE_PRIVATE (type_decl)
7397         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7398       TREE_PROTECTED (type_decl)
7399         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7400       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7401         {
7402           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7403           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7404         }
7405
7406       /* Let's consider the explicit specialization of a member
7407          of a class template specialization that is implicitely instantiated,
7408          e.g.:
7409              template<class T>
7410              struct S
7411              {
7412                template<class U> struct M {}; //#0
7413              };
7414
7415              template<>
7416              template<>
7417              struct S<int>::M<char> //#1
7418              {
7419                int i;
7420              };
7421         [temp.expl.spec]/4 says this is valid.
7422
7423         In this case, when we write:
7424         S<int>::M<char> m;
7425
7426         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7427         the one of #0.
7428
7429         When we encounter #1, we want to store the partial instantiation
7430         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7431
7432         For all cases other than this "explicit specialization of member of a
7433         class template", we just want to store the most general template into
7434         the CLASSTYPE_TI_TEMPLATE of M.
7435
7436         This case of "explicit specialization of member of a class template"
7437         only happens when:
7438         1/ the enclosing class is an instantiation of, and therefore not
7439         the same as, the context of the most general template, and
7440         2/ we aren't looking at the partial instantiation itself, i.e.
7441         the innermost arguments are not the same as the innermost parms of
7442         the most general template.
7443
7444         So it's only when 1/ and 2/ happens that we want to use the partial
7445         instantiation of the member template in lieu of its most general
7446         template.  */
7447
7448       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7449           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7450           /* the enclosing class must be an instantiation...  */
7451           && CLASS_TYPE_P (context)
7452           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7453         {
7454           tree partial_inst_args;
7455           TREE_VEC_LENGTH (arglist)--;
7456           ++processing_template_decl;
7457           partial_inst_args =
7458             tsubst (INNERMOST_TEMPLATE_ARGS
7459                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7460                     arglist, complain, NULL_TREE);
7461           --processing_template_decl;
7462           TREE_VEC_LENGTH (arglist)++;
7463           use_partial_inst_tmpl =
7464             /*...and we must not be looking at the partial instantiation
7465              itself. */
7466             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7467                                  partial_inst_args);
7468         }
7469
7470       if (!use_partial_inst_tmpl)
7471         /* This case is easy; there are no member templates involved.  */
7472         found = gen_tmpl;
7473       else
7474         {
7475           /* This is a full instantiation of a member template.  Find
7476              the partial instantiation of which this is an instance.  */
7477
7478           /* Temporarily reduce by one the number of levels in the ARGLIST
7479              so as to avoid comparing the last set of arguments.  */
7480           TREE_VEC_LENGTH (arglist)--;
7481           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7482           TREE_VEC_LENGTH (arglist)++;
7483           found = CLASSTYPE_TI_TEMPLATE (found);
7484         }
7485
7486       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7487
7488       elt.spec = t;
7489       slot = htab_find_slot_with_hash (type_specializations,
7490                                        &elt, hash, INSERT);
7491       entry = ggc_alloc_spec_entry ();
7492       *entry = elt;
7493       *slot = entry;
7494
7495       /* Note this use of the partial instantiation so we can check it
7496          later in maybe_process_partial_specialization.  */
7497       DECL_TEMPLATE_INSTANTIATIONS (templ)
7498         = tree_cons (arglist, t,
7499                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7500
7501       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7502         /* Now that the type has been registered on the instantiations
7503            list, we set up the enumerators.  Because the enumeration
7504            constants may involve the enumeration type itself, we make
7505            sure to register the type first, and then create the
7506            constants.  That way, doing tsubst_expr for the enumeration
7507            constants won't result in recursive calls here; we'll find
7508            the instantiation and exit above.  */
7509         tsubst_enum (template_type, t, arglist);
7510
7511       if (is_dependent_type)
7512         /* If the type makes use of template parameters, the
7513            code that generates debugging information will crash.  */
7514         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7515
7516       /* Possibly limit visibility based on template args.  */
7517       TREE_PUBLIC (type_decl) = 1;
7518       determine_visibility (type_decl);
7519
7520       return t;
7521     }
7522 }
7523
7524 /* Wrapper for lookup_template_class_1.  */
7525
7526 tree
7527 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7528                        int entering_scope, tsubst_flags_t complain)
7529 {
7530   tree ret;
7531   timevar_push (TV_TEMPLATE_INST);
7532   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7533                                  entering_scope, complain);
7534   timevar_pop (TV_TEMPLATE_INST);
7535   return ret;
7536 }
7537 \f
7538 struct pair_fn_data
7539 {
7540   tree_fn_t fn;
7541   void *data;
7542   /* True when we should also visit template parameters that occur in
7543      non-deduced contexts.  */
7544   bool include_nondeduced_p;
7545   struct pointer_set_t *visited;
7546 };
7547
7548 /* Called from for_each_template_parm via walk_tree.  */
7549
7550 static tree
7551 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7552 {
7553   tree t = *tp;
7554   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7555   tree_fn_t fn = pfd->fn;
7556   void *data = pfd->data;
7557
7558   if (TYPE_P (t)
7559       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7560       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7561                                  pfd->include_nondeduced_p))
7562     return error_mark_node;
7563
7564   switch (TREE_CODE (t))
7565     {
7566     case RECORD_TYPE:
7567       if (TYPE_PTRMEMFUNC_P (t))
7568         break;
7569       /* Fall through.  */
7570
7571     case UNION_TYPE:
7572     case ENUMERAL_TYPE:
7573       if (!TYPE_TEMPLATE_INFO (t))
7574         *walk_subtrees = 0;
7575       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7576                                        fn, data, pfd->visited, 
7577                                        pfd->include_nondeduced_p))
7578         return error_mark_node;
7579       break;
7580
7581     case INTEGER_TYPE:
7582       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7583                                   fn, data, pfd->visited, 
7584                                   pfd->include_nondeduced_p)
7585           || for_each_template_parm (TYPE_MAX_VALUE (t),
7586                                      fn, data, pfd->visited,
7587                                      pfd->include_nondeduced_p))
7588         return error_mark_node;
7589       break;
7590
7591     case METHOD_TYPE:
7592       /* Since we're not going to walk subtrees, we have to do this
7593          explicitly here.  */
7594       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7595                                   pfd->visited, pfd->include_nondeduced_p))
7596         return error_mark_node;
7597       /* Fall through.  */
7598
7599     case FUNCTION_TYPE:
7600       /* Check the return type.  */
7601       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7602                                   pfd->include_nondeduced_p))
7603         return error_mark_node;
7604
7605       /* Check the parameter types.  Since default arguments are not
7606          instantiated until they are needed, the TYPE_ARG_TYPES may
7607          contain expressions that involve template parameters.  But,
7608          no-one should be looking at them yet.  And, once they're
7609          instantiated, they don't contain template parameters, so
7610          there's no point in looking at them then, either.  */
7611       {
7612         tree parm;
7613
7614         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7615           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7616                                       pfd->visited, pfd->include_nondeduced_p))
7617             return error_mark_node;
7618
7619         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7620            want walk_tree walking into them itself.  */
7621         *walk_subtrees = 0;
7622       }
7623       break;
7624
7625     case TYPEOF_TYPE:
7626     case UNDERLYING_TYPE:
7627       if (pfd->include_nondeduced_p
7628           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7629                                      pfd->visited, 
7630                                      pfd->include_nondeduced_p))
7631         return error_mark_node;
7632       break;
7633
7634     case FUNCTION_DECL:
7635     case VAR_DECL:
7636       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7637           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7638                                      pfd->visited, pfd->include_nondeduced_p))
7639         return error_mark_node;
7640       /* Fall through.  */
7641
7642     case PARM_DECL:
7643     case CONST_DECL:
7644       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7645           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7646                                      pfd->visited, pfd->include_nondeduced_p))
7647         return error_mark_node;
7648       if (DECL_CONTEXT (t)
7649           && pfd->include_nondeduced_p
7650           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7651                                      pfd->visited, pfd->include_nondeduced_p))
7652         return error_mark_node;
7653       break;
7654
7655     case BOUND_TEMPLATE_TEMPLATE_PARM:
7656       /* Record template parameters such as `T' inside `TT<T>'.  */
7657       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7658                                   pfd->include_nondeduced_p))
7659         return error_mark_node;
7660       /* Fall through.  */
7661
7662     case TEMPLATE_TEMPLATE_PARM:
7663     case TEMPLATE_TYPE_PARM:
7664     case TEMPLATE_PARM_INDEX:
7665       if (fn && (*fn)(t, data))
7666         return error_mark_node;
7667       else if (!fn)
7668         return error_mark_node;
7669       break;
7670
7671     case TEMPLATE_DECL:
7672       /* A template template parameter is encountered.  */
7673       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7674           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7675                                      pfd->include_nondeduced_p))
7676         return error_mark_node;
7677
7678       /* Already substituted template template parameter */
7679       *walk_subtrees = 0;
7680       break;
7681
7682     case TYPENAME_TYPE:
7683       if (!fn
7684           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7685                                      data, pfd->visited, 
7686                                      pfd->include_nondeduced_p))
7687         return error_mark_node;
7688       break;
7689
7690     case CONSTRUCTOR:
7691       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7692           && pfd->include_nondeduced_p
7693           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7694                                      (TREE_TYPE (t)), fn, data,
7695                                      pfd->visited, pfd->include_nondeduced_p))
7696         return error_mark_node;
7697       break;
7698
7699     case INDIRECT_REF:
7700     case COMPONENT_REF:
7701       /* If there's no type, then this thing must be some expression
7702          involving template parameters.  */
7703       if (!fn && !TREE_TYPE (t))
7704         return error_mark_node;
7705       break;
7706
7707     case MODOP_EXPR:
7708     case CAST_EXPR:
7709     case IMPLICIT_CONV_EXPR:
7710     case REINTERPRET_CAST_EXPR:
7711     case CONST_CAST_EXPR:
7712     case STATIC_CAST_EXPR:
7713     case DYNAMIC_CAST_EXPR:
7714     case ARROW_EXPR:
7715     case DOTSTAR_EXPR:
7716     case TYPEID_EXPR:
7717     case PSEUDO_DTOR_EXPR:
7718       if (!fn)
7719         return error_mark_node;
7720       break;
7721
7722     default:
7723       break;
7724     }
7725
7726   /* We didn't find any template parameters we liked.  */
7727   return NULL_TREE;
7728 }
7729
7730 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7731    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7732    call FN with the parameter and the DATA.
7733    If FN returns nonzero, the iteration is terminated, and
7734    for_each_template_parm returns 1.  Otherwise, the iteration
7735    continues.  If FN never returns a nonzero value, the value
7736    returned by for_each_template_parm is 0.  If FN is NULL, it is
7737    considered to be the function which always returns 1.
7738
7739    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7740    parameters that occur in non-deduced contexts.  When false, only
7741    visits those template parameters that can be deduced.  */
7742
7743 static int
7744 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7745                         struct pointer_set_t *visited,
7746                         bool include_nondeduced_p)
7747 {
7748   struct pair_fn_data pfd;
7749   int result;
7750
7751   /* Set up.  */
7752   pfd.fn = fn;
7753   pfd.data = data;
7754   pfd.include_nondeduced_p = include_nondeduced_p;
7755
7756   /* Walk the tree.  (Conceptually, we would like to walk without
7757      duplicates, but for_each_template_parm_r recursively calls
7758      for_each_template_parm, so we would need to reorganize a fair
7759      bit to use walk_tree_without_duplicates, so we keep our own
7760      visited list.)  */
7761   if (visited)
7762     pfd.visited = visited;
7763   else
7764     pfd.visited = pointer_set_create ();
7765   result = cp_walk_tree (&t,
7766                          for_each_template_parm_r,
7767                          &pfd,
7768                          pfd.visited) != NULL_TREE;
7769
7770   /* Clean up.  */
7771   if (!visited)
7772     {
7773       pointer_set_destroy (pfd.visited);
7774       pfd.visited = 0;
7775     }
7776
7777   return result;
7778 }
7779
7780 /* Returns true if T depends on any template parameter.  */
7781
7782 int
7783 uses_template_parms (tree t)
7784 {
7785   bool dependent_p;
7786   int saved_processing_template_decl;
7787
7788   saved_processing_template_decl = processing_template_decl;
7789   if (!saved_processing_template_decl)
7790     processing_template_decl = 1;
7791   if (TYPE_P (t))
7792     dependent_p = dependent_type_p (t);
7793   else if (TREE_CODE (t) == TREE_VEC)
7794     dependent_p = any_dependent_template_arguments_p (t);
7795   else if (TREE_CODE (t) == TREE_LIST)
7796     dependent_p = (uses_template_parms (TREE_VALUE (t))
7797                    || uses_template_parms (TREE_CHAIN (t)));
7798   else if (TREE_CODE (t) == TYPE_DECL)
7799     dependent_p = dependent_type_p (TREE_TYPE (t));
7800   else if (DECL_P (t)
7801            || EXPR_P (t)
7802            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7803            || TREE_CODE (t) == OVERLOAD
7804            || BASELINK_P (t)
7805            || TREE_CODE (t) == IDENTIFIER_NODE
7806            || TREE_CODE (t) == TRAIT_EXPR
7807            || TREE_CODE (t) == CONSTRUCTOR
7808            || CONSTANT_CLASS_P (t))
7809     dependent_p = (type_dependent_expression_p (t)
7810                    || value_dependent_expression_p (t));
7811   else
7812     {
7813       gcc_assert (t == error_mark_node);
7814       dependent_p = false;
7815     }
7816
7817   processing_template_decl = saved_processing_template_decl;
7818
7819   return dependent_p;
7820 }
7821
7822 /* Returns true if T depends on any template parameter with level LEVEL.  */
7823
7824 int
7825 uses_template_parms_level (tree t, int level)
7826 {
7827   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7828                                  /*include_nondeduced_p=*/true);
7829 }
7830
7831 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7832    ill-formed translation unit, i.e. a variable or function that isn't
7833    usable in a constant expression.  */
7834
7835 static inline bool
7836 neglectable_inst_p (tree d)
7837 {
7838   return (DECL_P (d)
7839           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7840                : decl_maybe_constant_var_p (d)));
7841 }
7842
7843 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7844    neglectable and instantiated from within an erroneous instantiation.  */
7845
7846 static bool
7847 limit_bad_template_recursion (tree decl)
7848 {
7849   struct tinst_level *lev = current_tinst_level;
7850   int errs = errorcount + sorrycount;
7851   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7852     return false;
7853
7854   for (; lev; lev = lev->next)
7855     if (neglectable_inst_p (lev->decl))
7856       break;
7857
7858   return (lev && errs > lev->errors);
7859 }
7860
7861 static int tinst_depth;
7862 extern int max_tinst_depth;
7863 #ifdef GATHER_STATISTICS
7864 int depth_reached;
7865 #endif
7866 static GTY(()) struct tinst_level *last_error_tinst_level;
7867
7868 /* We're starting to instantiate D; record the template instantiation context
7869    for diagnostics and to restore it later.  */
7870
7871 int
7872 push_tinst_level (tree d)
7873 {
7874   struct tinst_level *new_level;
7875
7876   if (tinst_depth >= max_tinst_depth)
7877     {
7878       last_error_tinst_level = current_tinst_level;
7879       if (TREE_CODE (d) == TREE_LIST)
7880         error ("template instantiation depth exceeds maximum of %d (use "
7881                "-ftemplate-depth= to increase the maximum) substituting %qS",
7882                max_tinst_depth, d);
7883       else
7884         error ("template instantiation depth exceeds maximum of %d (use "
7885                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7886                max_tinst_depth, d);
7887
7888       print_instantiation_context ();
7889
7890       return 0;
7891     }
7892
7893   /* If the current instantiation caused problems, don't let it instantiate
7894      anything else.  Do allow deduction substitution and decls usable in
7895      constant expressions.  */
7896   if (limit_bad_template_recursion (d))
7897     return 0;
7898
7899   new_level = ggc_alloc_tinst_level ();
7900   new_level->decl = d;
7901   new_level->locus = input_location;
7902   new_level->errors = errorcount+sorrycount;
7903   new_level->in_system_header_p = in_system_header;
7904   new_level->next = current_tinst_level;
7905   current_tinst_level = new_level;
7906
7907   ++tinst_depth;
7908 #ifdef GATHER_STATISTICS
7909   if (tinst_depth > depth_reached)
7910     depth_reached = tinst_depth;
7911 #endif
7912
7913   return 1;
7914 }
7915
7916 /* We're done instantiating this template; return to the instantiation
7917    context.  */
7918
7919 void
7920 pop_tinst_level (void)
7921 {
7922   /* Restore the filename and line number stashed away when we started
7923      this instantiation.  */
7924   input_location = current_tinst_level->locus;
7925   current_tinst_level = current_tinst_level->next;
7926   --tinst_depth;
7927 }
7928
7929 /* We're instantiating a deferred template; restore the template
7930    instantiation context in which the instantiation was requested, which
7931    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7932
7933 static tree
7934 reopen_tinst_level (struct tinst_level *level)
7935 {
7936   struct tinst_level *t;
7937
7938   tinst_depth = 0;
7939   for (t = level; t; t = t->next)
7940     ++tinst_depth;
7941
7942   current_tinst_level = level;
7943   pop_tinst_level ();
7944   if (current_tinst_level)
7945     current_tinst_level->errors = errorcount+sorrycount;
7946   return level->decl;
7947 }
7948
7949 /* Returns the TINST_LEVEL which gives the original instantiation
7950    context.  */
7951
7952 struct tinst_level *
7953 outermost_tinst_level (void)
7954 {
7955   struct tinst_level *level = current_tinst_level;
7956   if (level)
7957     while (level->next)
7958       level = level->next;
7959   return level;
7960 }
7961
7962 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7963
7964 bool
7965 parameter_of_template_p (tree parm, tree templ)
7966 {
7967   tree parms;
7968   int i;
7969
7970   if (!parm || !templ)
7971     return false;
7972
7973   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7974   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7975
7976   parms = DECL_TEMPLATE_PARMS (templ);
7977   parms = INNERMOST_TEMPLATE_PARMS (parms);
7978
7979   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7980     {
7981       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7982       if (parm == p
7983           || (DECL_INITIAL (parm)
7984               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7985         return true;
7986     }
7987
7988   return false;
7989 }
7990
7991 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7992    vector of template arguments, as for tsubst.
7993
7994    Returns an appropriate tsubst'd friend declaration.  */
7995
7996 static tree
7997 tsubst_friend_function (tree decl, tree args)
7998 {
7999   tree new_friend;
8000
8001   if (TREE_CODE (decl) == FUNCTION_DECL
8002       && DECL_TEMPLATE_INSTANTIATION (decl)
8003       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8004     /* This was a friend declared with an explicit template
8005        argument list, e.g.:
8006
8007        friend void f<>(T);
8008
8009        to indicate that f was a template instantiation, not a new
8010        function declaration.  Now, we have to figure out what
8011        instantiation of what template.  */
8012     {
8013       tree template_id, arglist, fns;
8014       tree new_args;
8015       tree tmpl;
8016       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8017
8018       /* Friend functions are looked up in the containing namespace scope.
8019          We must enter that scope, to avoid finding member functions of the
8020          current class with same name.  */
8021       push_nested_namespace (ns);
8022       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8023                          tf_warning_or_error, NULL_TREE,
8024                          /*integral_constant_expression_p=*/false);
8025       pop_nested_namespace (ns);
8026       arglist = tsubst (DECL_TI_ARGS (decl), args,
8027                         tf_warning_or_error, NULL_TREE);
8028       template_id = lookup_template_function (fns, arglist);
8029
8030       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8031       tmpl = determine_specialization (template_id, new_friend,
8032                                        &new_args,
8033                                        /*need_member_template=*/0,
8034                                        TREE_VEC_LENGTH (args),
8035                                        tsk_none);
8036       return instantiate_template (tmpl, new_args, tf_error);
8037     }
8038
8039   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8040
8041   /* The NEW_FRIEND will look like an instantiation, to the
8042      compiler, but is not an instantiation from the point of view of
8043      the language.  For example, we might have had:
8044
8045      template <class T> struct S {
8046        template <class U> friend void f(T, U);
8047      };
8048
8049      Then, in S<int>, template <class U> void f(int, U) is not an
8050      instantiation of anything.  */
8051   if (new_friend == error_mark_node)
8052     return error_mark_node;
8053
8054   DECL_USE_TEMPLATE (new_friend) = 0;
8055   if (TREE_CODE (decl) == TEMPLATE_DECL)
8056     {
8057       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8058       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8059         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8060     }
8061
8062   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8063      is not a template instantiation and should not be mangled like
8064      one.  Therefore, we forget the mangling here; we'll recompute it
8065      later if we need it.  */
8066   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8067     {
8068       SET_DECL_RTL (new_friend, NULL);
8069       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8070     }
8071
8072   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8073     {
8074       tree old_decl;
8075       tree new_friend_template_info;
8076       tree new_friend_result_template_info;
8077       tree ns;
8078       int  new_friend_is_defn;
8079
8080       /* We must save some information from NEW_FRIEND before calling
8081          duplicate decls since that function will free NEW_FRIEND if
8082          possible.  */
8083       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8084       new_friend_is_defn =
8085             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8086                            (template_for_substitution (new_friend)))
8087              != NULL_TREE);
8088       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8089         {
8090           /* This declaration is a `primary' template.  */
8091           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8092
8093           new_friend_result_template_info
8094             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8095         }
8096       else
8097         new_friend_result_template_info = NULL_TREE;
8098
8099       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8100       if (new_friend_is_defn)
8101         DECL_INITIAL (new_friend) = error_mark_node;
8102
8103       /* Inside pushdecl_namespace_level, we will push into the
8104          current namespace. However, the friend function should go
8105          into the namespace of the template.  */
8106       ns = decl_namespace_context (new_friend);
8107       push_nested_namespace (ns);
8108       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8109       pop_nested_namespace (ns);
8110
8111       if (old_decl == error_mark_node)
8112         return error_mark_node;
8113
8114       if (old_decl != new_friend)
8115         {
8116           /* This new friend declaration matched an existing
8117              declaration.  For example, given:
8118
8119                template <class T> void f(T);
8120                template <class U> class C {
8121                  template <class T> friend void f(T) {}
8122                };
8123
8124              the friend declaration actually provides the definition
8125              of `f', once C has been instantiated for some type.  So,
8126              old_decl will be the out-of-class template declaration,
8127              while new_friend is the in-class definition.
8128
8129              But, if `f' was called before this point, the
8130              instantiation of `f' will have DECL_TI_ARGS corresponding
8131              to `T' but not to `U', references to which might appear
8132              in the definition of `f'.  Previously, the most general
8133              template for an instantiation of `f' was the out-of-class
8134              version; now it is the in-class version.  Therefore, we
8135              run through all specialization of `f', adding to their
8136              DECL_TI_ARGS appropriately.  In particular, they need a
8137              new set of outer arguments, corresponding to the
8138              arguments for this class instantiation.
8139
8140              The same situation can arise with something like this:
8141
8142                friend void f(int);
8143                template <class T> class C {
8144                  friend void f(T) {}
8145                };
8146
8147              when `C<int>' is instantiated.  Now, `f(int)' is defined
8148              in the class.  */
8149
8150           if (!new_friend_is_defn)
8151             /* On the other hand, if the in-class declaration does
8152                *not* provide a definition, then we don't want to alter
8153                existing definitions.  We can just leave everything
8154                alone.  */
8155             ;
8156           else
8157             {
8158               tree new_template = TI_TEMPLATE (new_friend_template_info);
8159               tree new_args = TI_ARGS (new_friend_template_info);
8160
8161               /* Overwrite whatever template info was there before, if
8162                  any, with the new template information pertaining to
8163                  the declaration.  */
8164               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8165
8166               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8167                 {
8168                   /* We should have called reregister_specialization in
8169                      duplicate_decls.  */
8170                   gcc_assert (retrieve_specialization (new_template,
8171                                                        new_args, 0)
8172                               == old_decl);
8173
8174                   /* Instantiate it if the global has already been used.  */
8175                   if (DECL_ODR_USED (old_decl))
8176                     instantiate_decl (old_decl, /*defer_ok=*/true,
8177                                       /*expl_inst_class_mem_p=*/false);
8178                 }
8179               else
8180                 {
8181                   tree t;
8182
8183                   /* Indicate that the old function template is a partial
8184                      instantiation.  */
8185                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8186                     = new_friend_result_template_info;
8187
8188                   gcc_assert (new_template
8189                               == most_general_template (new_template));
8190                   gcc_assert (new_template != old_decl);
8191
8192                   /* Reassign any specializations already in the hash table
8193                      to the new more general template, and add the
8194                      additional template args.  */
8195                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8196                        t != NULL_TREE;
8197                        t = TREE_CHAIN (t))
8198                     {
8199                       tree spec = TREE_VALUE (t);
8200                       spec_entry elt;
8201
8202                       elt.tmpl = old_decl;
8203                       elt.args = DECL_TI_ARGS (spec);
8204                       elt.spec = NULL_TREE;
8205
8206                       htab_remove_elt (decl_specializations, &elt);
8207
8208                       DECL_TI_ARGS (spec)
8209                         = add_outermost_template_args (new_args,
8210                                                        DECL_TI_ARGS (spec));
8211
8212                       register_specialization
8213                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8214
8215                     }
8216                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8217                 }
8218             }
8219
8220           /* The information from NEW_FRIEND has been merged into OLD_DECL
8221              by duplicate_decls.  */
8222           new_friend = old_decl;
8223         }
8224     }
8225   else
8226     {
8227       tree context = DECL_CONTEXT (new_friend);
8228       bool dependent_p;
8229
8230       /* In the code
8231            template <class T> class C {
8232              template <class U> friend void C1<U>::f (); // case 1
8233              friend void C2<T>::f ();                    // case 2
8234            };
8235          we only need to make sure CONTEXT is a complete type for
8236          case 2.  To distinguish between the two cases, we note that
8237          CONTEXT of case 1 remains dependent type after tsubst while
8238          this isn't true for case 2.  */
8239       ++processing_template_decl;
8240       dependent_p = dependent_type_p (context);
8241       --processing_template_decl;
8242
8243       if (!dependent_p
8244           && !complete_type_or_else (context, NULL_TREE))
8245         return error_mark_node;
8246
8247       if (COMPLETE_TYPE_P (context))
8248         {
8249           /* Check to see that the declaration is really present, and,
8250              possibly obtain an improved declaration.  */
8251           tree fn = check_classfn (context,
8252                                    new_friend, NULL_TREE);
8253
8254           if (fn)
8255             new_friend = fn;
8256         }
8257     }
8258
8259   return new_friend;
8260 }
8261
8262 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8263    template arguments, as for tsubst.
8264
8265    Returns an appropriate tsubst'd friend type or error_mark_node on
8266    failure.  */
8267
8268 static tree
8269 tsubst_friend_class (tree friend_tmpl, tree args)
8270 {
8271   tree friend_type;
8272   tree tmpl;
8273   tree context;
8274
8275   context = CP_DECL_CONTEXT (friend_tmpl);
8276
8277   if (context != global_namespace)
8278     {
8279       if (TREE_CODE (context) == NAMESPACE_DECL)
8280         push_nested_namespace (context);
8281       else
8282         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8283     }
8284
8285   /* Look for a class template declaration.  We look for hidden names
8286      because two friend declarations of the same template are the
8287      same.  For example, in:
8288
8289        struct A { 
8290          template <typename> friend class F;
8291        };
8292        template <typename> struct B { 
8293          template <typename> friend class F;
8294        };
8295
8296      both F templates are the same.  */
8297   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8298                            /*block_p=*/true, 0, 
8299                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8300
8301   /* But, if we don't find one, it might be because we're in a
8302      situation like this:
8303
8304        template <class T>
8305        struct S {
8306          template <class U>
8307          friend struct S;
8308        };
8309
8310      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8311      for `S<int>', not the TEMPLATE_DECL.  */
8312   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8313     {
8314       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8315       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8316     }
8317
8318   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8319     {
8320       /* The friend template has already been declared.  Just
8321          check to see that the declarations match, and install any new
8322          default parameters.  We must tsubst the default parameters,
8323          of course.  We only need the innermost template parameters
8324          because that is all that redeclare_class_template will look
8325          at.  */
8326       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8327           > TMPL_ARGS_DEPTH (args))
8328         {
8329           tree parms;
8330           location_t saved_input_location;
8331           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8332                                          args, tf_warning_or_error);
8333
8334           saved_input_location = input_location;
8335           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8336           redeclare_class_template (TREE_TYPE (tmpl), parms);
8337           input_location = saved_input_location;
8338           
8339         }
8340
8341       friend_type = TREE_TYPE (tmpl);
8342     }
8343   else
8344     {
8345       /* The friend template has not already been declared.  In this
8346          case, the instantiation of the template class will cause the
8347          injection of this template into the global scope.  */
8348       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8349       if (tmpl == error_mark_node)
8350         return error_mark_node;
8351
8352       /* The new TMPL is not an instantiation of anything, so we
8353          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8354          the new type because that is supposed to be the corresponding
8355          template decl, i.e., TMPL.  */
8356       DECL_USE_TEMPLATE (tmpl) = 0;
8357       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8358       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8359       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8360         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8361
8362       /* Inject this template into the global scope.  */
8363       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8364     }
8365
8366   if (context != global_namespace)
8367     {
8368       if (TREE_CODE (context) == NAMESPACE_DECL)
8369         pop_nested_namespace (context);
8370       else
8371         pop_nested_class ();
8372     }
8373
8374   return friend_type;
8375 }
8376
8377 /* Returns zero if TYPE cannot be completed later due to circularity.
8378    Otherwise returns one.  */
8379
8380 static int
8381 can_complete_type_without_circularity (tree type)
8382 {
8383   if (type == NULL_TREE || type == error_mark_node)
8384     return 0;
8385   else if (COMPLETE_TYPE_P (type))
8386     return 1;
8387   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8388     return can_complete_type_without_circularity (TREE_TYPE (type));
8389   else if (CLASS_TYPE_P (type)
8390            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8391     return 0;
8392   else
8393     return 1;
8394 }
8395
8396 /* Apply any attributes which had to be deferred until instantiation
8397    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8398    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8399
8400 static void
8401 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8402                                 tree args, tsubst_flags_t complain, tree in_decl)
8403 {
8404   tree last_dep = NULL_TREE;
8405   tree t;
8406   tree *p;
8407
8408   for (t = attributes; t; t = TREE_CHAIN (t))
8409     if (ATTR_IS_DEPENDENT (t))
8410       {
8411         last_dep = t;
8412         attributes = copy_list (attributes);
8413         break;
8414       }
8415
8416   if (DECL_P (*decl_p))
8417     {
8418       if (TREE_TYPE (*decl_p) == error_mark_node)
8419         return;
8420       p = &DECL_ATTRIBUTES (*decl_p);
8421     }
8422   else
8423     p = &TYPE_ATTRIBUTES (*decl_p);
8424
8425   if (last_dep)
8426     {
8427       tree late_attrs = NULL_TREE;
8428       tree *q = &late_attrs;
8429
8430       for (*p = attributes; *p; )
8431         {
8432           t = *p;
8433           if (ATTR_IS_DEPENDENT (t))
8434             {
8435               *p = TREE_CHAIN (t);
8436               TREE_CHAIN (t) = NULL_TREE;
8437               /* If the first attribute argument is an identifier, don't
8438                  pass it through tsubst.  Attributes like mode, format,
8439                  cleanup and several target specific attributes expect it
8440                  unmodified.  */
8441               if (TREE_VALUE (t)
8442                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8443                   && TREE_VALUE (TREE_VALUE (t))
8444                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8445                       == IDENTIFIER_NODE))
8446                 {
8447                   tree chain
8448                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8449                                    in_decl,
8450                                    /*integral_constant_expression_p=*/false);
8451                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8452                     TREE_VALUE (t)
8453                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8454                                    chain);
8455                 }
8456               else
8457                 TREE_VALUE (t)
8458                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8459                                  /*integral_constant_expression_p=*/false);
8460               *q = t;
8461               q = &TREE_CHAIN (t);
8462             }
8463           else
8464             p = &TREE_CHAIN (t);
8465         }
8466
8467       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8468     }
8469 }
8470
8471 /* Perform (or defer) access check for typedefs that were referenced
8472    from within the template TMPL code.
8473    This is a subroutine of instantiate_template and instantiate_class_template.
8474    TMPL is the template to consider and TARGS is the list of arguments of
8475    that template.  */
8476
8477 static void
8478 perform_typedefs_access_check (tree tmpl, tree targs)
8479 {
8480   location_t saved_location;
8481   int i;
8482   qualified_typedef_usage_t *iter;
8483
8484   if (!tmpl
8485       || (!CLASS_TYPE_P (tmpl)
8486           && TREE_CODE (tmpl) != FUNCTION_DECL))
8487     return;
8488
8489   saved_location = input_location;
8490   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8491                     get_types_needing_access_check (tmpl),
8492                     i, iter)
8493     {
8494       tree type_decl = iter->typedef_decl;
8495       tree type_scope = iter->context;
8496
8497       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8498         continue;
8499
8500       if (uses_template_parms (type_decl))
8501         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8502       if (uses_template_parms (type_scope))
8503         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8504
8505       /* Make access check error messages point to the location
8506          of the use of the typedef.  */
8507       input_location = iter->locus;
8508       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8509                                      type_decl, type_decl);
8510     }
8511     input_location = saved_location;
8512 }
8513
8514 static tree
8515 instantiate_class_template_1 (tree type)
8516 {
8517   tree templ, args, pattern, t, member;
8518   tree typedecl;
8519   tree pbinfo;
8520   tree base_list;
8521   unsigned int saved_maximum_field_alignment;
8522
8523   if (type == error_mark_node)
8524     return error_mark_node;
8525
8526   if (COMPLETE_OR_OPEN_TYPE_P (type)
8527       || uses_template_parms (type))
8528     return type;
8529
8530   /* Figure out which template is being instantiated.  */
8531   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8532   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8533
8534   /* Determine what specialization of the original template to
8535      instantiate.  */
8536   t = most_specialized_class (type, templ, tf_warning_or_error);
8537   if (t == error_mark_node)
8538     {
8539       TYPE_BEING_DEFINED (type) = 1;
8540       return error_mark_node;
8541     }
8542   else if (t)
8543     {
8544       /* This TYPE is actually an instantiation of a partial
8545          specialization.  We replace the innermost set of ARGS with
8546          the arguments appropriate for substitution.  For example,
8547          given:
8548
8549            template <class T> struct S {};
8550            template <class T> struct S<T*> {};
8551
8552          and supposing that we are instantiating S<int*>, ARGS will
8553          presently be {int*} -- but we need {int}.  */
8554       pattern = TREE_TYPE (t);
8555       args = TREE_PURPOSE (t);
8556     }
8557   else
8558     {
8559       pattern = TREE_TYPE (templ);
8560       args = CLASSTYPE_TI_ARGS (type);
8561     }
8562
8563   /* If the template we're instantiating is incomplete, then clearly
8564      there's nothing we can do.  */
8565   if (!COMPLETE_TYPE_P (pattern))
8566     return type;
8567
8568   /* If we've recursively instantiated too many templates, stop.  */
8569   if (! push_tinst_level (type))
8570     return type;
8571
8572   /* Now we're really doing the instantiation.  Mark the type as in
8573      the process of being defined.  */
8574   TYPE_BEING_DEFINED (type) = 1;
8575
8576   /* We may be in the middle of deferred access check.  Disable
8577      it now.  */
8578   push_deferring_access_checks (dk_no_deferred);
8579
8580   push_to_top_level ();
8581   /* Use #pragma pack from the template context.  */
8582   saved_maximum_field_alignment = maximum_field_alignment;
8583   maximum_field_alignment = TYPE_PRECISION (pattern);
8584
8585   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8586
8587   /* Set the input location to the most specialized template definition.
8588      This is needed if tsubsting causes an error.  */
8589   typedecl = TYPE_MAIN_DECL (pattern);
8590   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8591     DECL_SOURCE_LOCATION (typedecl);
8592
8593   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8594   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8595   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8596   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8597   if (ANON_AGGR_TYPE_P (pattern))
8598     SET_ANON_AGGR_TYPE_P (type);
8599   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8600     {
8601       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8602       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8603     }
8604   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8605
8606   pbinfo = TYPE_BINFO (pattern);
8607
8608   /* We should never instantiate a nested class before its enclosing
8609      class; we need to look up the nested class by name before we can
8610      instantiate it, and that lookup should instantiate the enclosing
8611      class.  */
8612   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8613               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8614
8615   base_list = NULL_TREE;
8616   if (BINFO_N_BASE_BINFOS (pbinfo))
8617     {
8618       tree pbase_binfo;
8619       tree pushed_scope;
8620       int i;
8621
8622       /* We must enter the scope containing the type, as that is where
8623          the accessibility of types named in dependent bases are
8624          looked up from.  */
8625       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8626
8627       /* Substitute into each of the bases to determine the actual
8628          basetypes.  */
8629       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8630         {
8631           tree base;
8632           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8633           tree expanded_bases = NULL_TREE;
8634           int idx, len = 1;
8635
8636           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8637             {
8638               expanded_bases = 
8639                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8640                                        args, tf_error, NULL_TREE);
8641               if (expanded_bases == error_mark_node)
8642                 continue;
8643
8644               len = TREE_VEC_LENGTH (expanded_bases);
8645             }
8646
8647           for (idx = 0; idx < len; idx++)
8648             {
8649               if (expanded_bases)
8650                 /* Extract the already-expanded base class.  */
8651                 base = TREE_VEC_ELT (expanded_bases, idx);
8652               else
8653                 /* Substitute to figure out the base class.  */
8654                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8655                                NULL_TREE);
8656
8657               if (base == error_mark_node)
8658                 continue;
8659
8660               base_list = tree_cons (access, base, base_list);
8661               if (BINFO_VIRTUAL_P (pbase_binfo))
8662                 TREE_TYPE (base_list) = integer_type_node;
8663             }
8664         }
8665
8666       /* The list is now in reverse order; correct that.  */
8667       base_list = nreverse (base_list);
8668
8669       if (pushed_scope)
8670         pop_scope (pushed_scope);
8671     }
8672   /* Now call xref_basetypes to set up all the base-class
8673      information.  */
8674   xref_basetypes (type, base_list);
8675
8676   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8677                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8678                                   args, tf_error, NULL_TREE);
8679   fixup_attribute_variants (type);
8680
8681   /* Now that our base classes are set up, enter the scope of the
8682      class, so that name lookups into base classes, etc. will work
8683      correctly.  This is precisely analogous to what we do in
8684      begin_class_definition when defining an ordinary non-template
8685      class, except we also need to push the enclosing classes.  */
8686   push_nested_class (type);
8687
8688   /* Now members are processed in the order of declaration.  */
8689   for (member = CLASSTYPE_DECL_LIST (pattern);
8690        member; member = TREE_CHAIN (member))
8691     {
8692       tree t = TREE_VALUE (member);
8693
8694       if (TREE_PURPOSE (member))
8695         {
8696           if (TYPE_P (t))
8697             {
8698               /* Build new CLASSTYPE_NESTED_UTDS.  */
8699
8700               tree newtag;
8701               bool class_template_p;
8702
8703               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8704                                   && TYPE_LANG_SPECIFIC (t)
8705                                   && CLASSTYPE_IS_TEMPLATE (t));
8706               /* If the member is a class template, then -- even after
8707                  substitution -- there may be dependent types in the
8708                  template argument list for the class.  We increment
8709                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8710                  that function will assume that no types are dependent
8711                  when outside of a template.  */
8712               if (class_template_p)
8713                 ++processing_template_decl;
8714               newtag = tsubst (t, args, tf_error, NULL_TREE);
8715               if (class_template_p)
8716                 --processing_template_decl;
8717               if (newtag == error_mark_node)
8718                 continue;
8719
8720               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8721                 {
8722                   tree name = TYPE_IDENTIFIER (t);
8723
8724                   if (class_template_p)
8725                     /* Unfortunately, lookup_template_class sets
8726                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8727                        instantiation (i.e., for the type of a member
8728                        template class nested within a template class.)
8729                        This behavior is required for
8730                        maybe_process_partial_specialization to work
8731                        correctly, but is not accurate in this case;
8732                        the TAG is not an instantiation of anything.
8733                        (The corresponding TEMPLATE_DECL is an
8734                        instantiation, but the TYPE is not.) */
8735                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8736
8737                   /* Now, we call pushtag to put this NEWTAG into the scope of
8738                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8739                      pushtag calling push_template_decl.  We don't have to do
8740                      this for enums because it will already have been done in
8741                      tsubst_enum.  */
8742                   if (name)
8743                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8744                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8745                 }
8746             }
8747           else if (TREE_CODE (t) == FUNCTION_DECL
8748                    || DECL_FUNCTION_TEMPLATE_P (t))
8749             {
8750               /* Build new TYPE_METHODS.  */
8751               tree r;
8752
8753               if (TREE_CODE (t) == TEMPLATE_DECL)
8754                 ++processing_template_decl;
8755               r = tsubst (t, args, tf_error, NULL_TREE);
8756               if (TREE_CODE (t) == TEMPLATE_DECL)
8757                 --processing_template_decl;
8758               set_current_access_from_decl (r);
8759               finish_member_declaration (r);
8760               /* Instantiate members marked with attribute used.  */
8761               if (r != error_mark_node && DECL_PRESERVE_P (r))
8762                 mark_used (r);
8763             }
8764           else
8765             {
8766               /* Build new TYPE_FIELDS.  */
8767               if (TREE_CODE (t) == STATIC_ASSERT)
8768                 {
8769                   tree condition = 
8770                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8771                                  tf_warning_or_error, NULL_TREE,
8772                                  /*integral_constant_expression_p=*/true);
8773                   finish_static_assert (condition,
8774                                         STATIC_ASSERT_MESSAGE (t), 
8775                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8776                                         /*member_p=*/true);
8777                 }
8778               else if (TREE_CODE (t) != CONST_DECL)
8779                 {
8780                   tree r;
8781
8782                   /* The file and line for this declaration, to
8783                      assist in error message reporting.  Since we
8784                      called push_tinst_level above, we don't need to
8785                      restore these.  */
8786                   input_location = DECL_SOURCE_LOCATION (t);
8787
8788                   if (TREE_CODE (t) == TEMPLATE_DECL)
8789                     ++processing_template_decl;
8790                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8791                   if (TREE_CODE (t) == TEMPLATE_DECL)
8792                     --processing_template_decl;
8793                   if (TREE_CODE (r) == VAR_DECL)
8794                     {
8795                       /* In [temp.inst]:
8796
8797                            [t]he initialization (and any associated
8798                            side-effects) of a static data member does
8799                            not occur unless the static data member is
8800                            itself used in a way that requires the
8801                            definition of the static data member to
8802                            exist.
8803
8804                          Therefore, we do not substitute into the
8805                          initialized for the static data member here.  */
8806                       finish_static_data_member_decl
8807                         (r,
8808                          /*init=*/NULL_TREE,
8809                          /*init_const_expr_p=*/false,
8810                          /*asmspec_tree=*/NULL_TREE,
8811                          /*flags=*/0);
8812                       /* Instantiate members marked with attribute used.  */
8813                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8814                         mark_used (r);
8815                     }
8816                   else if (TREE_CODE (r) == FIELD_DECL)
8817                     {
8818                       /* Determine whether R has a valid type and can be
8819                          completed later.  If R is invalid, then it is
8820                          replaced by error_mark_node so that it will not be
8821                          added to TYPE_FIELDS.  */
8822                       tree rtype = TREE_TYPE (r);
8823                       if (can_complete_type_without_circularity (rtype))
8824                         complete_type (rtype);
8825
8826                       if (!COMPLETE_TYPE_P (rtype))
8827                         {
8828                           cxx_incomplete_type_error (r, rtype);
8829                           r = error_mark_node;
8830                         }
8831                     }
8832
8833                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8834                      such a thing will already have been added to the field
8835                      list by tsubst_enum in finish_member_declaration in the
8836                      CLASSTYPE_NESTED_UTDS case above.  */
8837                   if (!(TREE_CODE (r) == TYPE_DECL
8838                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8839                         && DECL_ARTIFICIAL (r)))
8840                     {
8841                       set_current_access_from_decl (r);
8842                       finish_member_declaration (r);
8843                     }
8844                 }
8845             }
8846         }
8847       else
8848         {
8849           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8850             {
8851               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8852
8853               tree friend_type = t;
8854               bool adjust_processing_template_decl = false;
8855
8856               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8857                 {
8858                   /* template <class T> friend class C;  */
8859                   friend_type = tsubst_friend_class (friend_type, args);
8860                   adjust_processing_template_decl = true;
8861                 }
8862               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8863                 {
8864                   /* template <class T> friend class C::D;  */
8865                   friend_type = tsubst (friend_type, args,
8866                                         tf_warning_or_error, NULL_TREE);
8867                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8868                     friend_type = TREE_TYPE (friend_type);
8869                   adjust_processing_template_decl = true;
8870                 }
8871               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8872                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8873                 {
8874                   /* This could be either
8875
8876                        friend class T::C;
8877
8878                      when dependent_type_p is false or
8879
8880                        template <class U> friend class T::C;
8881
8882                      otherwise.  */
8883                   friend_type = tsubst (friend_type, args,
8884                                         tf_warning_or_error, NULL_TREE);
8885                   /* Bump processing_template_decl for correct
8886                      dependent_type_p calculation.  */
8887                   ++processing_template_decl;
8888                   if (dependent_type_p (friend_type))
8889                     adjust_processing_template_decl = true;
8890                   --processing_template_decl;
8891                 }
8892               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8893                        && hidden_name_p (TYPE_NAME (friend_type)))
8894                 {
8895                   /* friend class C;
8896
8897                      where C hasn't been declared yet.  Let's lookup name
8898                      from namespace scope directly, bypassing any name that
8899                      come from dependent base class.  */
8900                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8901
8902                   /* The call to xref_tag_from_type does injection for friend
8903                      classes.  */
8904                   push_nested_namespace (ns);
8905                   friend_type =
8906                     xref_tag_from_type (friend_type, NULL_TREE,
8907                                         /*tag_scope=*/ts_current);
8908                   pop_nested_namespace (ns);
8909                 }
8910               else if (uses_template_parms (friend_type))
8911                 /* friend class C<T>;  */
8912                 friend_type = tsubst (friend_type, args,
8913                                       tf_warning_or_error, NULL_TREE);
8914               /* Otherwise it's
8915
8916                    friend class C;
8917
8918                  where C is already declared or
8919
8920                    friend class C<int>;
8921
8922                  We don't have to do anything in these cases.  */
8923
8924               if (adjust_processing_template_decl)
8925                 /* Trick make_friend_class into realizing that the friend
8926                    we're adding is a template, not an ordinary class.  It's
8927                    important that we use make_friend_class since it will
8928                    perform some error-checking and output cross-reference
8929                    information.  */
8930                 ++processing_template_decl;
8931
8932               if (friend_type != error_mark_node)
8933                 make_friend_class (type, friend_type, /*complain=*/false);
8934
8935               if (adjust_processing_template_decl)
8936                 --processing_template_decl;
8937             }
8938           else
8939             {
8940               /* Build new DECL_FRIENDLIST.  */
8941               tree r;
8942
8943               /* The file and line for this declaration, to
8944                  assist in error message reporting.  Since we
8945                  called push_tinst_level above, we don't need to
8946                  restore these.  */
8947               input_location = DECL_SOURCE_LOCATION (t);
8948
8949               if (TREE_CODE (t) == TEMPLATE_DECL)
8950                 {
8951                   ++processing_template_decl;
8952                   push_deferring_access_checks (dk_no_check);
8953                 }
8954
8955               r = tsubst_friend_function (t, args);
8956               add_friend (type, r, /*complain=*/false);
8957               if (TREE_CODE (t) == TEMPLATE_DECL)
8958                 {
8959                   pop_deferring_access_checks ();
8960                   --processing_template_decl;
8961                 }
8962             }
8963         }
8964     }
8965
8966   if (CLASSTYPE_LAMBDA_EXPR (type))
8967     {
8968       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8969       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8970         {
8971           apply_lambda_return_type (lambda, void_type_node);
8972           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8973         }
8974       instantiate_decl (lambda_function (type), false, false);
8975       maybe_add_lambda_conv_op (type);
8976     }
8977
8978   /* Set the file and line number information to whatever is given for
8979      the class itself.  This puts error messages involving generated
8980      implicit functions at a predictable point, and the same point
8981      that would be used for non-template classes.  */
8982   input_location = DECL_SOURCE_LOCATION (typedecl);
8983
8984   unreverse_member_declarations (type);
8985   finish_struct_1 (type);
8986   TYPE_BEING_DEFINED (type) = 0;
8987
8988   /* We don't instantiate default arguments for member functions.  14.7.1:
8989
8990      The implicit instantiation of a class template specialization causes
8991      the implicit instantiation of the declarations, but not of the
8992      definitions or default arguments, of the class member functions,
8993      member classes, static data members and member templates....  */
8994
8995   /* Some typedefs referenced from within the template code need to be access
8996      checked at template instantiation time, i.e now. These types were
8997      added to the template at parsing time. Let's get those and perform
8998      the access checks then.  */
8999   perform_typedefs_access_check (pattern, args);
9000   perform_deferred_access_checks ();
9001   pop_nested_class ();
9002   maximum_field_alignment = saved_maximum_field_alignment;
9003   pop_from_top_level ();
9004   pop_deferring_access_checks ();
9005   pop_tinst_level ();
9006
9007   /* The vtable for a template class can be emitted in any translation
9008      unit in which the class is instantiated.  When there is no key
9009      method, however, finish_struct_1 will already have added TYPE to
9010      the keyed_classes list.  */
9011   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9012     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9013
9014   return type;
9015 }
9016
9017 /* Wrapper for instantiate_class_template_1.  */
9018
9019 tree
9020 instantiate_class_template (tree type)
9021 {
9022   tree ret;
9023   timevar_push (TV_TEMPLATE_INST);
9024   ret = instantiate_class_template_1 (type);
9025   timevar_pop (TV_TEMPLATE_INST);
9026   return ret;
9027 }
9028
9029 static tree
9030 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9031 {
9032   tree r;
9033
9034   if (!t)
9035     r = t;
9036   else if (TYPE_P (t))
9037     r = tsubst (t, args, complain, in_decl);
9038   else
9039     {
9040       if (!(complain & tf_warning))
9041         ++c_inhibit_evaluation_warnings;
9042       r = tsubst_expr (t, args, complain, in_decl,
9043                        /*integral_constant_expression_p=*/true);
9044       if (!(complain & tf_warning))
9045         --c_inhibit_evaluation_warnings;
9046       /* Preserve the raw-reference nature of T.  */
9047       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9048           && REFERENCE_REF_P (r))
9049         r = TREE_OPERAND (r, 0);
9050     }
9051   return r;
9052 }
9053
9054 /* Given a function parameter pack TMPL_PARM and some function parameters
9055    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9056    and set *SPEC_P to point at the next point in the list.  */
9057
9058 static tree
9059 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9060 {
9061   /* Collect all of the extra "packed" parameters into an
9062      argument pack.  */
9063   tree parmvec;
9064   tree parmtypevec;
9065   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9066   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9067   tree spec_parm = *spec_p;
9068   int i, len;
9069
9070   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9071     if (tmpl_parm
9072         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9073       break;
9074
9075   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9076   parmvec = make_tree_vec (len);
9077   parmtypevec = make_tree_vec (len);
9078   spec_parm = *spec_p;
9079   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9080     {
9081       TREE_VEC_ELT (parmvec, i) = spec_parm;
9082       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9083     }
9084
9085   /* Build the argument packs.  */
9086   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9087   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9088   TREE_TYPE (argpack) = argtypepack;
9089   *spec_p = spec_parm;
9090
9091   return argpack;
9092 }
9093
9094 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9095    NONTYPE_ARGUMENT_PACK.  */
9096
9097 static tree
9098 make_fnparm_pack (tree spec_parm)
9099 {
9100   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9101 }
9102
9103 /* Substitute ARGS into T, which is an pack expansion
9104    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9105    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9106    (if only a partial substitution could be performed) or
9107    ERROR_MARK_NODE if there was an error.  */
9108 tree
9109 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9110                        tree in_decl)
9111 {
9112   tree pattern;
9113   tree pack, packs = NULL_TREE;
9114   bool unsubstituted_packs = false;
9115   int i, len = -1;
9116   tree result;
9117   htab_t saved_local_specializations = NULL;
9118
9119   gcc_assert (PACK_EXPANSION_P (t));
9120   pattern = PACK_EXPANSION_PATTERN (t);
9121
9122   /* Determine the argument packs that will instantiate the parameter
9123      packs used in the expansion expression. While we're at it,
9124      compute the number of arguments to be expanded and make sure it
9125      is consistent.  */
9126   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9127        pack = TREE_CHAIN (pack))
9128     {
9129       tree parm_pack = TREE_VALUE (pack);
9130       tree arg_pack = NULL_TREE;
9131       tree orig_arg = NULL_TREE;
9132
9133       if (TREE_CODE (parm_pack) == BASES)
9134        {
9135          if (BASES_DIRECT (parm_pack))
9136            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9137                                                         args, complain, in_decl, false));
9138          else
9139            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9140                                                  args, complain, in_decl, false));
9141        }
9142       if (TREE_CODE (parm_pack) == PARM_DECL)
9143         {
9144           if (!cp_unevaluated_operand)
9145             arg_pack = retrieve_local_specialization (parm_pack);
9146           else
9147             {
9148               /* We can't rely on local_specializations for a parameter
9149                  name used later in a function declaration (such as in a
9150                  late-specified return type).  Even if it exists, it might
9151                  have the wrong value for a recursive call.  Just make a
9152                  dummy decl, since it's only used for its type.  */
9153               arg_pack = tsubst_decl (parm_pack, args, complain);
9154               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9155                 /* Partial instantiation of the parm_pack, we can't build
9156                    up an argument pack yet.  */
9157                 arg_pack = NULL_TREE;
9158               else
9159                 arg_pack = make_fnparm_pack (arg_pack);
9160             }
9161         }
9162       else
9163         {
9164           int level, idx, levels;
9165           template_parm_level_and_index (parm_pack, &level, &idx);
9166
9167           levels = TMPL_ARGS_DEPTH (args);
9168           if (level <= levels)
9169             arg_pack = TMPL_ARG (args, level, idx);
9170         }
9171
9172       orig_arg = arg_pack;
9173       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9174         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9175       
9176       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9177         /* This can only happen if we forget to expand an argument
9178            pack somewhere else. Just return an error, silently.  */
9179         {
9180           result = make_tree_vec (1);
9181           TREE_VEC_ELT (result, 0) = error_mark_node;
9182           return result;
9183         }
9184
9185       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9186         /* The argument pack that the parameter maps to is just an
9187            expansion of the parameter itself, such as one would find
9188            in the implicit typedef of a class inside the class itself.
9189            Consider this parameter "unsubstituted", so that we will
9190            maintain the outer pack expansion.  */
9191         arg_pack = NULL_TREE;
9192           
9193       if (arg_pack)
9194         {
9195           int my_len = 
9196             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9197
9198           /* Don't bother trying to do a partial substitution with
9199              incomplete packs; we'll try again after deduction.  */
9200           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9201             return t;
9202
9203           if (len < 0)
9204             len = my_len;
9205           else if (len != my_len)
9206             {
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         {
9225           /* We can't substitute for this parameter pack.  */
9226           unsubstituted_packs = true;
9227           break;
9228         }
9229     }
9230
9231   /* We cannot expand this expansion expression, because we don't have
9232      all of the argument packs we need. Substitute into the pattern
9233      and return a PACK_EXPANSION_*. The caller will need to deal with
9234      that.  */
9235   if (unsubstituted_packs)
9236     {
9237       tree new_pat;
9238       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9239         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9240                                /*integral_constant_expression_p=*/false);
9241       else
9242         new_pat = tsubst (pattern, args, complain, in_decl);
9243       return make_pack_expansion (new_pat);
9244     }
9245
9246   /* We could not find any argument packs that work.  */
9247   if (len < 0)
9248     return error_mark_node;
9249
9250   if (cp_unevaluated_operand)
9251     {
9252       /* We're in a late-specified return type, so create our own local
9253          specializations table; the current table is either NULL or (in the
9254          case of recursive unification) might have bindings that we don't
9255          want to use or alter.  */
9256       saved_local_specializations = local_specializations;
9257       local_specializations = htab_create (37,
9258                                            hash_local_specialization,
9259                                            eq_local_specializations,
9260                                            NULL);
9261     }
9262
9263   /* For each argument in each argument pack, substitute into the
9264      pattern.  */
9265   result = make_tree_vec (len);
9266   for (i = 0; i < len; ++i)
9267     {
9268       /* For parameter pack, change the substitution of the parameter
9269          pack to the ith argument in its argument pack, then expand
9270          the pattern.  */
9271       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9272         {
9273           tree parm = TREE_PURPOSE (pack);
9274           tree arg;
9275
9276           /* Select the Ith argument from the pack.  */
9277           if (TREE_CODE (parm) == PARM_DECL)
9278             {
9279               if (i == 0)
9280                 {
9281                   arg = make_node (ARGUMENT_PACK_SELECT);
9282                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9283                   mark_used (parm);
9284                   register_local_specialization (arg, parm);
9285                 }
9286               else
9287                 arg = retrieve_local_specialization (parm);
9288             }
9289           else
9290             {
9291               int idx, level;
9292               template_parm_level_and_index (parm, &level, &idx);
9293
9294               if (i == 0)
9295                 {
9296                   arg = make_node (ARGUMENT_PACK_SELECT);
9297                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9298                   /* Update the corresponding argument.  */
9299                   TMPL_ARG (args, level, idx) = arg;
9300                 }
9301               else
9302                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9303                 arg = TMPL_ARG (args, level, idx);
9304             }
9305           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9306         }
9307
9308       /* Substitute into the PATTERN with the altered arguments.  */
9309       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9310         TREE_VEC_ELT (result, i) = 
9311           tsubst_expr (pattern, args, complain, in_decl,
9312                        /*integral_constant_expression_p=*/false);
9313       else
9314         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9315
9316       if (TREE_VEC_ELT (result, i) == error_mark_node)
9317         {
9318           result = error_mark_node;
9319           break;
9320         }
9321     }
9322
9323   /* Update ARGS to restore the substitution from parameter packs to
9324      their argument packs.  */
9325   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9326     {
9327       tree parm = TREE_PURPOSE (pack);
9328
9329       if (TREE_CODE (parm) == PARM_DECL)
9330         register_local_specialization (TREE_TYPE (pack), parm);
9331       else
9332         {
9333           int idx, level;
9334           template_parm_level_and_index (parm, &level, &idx);
9335           
9336           /* Update the corresponding argument.  */
9337           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9338             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9339               TREE_TYPE (pack);
9340           else
9341             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9342         }
9343     }
9344
9345   if (saved_local_specializations)
9346     {
9347       htab_delete (local_specializations);
9348       local_specializations = saved_local_specializations;
9349     }
9350   
9351   return result;
9352 }
9353
9354 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9355    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9356    parameter packs; all parms generated from a function parameter pack will
9357    have the same DECL_PARM_INDEX.  */
9358
9359 tree
9360 get_pattern_parm (tree parm, tree tmpl)
9361 {
9362   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9363   tree patparm;
9364
9365   if (DECL_ARTIFICIAL (parm))
9366     {
9367       for (patparm = DECL_ARGUMENTS (pattern);
9368            patparm; patparm = DECL_CHAIN (patparm))
9369         if (DECL_ARTIFICIAL (patparm)
9370             && DECL_NAME (parm) == DECL_NAME (patparm))
9371           break;
9372     }
9373   else
9374     {
9375       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9376       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9377       gcc_assert (DECL_PARM_INDEX (patparm)
9378                   == DECL_PARM_INDEX (parm));
9379     }
9380
9381   return patparm;
9382 }
9383
9384 /* Substitute ARGS into the vector or list of template arguments T.  */
9385
9386 static tree
9387 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9388 {
9389   tree orig_t = t;
9390   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9391   tree *elts;
9392
9393   if (t == error_mark_node)
9394     return error_mark_node;
9395
9396   len = TREE_VEC_LENGTH (t);
9397   elts = XALLOCAVEC (tree, len);
9398
9399   for (i = 0; i < len; i++)
9400     {
9401       tree orig_arg = TREE_VEC_ELT (t, i);
9402       tree new_arg;
9403
9404       if (TREE_CODE (orig_arg) == TREE_VEC)
9405         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9406       else if (PACK_EXPANSION_P (orig_arg))
9407         {
9408           /* Substitute into an expansion expression.  */
9409           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9410
9411           if (TREE_CODE (new_arg) == TREE_VEC)
9412             /* Add to the expanded length adjustment the number of
9413                expanded arguments. We subtract one from this
9414                measurement, because the argument pack expression
9415                itself is already counted as 1 in
9416                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9417                the argument pack is empty.  */
9418             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9419         }
9420       else if (ARGUMENT_PACK_P (orig_arg))
9421         {
9422           /* Substitute into each of the arguments.  */
9423           new_arg = TYPE_P (orig_arg)
9424             ? cxx_make_type (TREE_CODE (orig_arg))
9425             : make_node (TREE_CODE (orig_arg));
9426           
9427           SET_ARGUMENT_PACK_ARGS (
9428             new_arg,
9429             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9430                                   args, complain, in_decl));
9431
9432           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9433             new_arg = error_mark_node;
9434
9435           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9436             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9437                                           complain, in_decl);
9438             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9439
9440             if (TREE_TYPE (new_arg) == error_mark_node)
9441               new_arg = error_mark_node;
9442           }
9443         }
9444       else
9445         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9446
9447       if (new_arg == error_mark_node)
9448         return error_mark_node;
9449
9450       elts[i] = new_arg;
9451       if (new_arg != orig_arg)
9452         need_new = 1;
9453     }
9454
9455   if (!need_new)
9456     return t;
9457
9458   /* Make space for the expanded arguments coming from template
9459      argument packs.  */
9460   t = make_tree_vec (len + expanded_len_adjust);
9461   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9462      arguments for a member template.
9463      In that case each TREE_VEC in ORIG_T represents a level of template
9464      arguments, and ORIG_T won't carry any non defaulted argument count.
9465      It will rather be the nested TREE_VECs that will carry one.
9466      In other words, ORIG_T carries a non defaulted argument count only
9467      if it doesn't contain any nested TREE_VEC.  */
9468   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9469     {
9470       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9471       count += expanded_len_adjust;
9472       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9473     }
9474   for (i = 0, out = 0; i < len; i++)
9475     {
9476       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9477            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9478           && TREE_CODE (elts[i]) == TREE_VEC)
9479         {
9480           int idx;
9481
9482           /* Now expand the template argument pack "in place".  */
9483           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9484             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9485         }
9486       else
9487         {
9488           TREE_VEC_ELT (t, out) = elts[i];
9489           out++;
9490         }
9491     }
9492
9493   return t;
9494 }
9495
9496 /* Return the result of substituting ARGS into the template parameters
9497    given by PARMS.  If there are m levels of ARGS and m + n levels of
9498    PARMS, then the result will contain n levels of PARMS.  For
9499    example, if PARMS is `template <class T> template <class U>
9500    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9501    result will be `template <int*, double, class V>'.  */
9502
9503 static tree
9504 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9505 {
9506   tree r = NULL_TREE;
9507   tree* new_parms;
9508
9509   /* When substituting into a template, we must set
9510      PROCESSING_TEMPLATE_DECL as the template parameters may be
9511      dependent if they are based on one-another, and the dependency
9512      predicates are short-circuit outside of templates.  */
9513   ++processing_template_decl;
9514
9515   for (new_parms = &r;
9516        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9517        new_parms = &(TREE_CHAIN (*new_parms)),
9518          parms = TREE_CHAIN (parms))
9519     {
9520       tree new_vec =
9521         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9522       int i;
9523
9524       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9525         {
9526           tree tuple;
9527
9528           if (parms == error_mark_node)
9529             continue;
9530
9531           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9532
9533           if (tuple == error_mark_node)
9534             continue;
9535
9536           TREE_VEC_ELT (new_vec, i) =
9537             tsubst_template_parm (tuple, args, complain);
9538         }
9539
9540       *new_parms =
9541         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9542                              - TMPL_ARGS_DEPTH (args)),
9543                    new_vec, NULL_TREE);
9544     }
9545
9546   --processing_template_decl;
9547
9548   return r;
9549 }
9550
9551 /* Return the result of substituting ARGS into one template parameter
9552    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9553    parameter and which TREE_PURPOSE is the default argument of the
9554    template parameter.  */
9555
9556 static tree
9557 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9558 {
9559   tree default_value, parm_decl;
9560
9561   if (args == NULL_TREE
9562       || t == NULL_TREE
9563       || t == error_mark_node)
9564     return t;
9565
9566   gcc_assert (TREE_CODE (t) == TREE_LIST);
9567
9568   default_value = TREE_PURPOSE (t);
9569   parm_decl = TREE_VALUE (t);
9570
9571   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9572   if (TREE_CODE (parm_decl) == PARM_DECL
9573       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9574     parm_decl = error_mark_node;
9575   default_value = tsubst_template_arg (default_value, args,
9576                                        complain, NULL_TREE);
9577
9578   return build_tree_list (default_value, parm_decl);
9579 }
9580
9581 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9582    type T.  If T is not an aggregate or enumeration type, it is
9583    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9584    ENTERING_SCOPE is nonzero, T is the context for a template which
9585    we are presently tsubst'ing.  Return the substituted value.  */
9586
9587 static tree
9588 tsubst_aggr_type (tree t,
9589                   tree args,
9590                   tsubst_flags_t complain,
9591                   tree in_decl,
9592                   int entering_scope)
9593 {
9594   if (t == NULL_TREE)
9595     return NULL_TREE;
9596
9597   switch (TREE_CODE (t))
9598     {
9599     case RECORD_TYPE:
9600       if (TYPE_PTRMEMFUNC_P (t))
9601         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9602
9603       /* Else fall through.  */
9604     case ENUMERAL_TYPE:
9605     case UNION_TYPE:
9606       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9607         {
9608           tree argvec;
9609           tree context;
9610           tree r;
9611           int saved_unevaluated_operand;
9612           int saved_inhibit_evaluation_warnings;
9613
9614           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9615           saved_unevaluated_operand = cp_unevaluated_operand;
9616           cp_unevaluated_operand = 0;
9617           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9618           c_inhibit_evaluation_warnings = 0;
9619
9620           /* First, determine the context for the type we are looking
9621              up.  */
9622           context = TYPE_CONTEXT (t);
9623           if (context && TYPE_P (context))
9624             {
9625               context = tsubst_aggr_type (context, args, complain,
9626                                           in_decl, /*entering_scope=*/1);
9627               /* If context is a nested class inside a class template,
9628                  it may still need to be instantiated (c++/33959).  */
9629               context = complete_type (context);
9630             }
9631
9632           /* Then, figure out what arguments are appropriate for the
9633              type we are trying to find.  For example, given:
9634
9635                template <class T> struct S;
9636                template <class T, class U> void f(T, U) { S<U> su; }
9637
9638              and supposing that we are instantiating f<int, double>,
9639              then our ARGS will be {int, double}, but, when looking up
9640              S we only want {double}.  */
9641           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9642                                          complain, in_decl);
9643           if (argvec == error_mark_node)
9644             r = error_mark_node;
9645           else
9646             {
9647               r = lookup_template_class (t, argvec, in_decl, context,
9648                                          entering_scope, complain);
9649               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9650             }
9651
9652           cp_unevaluated_operand = saved_unevaluated_operand;
9653           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9654
9655           return r;
9656         }
9657       else
9658         /* This is not a template type, so there's nothing to do.  */
9659         return t;
9660
9661     default:
9662       return tsubst (t, args, complain, in_decl);
9663     }
9664 }
9665
9666 /* Substitute into the default argument ARG (a default argument for
9667    FN), which has the indicated TYPE.  */
9668
9669 tree
9670 tsubst_default_argument (tree fn, tree type, tree arg)
9671 {
9672   tree saved_class_ptr = NULL_TREE;
9673   tree saved_class_ref = NULL_TREE;
9674
9675   /* This can happen in invalid code.  */
9676   if (TREE_CODE (arg) == DEFAULT_ARG)
9677     return arg;
9678
9679   /* This default argument came from a template.  Instantiate the
9680      default argument here, not in tsubst.  In the case of
9681      something like:
9682
9683        template <class T>
9684        struct S {
9685          static T t();
9686          void f(T = t());
9687        };
9688
9689      we must be careful to do name lookup in the scope of S<T>,
9690      rather than in the current class.  */
9691   push_access_scope (fn);
9692   /* The "this" pointer is not valid in a default argument.  */
9693   if (cfun)
9694     {
9695       saved_class_ptr = current_class_ptr;
9696       cp_function_chain->x_current_class_ptr = NULL_TREE;
9697       saved_class_ref = current_class_ref;
9698       cp_function_chain->x_current_class_ref = NULL_TREE;
9699     }
9700
9701   push_deferring_access_checks(dk_no_deferred);
9702   /* The default argument expression may cause implicitly defined
9703      member functions to be synthesized, which will result in garbage
9704      collection.  We must treat this situation as if we were within
9705      the body of function so as to avoid collecting live data on the
9706      stack.  */
9707   ++function_depth;
9708   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9709                      tf_warning_or_error, NULL_TREE,
9710                      /*integral_constant_expression_p=*/false);
9711   --function_depth;
9712   pop_deferring_access_checks();
9713
9714   /* Restore the "this" pointer.  */
9715   if (cfun)
9716     {
9717       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9718       cp_function_chain->x_current_class_ref = saved_class_ref;
9719     }
9720
9721   /* Make sure the default argument is reasonable.  */
9722   arg = check_default_argument (type, arg);
9723
9724   pop_access_scope (fn);
9725
9726   return arg;
9727 }
9728
9729 /* Substitute into all the default arguments for FN.  */
9730
9731 static void
9732 tsubst_default_arguments (tree fn)
9733 {
9734   tree arg;
9735   tree tmpl_args;
9736
9737   tmpl_args = DECL_TI_ARGS (fn);
9738
9739   /* If this function is not yet instantiated, we certainly don't need
9740      its default arguments.  */
9741   if (uses_template_parms (tmpl_args))
9742     return;
9743   /* Don't do this again for clones.  */
9744   if (DECL_CLONED_FUNCTION_P (fn))
9745     return;
9746
9747   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9748        arg;
9749        arg = TREE_CHAIN (arg))
9750     if (TREE_PURPOSE (arg))
9751       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9752                                                     TREE_VALUE (arg),
9753                                                     TREE_PURPOSE (arg));
9754 }
9755
9756 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9757    result of the substitution.  Issue error and warning messages under
9758    control of COMPLAIN.  */
9759
9760 static tree
9761 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9762 {
9763 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9764   location_t saved_loc;
9765   tree r = NULL_TREE;
9766   tree in_decl = t;
9767   hashval_t hash = 0;
9768
9769   /* Set the filename and linenumber to improve error-reporting.  */
9770   saved_loc = input_location;
9771   input_location = DECL_SOURCE_LOCATION (t);
9772
9773   switch (TREE_CODE (t))
9774     {
9775     case TEMPLATE_DECL:
9776       {
9777         /* We can get here when processing a member function template,
9778            member class template, or template template parameter.  */
9779         tree decl = DECL_TEMPLATE_RESULT (t);
9780         tree spec;
9781         tree tmpl_args;
9782         tree full_args;
9783
9784         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9785           {
9786             /* Template template parameter is treated here.  */
9787             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9788             if (new_type == error_mark_node)
9789               RETURN (error_mark_node);
9790
9791             r = copy_decl (t);
9792             DECL_CHAIN (r) = NULL_TREE;
9793             TREE_TYPE (r) = new_type;
9794             DECL_TEMPLATE_RESULT (r)
9795               = build_decl (DECL_SOURCE_LOCATION (decl),
9796                             TYPE_DECL, DECL_NAME (decl), new_type);
9797             DECL_TEMPLATE_PARMS (r)
9798               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9799                                        complain);
9800             TYPE_NAME (new_type) = r;
9801             break;
9802           }
9803
9804         /* We might already have an instance of this template.
9805            The ARGS are for the surrounding class type, so the
9806            full args contain the tsubst'd args for the context,
9807            plus the innermost args from the template decl.  */
9808         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9809           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9810           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9811         /* Because this is a template, the arguments will still be
9812            dependent, even after substitution.  If
9813            PROCESSING_TEMPLATE_DECL is not set, the dependency
9814            predicates will short-circuit.  */
9815         ++processing_template_decl;
9816         full_args = tsubst_template_args (tmpl_args, args,
9817                                           complain, in_decl);
9818         --processing_template_decl;
9819         if (full_args == error_mark_node)
9820           RETURN (error_mark_node);
9821
9822         /* If this is a default template template argument,
9823            tsubst might not have changed anything.  */
9824         if (full_args == tmpl_args)
9825           RETURN (t);
9826
9827         hash = hash_tmpl_and_args (t, full_args);
9828         spec = retrieve_specialization (t, full_args, hash);
9829         if (spec != NULL_TREE)
9830           {
9831             r = spec;
9832             break;
9833           }
9834
9835         /* Make a new template decl.  It will be similar to the
9836            original, but will record the current template arguments.
9837            We also create a new function declaration, which is just
9838            like the old one, but points to this new template, rather
9839            than the old one.  */
9840         r = copy_decl (t);
9841         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9842         DECL_CHAIN (r) = NULL_TREE;
9843
9844         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9845
9846         if (TREE_CODE (decl) == TYPE_DECL)
9847           {
9848             tree new_type;
9849             ++processing_template_decl;
9850             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9851             --processing_template_decl;
9852             if (new_type == error_mark_node)
9853               RETURN (error_mark_node);
9854
9855             TREE_TYPE (r) = new_type;
9856             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9857             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9858             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9859             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9860           }
9861         else
9862           {
9863             tree new_decl;
9864             ++processing_template_decl;
9865             new_decl = tsubst (decl, args, complain, in_decl);
9866             --processing_template_decl;
9867             if (new_decl == error_mark_node)
9868               RETURN (error_mark_node);
9869
9870             DECL_TEMPLATE_RESULT (r) = new_decl;
9871             DECL_TI_TEMPLATE (new_decl) = r;
9872             TREE_TYPE (r) = TREE_TYPE (new_decl);
9873             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9874             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9875           }
9876
9877         SET_DECL_IMPLICIT_INSTANTIATION (r);
9878         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9879         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9880
9881         /* The template parameters for this new template are all the
9882            template parameters for the old template, except the
9883            outermost level of parameters.  */
9884         DECL_TEMPLATE_PARMS (r)
9885           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9886                                    complain);
9887
9888         if (PRIMARY_TEMPLATE_P (t))
9889           DECL_PRIMARY_TEMPLATE (r) = r;
9890
9891         if (TREE_CODE (decl) != TYPE_DECL)
9892           /* Record this non-type partial instantiation.  */
9893           register_specialization (r, t,
9894                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9895                                    false, hash);
9896       }
9897       break;
9898
9899     case FUNCTION_DECL:
9900       {
9901         tree ctx;
9902         tree argvec = NULL_TREE;
9903         tree *friends;
9904         tree gen_tmpl;
9905         tree type;
9906         int member;
9907         int args_depth;
9908         int parms_depth;
9909
9910         /* Nobody should be tsubst'ing into non-template functions.  */
9911         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9912
9913         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9914           {
9915             tree spec;
9916             bool dependent_p;
9917
9918             /* If T is not dependent, just return it.  We have to
9919                increment PROCESSING_TEMPLATE_DECL because
9920                value_dependent_expression_p assumes that nothing is
9921                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9922             ++processing_template_decl;
9923             dependent_p = value_dependent_expression_p (t);
9924             --processing_template_decl;
9925             if (!dependent_p)
9926               RETURN (t);
9927
9928             /* Calculate the most general template of which R is a
9929                specialization, and the complete set of arguments used to
9930                specialize R.  */
9931             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9932             argvec = tsubst_template_args (DECL_TI_ARGS
9933                                           (DECL_TEMPLATE_RESULT
9934                                                  (DECL_TI_TEMPLATE (t))),
9935                                            args, complain, in_decl);
9936             if (argvec == error_mark_node)
9937               RETURN (error_mark_node);
9938
9939             /* Check to see if we already have this specialization.  */
9940             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9941             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9942
9943             if (spec)
9944               {
9945                 r = spec;
9946                 break;
9947               }
9948
9949             /* We can see more levels of arguments than parameters if
9950                there was a specialization of a member template, like
9951                this:
9952
9953                  template <class T> struct S { template <class U> void f(); }
9954                  template <> template <class U> void S<int>::f(U);
9955
9956                Here, we'll be substituting into the specialization,
9957                because that's where we can find the code we actually
9958                want to generate, but we'll have enough arguments for
9959                the most general template.
9960
9961                We also deal with the peculiar case:
9962
9963                  template <class T> struct S {
9964                    template <class U> friend void f();
9965                  };
9966                  template <class U> void f() {}
9967                  template S<int>;
9968                  template void f<double>();
9969
9970                Here, the ARGS for the instantiation of will be {int,
9971                double}.  But, we only need as many ARGS as there are
9972                levels of template parameters in CODE_PATTERN.  We are
9973                careful not to get fooled into reducing the ARGS in
9974                situations like:
9975
9976                  template <class T> struct S { template <class U> void f(U); }
9977                  template <class T> template <> void S<T>::f(int) {}
9978
9979                which we can spot because the pattern will be a
9980                specialization in this case.  */
9981             args_depth = TMPL_ARGS_DEPTH (args);
9982             parms_depth =
9983               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9984             if (args_depth > parms_depth
9985                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9986               args = get_innermost_template_args (args, parms_depth);
9987           }
9988         else
9989           {
9990             /* This special case arises when we have something like this:
9991
9992                  template <class T> struct S {
9993                    friend void f<int>(int, double);
9994                  };
9995
9996                Here, the DECL_TI_TEMPLATE for the friend declaration
9997                will be an IDENTIFIER_NODE.  We are being called from
9998                tsubst_friend_function, and we want only to create a
9999                new decl (R) with appropriate types so that we can call
10000                determine_specialization.  */
10001             gen_tmpl = NULL_TREE;
10002           }
10003
10004         if (DECL_CLASS_SCOPE_P (t))
10005           {
10006             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10007               member = 2;
10008             else
10009               member = 1;
10010             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10011                                     complain, t, /*entering_scope=*/1);
10012           }
10013         else
10014           {
10015             member = 0;
10016             ctx = DECL_CONTEXT (t);
10017           }
10018         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10019         if (type == error_mark_node)
10020           RETURN (error_mark_node);
10021
10022         /* We do NOT check for matching decls pushed separately at this
10023            point, as they may not represent instantiations of this
10024            template, and in any case are considered separate under the
10025            discrete model.  */
10026         r = copy_decl (t);
10027         DECL_USE_TEMPLATE (r) = 0;
10028         TREE_TYPE (r) = type;
10029         /* Clear out the mangled name and RTL for the instantiation.  */
10030         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10031         SET_DECL_RTL (r, NULL);
10032         /* Leave DECL_INITIAL set on deleted instantiations.  */
10033         if (!DECL_DELETED_FN (r))
10034           DECL_INITIAL (r) = NULL_TREE;
10035         DECL_CONTEXT (r) = ctx;
10036
10037         if (member && DECL_CONV_FN_P (r))
10038           /* Type-conversion operator.  Reconstruct the name, in
10039              case it's the name of one of the template's parameters.  */
10040           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10041
10042         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10043                                      complain, t);
10044         DECL_RESULT (r) = NULL_TREE;
10045
10046         TREE_STATIC (r) = 0;
10047         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10048         DECL_EXTERNAL (r) = 1;
10049         /* If this is an instantiation of a function with internal
10050            linkage, we already know what object file linkage will be
10051            assigned to the instantiation.  */
10052         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10053         DECL_DEFER_OUTPUT (r) = 0;
10054         DECL_CHAIN (r) = NULL_TREE;
10055         DECL_PENDING_INLINE_INFO (r) = 0;
10056         DECL_PENDING_INLINE_P (r) = 0;
10057         DECL_SAVED_TREE (r) = NULL_TREE;
10058         DECL_STRUCT_FUNCTION (r) = NULL;
10059         TREE_USED (r) = 0;
10060         /* We'll re-clone as appropriate in instantiate_template.  */
10061         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10062
10063         /* If we aren't complaining now, return on error before we register
10064            the specialization so that we'll complain eventually.  */
10065         if ((complain & tf_error) == 0
10066             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10067             && !grok_op_properties (r, /*complain=*/false))
10068           RETURN (error_mark_node);
10069
10070         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10071            this in the special friend case mentioned above where
10072            GEN_TMPL is NULL.  */
10073         if (gen_tmpl)
10074           {
10075             DECL_TEMPLATE_INFO (r)
10076               = build_template_info (gen_tmpl, argvec);
10077             SET_DECL_IMPLICIT_INSTANTIATION (r);
10078             register_specialization (r, gen_tmpl, argvec, false, hash);
10079
10080             /* We're not supposed to instantiate default arguments
10081                until they are called, for a template.  But, for a
10082                declaration like:
10083
10084                  template <class T> void f ()
10085                  { extern void g(int i = T()); }
10086
10087                we should do the substitution when the template is
10088                instantiated.  We handle the member function case in
10089                instantiate_class_template since the default arguments
10090                might refer to other members of the class.  */
10091             if (!member
10092                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10093                 && !uses_template_parms (argvec))
10094               tsubst_default_arguments (r);
10095           }
10096         else
10097           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10098
10099         /* Copy the list of befriending classes.  */
10100         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10101              *friends;
10102              friends = &TREE_CHAIN (*friends))
10103           {
10104             *friends = copy_node (*friends);
10105             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10106                                             args, complain,
10107                                             in_decl);
10108           }
10109
10110         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10111           {
10112             maybe_retrofit_in_chrg (r);
10113             if (DECL_CONSTRUCTOR_P (r))
10114               grok_ctor_properties (ctx, r);
10115             /* If this is an instantiation of a member template, clone it.
10116                If it isn't, that'll be handled by
10117                clone_constructors_and_destructors.  */
10118             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10119               clone_function_decl (r, /*update_method_vec_p=*/0);
10120           }
10121         else if ((complain & tf_error) != 0
10122                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10123                  && !grok_op_properties (r, /*complain=*/true))
10124           RETURN (error_mark_node);
10125
10126         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10127           SET_DECL_FRIEND_CONTEXT (r,
10128                                    tsubst (DECL_FRIEND_CONTEXT (t),
10129                                             args, complain, in_decl));
10130
10131         /* Possibly limit visibility based on template args.  */
10132         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10133         if (DECL_VISIBILITY_SPECIFIED (t))
10134           {
10135             DECL_VISIBILITY_SPECIFIED (r) = 0;
10136             DECL_ATTRIBUTES (r)
10137               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10138           }
10139         determine_visibility (r);
10140         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10141             && !processing_template_decl)
10142           defaulted_late_check (r);
10143
10144         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10145                                         args, complain, in_decl);
10146       }
10147       break;
10148
10149     case PARM_DECL:
10150       {
10151         tree type = NULL_TREE;
10152         int i, len = 1;
10153         tree expanded_types = NULL_TREE;
10154         tree prev_r = NULL_TREE;
10155         tree first_r = NULL_TREE;
10156
10157         if (FUNCTION_PARAMETER_PACK_P (t))
10158           {
10159             /* If there is a local specialization that isn't a
10160                parameter pack, it means that we're doing a "simple"
10161                substitution from inside tsubst_pack_expansion. Just
10162                return the local specialization (which will be a single
10163                parm).  */
10164             tree spec = retrieve_local_specialization (t);
10165             if (spec 
10166                 && TREE_CODE (spec) == PARM_DECL
10167                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10168               RETURN (spec);
10169
10170             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10171                the parameters in this function parameter pack.  */
10172             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10173                                                     complain, in_decl);
10174             if (TREE_CODE (expanded_types) == TREE_VEC)
10175               {
10176                 len = TREE_VEC_LENGTH (expanded_types);
10177
10178                 /* Zero-length parameter packs are boring. Just substitute
10179                    into the chain.  */
10180                 if (len == 0)
10181                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10182                                   TREE_CHAIN (t)));
10183               }
10184             else
10185               {
10186                 /* All we did was update the type. Make a note of that.  */
10187                 type = expanded_types;
10188                 expanded_types = NULL_TREE;
10189               }
10190           }
10191
10192         /* Loop through all of the parameter's we'll build. When T is
10193            a function parameter pack, LEN is the number of expanded
10194            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10195         r = NULL_TREE;
10196         for (i = 0; i < len; ++i)
10197           {
10198             prev_r = r;
10199             r = copy_node (t);
10200             if (DECL_TEMPLATE_PARM_P (t))
10201               SET_DECL_TEMPLATE_PARM_P (r);
10202
10203             if (expanded_types)
10204               /* We're on the Ith parameter of the function parameter
10205                  pack.  */
10206               {
10207                 /* An argument of a function parameter pack is not a parameter
10208                    pack.  */
10209                 FUNCTION_PARAMETER_PACK_P (r) = false;
10210
10211                 /* Get the Ith type.  */
10212                 type = TREE_VEC_ELT (expanded_types, i);
10213
10214                 if (DECL_NAME (r))
10215                   /* Rename the parameter to include the index.  */
10216                   DECL_NAME (r) =
10217                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10218               }
10219             else if (!type)
10220               /* We're dealing with a normal parameter.  */
10221               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10222
10223             type = type_decays_to (type);
10224             TREE_TYPE (r) = type;
10225             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10226
10227             if (DECL_INITIAL (r))
10228               {
10229                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10230                   DECL_INITIAL (r) = TREE_TYPE (r);
10231                 else
10232                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10233                                              complain, in_decl);
10234               }
10235
10236             DECL_CONTEXT (r) = NULL_TREE;
10237
10238             if (!DECL_TEMPLATE_PARM_P (r))
10239               DECL_ARG_TYPE (r) = type_passed_as (type);
10240
10241             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10242                                             args, complain, in_decl);
10243
10244             /* Keep track of the first new parameter we
10245                generate. That's what will be returned to the
10246                caller.  */
10247             if (!first_r)
10248               first_r = r;
10249
10250             /* Build a proper chain of parameters when substituting
10251                into a function parameter pack.  */
10252             if (prev_r)
10253               DECL_CHAIN (prev_r) = r;
10254           }
10255
10256         if (DECL_CHAIN (t))
10257           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10258                                    complain, DECL_CHAIN (t));
10259
10260         /* FIRST_R contains the start of the chain we've built.  */
10261         r = first_r;
10262       }
10263       break;
10264
10265     case FIELD_DECL:
10266       {
10267         tree type;
10268
10269         r = copy_decl (t);
10270         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10271         if (type == error_mark_node)
10272           RETURN (error_mark_node);
10273         TREE_TYPE (r) = type;
10274         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10275
10276         if (DECL_C_BIT_FIELD (r))
10277           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10278              non-bit-fields DECL_INITIAL is a non-static data member
10279              initializer, which gets deferred instantiation.  */
10280           DECL_INITIAL (r)
10281             = tsubst_expr (DECL_INITIAL (t), args,
10282                            complain, in_decl,
10283                            /*integral_constant_expression_p=*/true);
10284         else if (DECL_INITIAL (t))
10285           {
10286             /* Set up DECL_TEMPLATE_INFO so that we can get at the
10287                NSDMI in perform_member_init.  Still set DECL_INITIAL
10288                so that we know there is one.  */
10289             DECL_INITIAL (r) = void_zero_node;
10290             gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10291             retrofit_lang_decl (r);
10292             DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10293           }
10294         /* We don't have to set DECL_CONTEXT here; it is set by
10295            finish_member_declaration.  */
10296         DECL_CHAIN (r) = NULL_TREE;
10297         if (VOID_TYPE_P (type))
10298           error ("instantiation of %q+D as type %qT", r, type);
10299
10300         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10301                                         args, complain, in_decl);
10302       }
10303       break;
10304
10305     case USING_DECL:
10306       /* We reach here only for member using decls.  */
10307       if (DECL_DEPENDENT_P (t))
10308         {
10309           r = do_class_using_decl
10310             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10311              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10312           if (!r)
10313             r = error_mark_node;
10314           else
10315             {
10316               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10317               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10318             }
10319         }
10320       else
10321         {
10322           r = copy_node (t);
10323           DECL_CHAIN (r) = NULL_TREE;
10324         }
10325       break;
10326
10327     case TYPE_DECL:
10328     case VAR_DECL:
10329       {
10330         tree argvec = NULL_TREE;
10331         tree gen_tmpl = NULL_TREE;
10332         tree spec;
10333         tree tmpl = NULL_TREE;
10334         tree ctx;
10335         tree type = NULL_TREE;
10336         bool local_p;
10337
10338         if (TREE_CODE (t) == TYPE_DECL
10339             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10340           {
10341             /* If this is the canonical decl, we don't have to
10342                mess with instantiations, and often we can't (for
10343                typename, template type parms and such).  Note that
10344                TYPE_NAME is not correct for the above test if
10345                we've copied the type for a typedef.  */
10346             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10347             if (type == error_mark_node)
10348               RETURN (error_mark_node);
10349             r = TYPE_NAME (type);
10350             break;
10351           }
10352
10353         /* Check to see if we already have the specialization we
10354            need.  */
10355         spec = NULL_TREE;
10356         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10357           {
10358             /* T is a static data member or namespace-scope entity.
10359                We have to substitute into namespace-scope variables
10360                (even though such entities are never templates) because
10361                of cases like:
10362                
10363                  template <class T> void f() { extern T t; }
10364
10365                where the entity referenced is not known until
10366                instantiation time.  */
10367             local_p = false;
10368             ctx = DECL_CONTEXT (t);
10369             if (DECL_CLASS_SCOPE_P (t))
10370               {
10371                 ctx = tsubst_aggr_type (ctx, args,
10372                                         complain,
10373                                         in_decl, /*entering_scope=*/1);
10374                 /* If CTX is unchanged, then T is in fact the
10375                    specialization we want.  That situation occurs when
10376                    referencing a static data member within in its own
10377                    class.  We can use pointer equality, rather than
10378                    same_type_p, because DECL_CONTEXT is always
10379                    canonical.  */
10380                 if (ctx == DECL_CONTEXT (t))
10381                   spec = t;
10382               }
10383
10384             if (!spec)
10385               {
10386                 tmpl = DECL_TI_TEMPLATE (t);
10387                 gen_tmpl = most_general_template (tmpl);
10388                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10389                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10390                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10391               }
10392           }
10393         else
10394           {
10395             /* A local variable.  */
10396             local_p = true;
10397             /* Subsequent calls to pushdecl will fill this in.  */
10398             ctx = NULL_TREE;
10399             spec = retrieve_local_specialization (t);
10400           }
10401         /* If we already have the specialization we need, there is
10402            nothing more to do.  */ 
10403         if (spec)
10404           {
10405             r = spec;
10406             break;
10407           }
10408
10409         /* Create a new node for the specialization we need.  */
10410         r = copy_decl (t);
10411         if (type == NULL_TREE)
10412           {
10413             if (is_typedef_decl (t))
10414               type = DECL_ORIGINAL_TYPE (t);
10415             else
10416               type = TREE_TYPE (t);
10417             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10418               type = strip_array_domain (type);
10419             type = tsubst (type, args, complain, in_decl);
10420           }
10421         if (TREE_CODE (r) == VAR_DECL)
10422           {
10423             /* Even if the original location is out of scope, the
10424                newly substituted one is not.  */
10425             DECL_DEAD_FOR_LOCAL (r) = 0;
10426             DECL_INITIALIZED_P (r) = 0;
10427             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10428             if (type == error_mark_node)
10429               RETURN (error_mark_node);
10430             if (TREE_CODE (type) == FUNCTION_TYPE)
10431               {
10432                 /* It may seem that this case cannot occur, since:
10433
10434                      typedef void f();
10435                      void g() { f x; }
10436
10437                    declares a function, not a variable.  However:
10438       
10439                      typedef void f();
10440                      template <typename T> void g() { T t; }
10441                      template void g<f>();
10442
10443                    is an attempt to declare a variable with function
10444                    type.  */
10445                 error ("variable %qD has function type",
10446                        /* R is not yet sufficiently initialized, so we
10447                           just use its name.  */
10448                        DECL_NAME (r));
10449                 RETURN (error_mark_node);
10450               }
10451             type = complete_type (type);
10452             /* Wait until cp_finish_decl to set this again, to handle
10453                circular dependency (template/instantiate6.C). */
10454             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10455             type = check_var_type (DECL_NAME (r), type);
10456
10457             if (DECL_HAS_VALUE_EXPR_P (t))
10458               {
10459                 tree ve = DECL_VALUE_EXPR (t);
10460                 ve = tsubst_expr (ve, args, complain, in_decl,
10461                                   /*constant_expression_p=*/false);
10462                 if (REFERENCE_REF_P (ve))
10463                   {
10464                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10465                     ve = TREE_OPERAND (ve, 0);
10466                   }
10467                 SET_DECL_VALUE_EXPR (r, ve);
10468               }
10469           }
10470         else if (DECL_SELF_REFERENCE_P (t))
10471           SET_DECL_SELF_REFERENCE_P (r);
10472         TREE_TYPE (r) = type;
10473         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10474         DECL_CONTEXT (r) = ctx;
10475         /* Clear out the mangled name and RTL for the instantiation.  */
10476         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10477         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10478           SET_DECL_RTL (r, NULL);
10479         /* The initializer must not be expanded until it is required;
10480            see [temp.inst].  */
10481         DECL_INITIAL (r) = NULL_TREE;
10482         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10483           SET_DECL_RTL (r, NULL);
10484         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10485         if (TREE_CODE (r) == VAR_DECL)
10486           {
10487             /* Possibly limit visibility based on template args.  */
10488             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10489             if (DECL_VISIBILITY_SPECIFIED (t))
10490               {
10491                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10492                 DECL_ATTRIBUTES (r)
10493                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10494               }
10495             determine_visibility (r);
10496           }
10497
10498         if (!local_p)
10499           {
10500             /* A static data member declaration is always marked
10501                external when it is declared in-class, even if an
10502                initializer is present.  We mimic the non-template
10503                processing here.  */
10504             DECL_EXTERNAL (r) = 1;
10505
10506             register_specialization (r, gen_tmpl, argvec, false, hash);
10507             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10508             SET_DECL_IMPLICIT_INSTANTIATION (r);
10509           }
10510         else if (cp_unevaluated_operand)
10511           {
10512             /* We're substituting this var in a decltype outside of its
10513                scope, such as for a lambda return type.  Don't add it to
10514                local_specializations, do perform auto deduction.  */
10515             tree auto_node = type_uses_auto (type);
10516             if (auto_node)
10517               {
10518                 tree init
10519                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10520                                  /*constant_expression_p=*/false);
10521                 init = resolve_nondeduced_context (init);
10522                 TREE_TYPE (r) = type
10523                   = do_auto_deduction (type, init, auto_node);
10524               }
10525           }
10526         else
10527           register_local_specialization (r, t);
10528
10529         DECL_CHAIN (r) = NULL_TREE;
10530
10531         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10532                                         /*flags=*/0,
10533                                         args, complain, in_decl);
10534
10535         /* Preserve a typedef that names a type.  */
10536         if (is_typedef_decl (r))
10537           {
10538             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10539             set_underlying_type (r);
10540           }
10541
10542         layout_decl (r, 0);
10543       }
10544       break;
10545
10546     default:
10547       gcc_unreachable ();
10548     }
10549 #undef RETURN
10550
10551  out:
10552   /* Restore the file and line information.  */
10553   input_location = saved_loc;
10554
10555   return r;
10556 }
10557
10558 /* Substitute into the ARG_TYPES of a function type.  */
10559
10560 static tree
10561 tsubst_arg_types (tree arg_types,
10562                   tree args,
10563                   tsubst_flags_t complain,
10564                   tree in_decl)
10565 {
10566   tree remaining_arg_types;
10567   tree type = NULL_TREE;
10568   int i = 1;
10569   tree expanded_args = NULL_TREE;
10570   tree default_arg;
10571
10572   if (!arg_types || arg_types == void_list_node)
10573     return arg_types;
10574
10575   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10576                                           args, complain, in_decl);
10577   if (remaining_arg_types == error_mark_node)
10578     return error_mark_node;
10579
10580   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10581     {
10582       /* For a pack expansion, perform substitution on the
10583          entire expression. Later on, we'll handle the arguments
10584          one-by-one.  */
10585       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10586                                             args, complain, in_decl);
10587
10588       if (TREE_CODE (expanded_args) == TREE_VEC)
10589         /* So that we'll spin through the parameters, one by one.  */
10590         i = TREE_VEC_LENGTH (expanded_args);
10591       else
10592         {
10593           /* We only partially substituted into the parameter
10594              pack. Our type is TYPE_PACK_EXPANSION.  */
10595           type = expanded_args;
10596           expanded_args = NULL_TREE;
10597         }
10598     }
10599
10600   while (i > 0) {
10601     --i;
10602     
10603     if (expanded_args)
10604       type = TREE_VEC_ELT (expanded_args, i);
10605     else if (!type)
10606       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10607
10608     if (type == error_mark_node)
10609       return error_mark_node;
10610     if (VOID_TYPE_P (type))
10611       {
10612         if (complain & tf_error)
10613           {
10614             error ("invalid parameter type %qT", type);
10615             if (in_decl)
10616               error ("in declaration %q+D", in_decl);
10617           }
10618         return error_mark_node;
10619     }
10620     
10621     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10622        top-level qualifiers as required.  */
10623     type = cv_unqualified (type_decays_to (type));
10624
10625     /* We do not substitute into default arguments here.  The standard
10626        mandates that they be instantiated only when needed, which is
10627        done in build_over_call.  */
10628     default_arg = TREE_PURPOSE (arg_types);
10629
10630     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10631       {
10632         /* We've instantiated a template before its default arguments
10633            have been parsed.  This can happen for a nested template
10634            class, and is not an error unless we require the default
10635            argument in a call of this function.  */
10636         remaining_arg_types = 
10637           tree_cons (default_arg, type, remaining_arg_types);
10638         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10639                        remaining_arg_types);
10640       }
10641     else
10642       remaining_arg_types = 
10643         hash_tree_cons (default_arg, type, remaining_arg_types);
10644   }
10645         
10646   return remaining_arg_types;
10647 }
10648
10649 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10650    *not* handle the exception-specification for FNTYPE, because the
10651    initial substitution of explicitly provided template parameters
10652    during argument deduction forbids substitution into the
10653    exception-specification:
10654
10655      [temp.deduct]
10656
10657      All references in the function type of the function template to  the
10658      corresponding template parameters are replaced by the specified tem-
10659      plate argument values.  If a substitution in a template parameter or
10660      in  the function type of the function template results in an invalid
10661      type, type deduction fails.  [Note: The equivalent  substitution  in
10662      exception specifications is done only when the function is instanti-
10663      ated, at which point a program is  ill-formed  if  the  substitution
10664      results in an invalid type.]  */
10665
10666 static tree
10667 tsubst_function_type (tree t,
10668                       tree args,
10669                       tsubst_flags_t complain,
10670                       tree in_decl)
10671 {
10672   tree return_type;
10673   tree arg_types;
10674   tree fntype;
10675
10676   /* The TYPE_CONTEXT is not used for function/method types.  */
10677   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10678
10679   /* Substitute the return type.  */
10680   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10681   if (return_type == error_mark_node)
10682     return error_mark_node;
10683   /* The standard does not presently indicate that creation of a
10684      function type with an invalid return type is a deduction failure.
10685      However, that is clearly analogous to creating an array of "void"
10686      or a reference to a reference.  This is core issue #486.  */
10687   if (TREE_CODE (return_type) == ARRAY_TYPE
10688       || TREE_CODE (return_type) == FUNCTION_TYPE)
10689     {
10690       if (complain & tf_error)
10691         {
10692           if (TREE_CODE (return_type) == ARRAY_TYPE)
10693             error ("function returning an array");
10694           else
10695             error ("function returning a function");
10696         }
10697       return error_mark_node;
10698     }
10699
10700   /* Substitute the argument types.  */
10701   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10702                                 complain, in_decl);
10703   if (arg_types == error_mark_node)
10704     return error_mark_node;
10705
10706   /* Construct a new type node and return it.  */
10707   if (TREE_CODE (t) == FUNCTION_TYPE)
10708     {
10709       fntype = build_function_type (return_type, arg_types);
10710       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10711     }
10712   else
10713     {
10714       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10715       if (! MAYBE_CLASS_TYPE_P (r))
10716         {
10717           /* [temp.deduct]
10718
10719              Type deduction may fail for any of the following
10720              reasons:
10721
10722              -- Attempting to create "pointer to member of T" when T
10723              is not a class type.  */
10724           if (complain & tf_error)
10725             error ("creating pointer to member function of non-class type %qT",
10726                       r);
10727           return error_mark_node;
10728         }
10729
10730       fntype = build_method_type_directly (r, return_type,
10731                                            TREE_CHAIN (arg_types));
10732     }
10733   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10734
10735   return fntype;
10736 }
10737
10738 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10739    ARGS into that specification, and return the substituted
10740    specification.  If there is no specification, return NULL_TREE.  */
10741
10742 static tree
10743 tsubst_exception_specification (tree fntype,
10744                                 tree args,
10745                                 tsubst_flags_t complain,
10746                                 tree in_decl,
10747                                 bool defer_ok)
10748 {
10749   tree specs;
10750   tree new_specs;
10751
10752   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10753   new_specs = NULL_TREE;
10754   if (specs && TREE_PURPOSE (specs))
10755     {
10756       /* A noexcept-specifier.  */
10757       tree expr = TREE_PURPOSE (specs);
10758       if (expr == boolean_true_node || expr == boolean_false_node)
10759         new_specs = expr;
10760       else if (defer_ok)
10761         {
10762           /* Defer instantiation of noexcept-specifiers to avoid
10763              excessive instantiations (c++/49107).  */
10764           new_specs = make_node (DEFERRED_NOEXCEPT);
10765           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10766             {
10767               /* We already partially instantiated this member template,
10768                  so combine the new args with the old.  */
10769               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10770                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10771               DEFERRED_NOEXCEPT_ARGS (new_specs)
10772                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10773             }
10774           else
10775             {
10776               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10777               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10778             }
10779         }
10780       else
10781         new_specs = tsubst_copy_and_build
10782           (expr, args, complain, in_decl, /*function_p=*/false,
10783            /*integral_constant_expression_p=*/true);
10784       new_specs = build_noexcept_spec (new_specs, complain);
10785     }
10786   else if (specs)
10787     {
10788       if (! TREE_VALUE (specs))
10789         new_specs = specs;
10790       else
10791         while (specs)
10792           {
10793             tree spec;
10794             int i, len = 1;
10795             tree expanded_specs = NULL_TREE;
10796
10797             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10798               {
10799                 /* Expand the pack expansion type.  */
10800                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10801                                                        args, complain,
10802                                                        in_decl);
10803
10804                 if (expanded_specs == error_mark_node)
10805                   return error_mark_node;
10806                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10807                   len = TREE_VEC_LENGTH (expanded_specs);
10808                 else
10809                   {
10810                     /* We're substituting into a member template, so
10811                        we got a TYPE_PACK_EXPANSION back.  Add that
10812                        expansion and move on.  */
10813                     gcc_assert (TREE_CODE (expanded_specs) 
10814                                 == TYPE_PACK_EXPANSION);
10815                     new_specs = add_exception_specifier (new_specs,
10816                                                          expanded_specs,
10817                                                          complain);
10818                     specs = TREE_CHAIN (specs);
10819                     continue;
10820                   }
10821               }
10822
10823             for (i = 0; i < len; ++i)
10824               {
10825                 if (expanded_specs)
10826                   spec = TREE_VEC_ELT (expanded_specs, i);
10827                 else
10828                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10829                 if (spec == error_mark_node)
10830                   return spec;
10831                 new_specs = add_exception_specifier (new_specs, spec, 
10832                                                      complain);
10833               }
10834
10835             specs = TREE_CHAIN (specs);
10836           }
10837     }
10838   return new_specs;
10839 }
10840
10841 /* Take the tree structure T and replace template parameters used
10842    therein with the argument vector ARGS.  IN_DECL is an associated
10843    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10844    Issue error and warning messages under control of COMPLAIN.  Note
10845    that we must be relatively non-tolerant of extensions here, in
10846    order to preserve conformance; if we allow substitutions that
10847    should not be allowed, we may allow argument deductions that should
10848    not succeed, and therefore report ambiguous overload situations
10849    where there are none.  In theory, we could allow the substitution,
10850    but indicate that it should have failed, and allow our caller to
10851    make sure that the right thing happens, but we don't try to do this
10852    yet.
10853
10854    This function is used for dealing with types, decls and the like;
10855    for expressions, use tsubst_expr or tsubst_copy.  */
10856
10857 tree
10858 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10859 {
10860   enum tree_code code;
10861   tree type, r;
10862
10863   if (t == NULL_TREE || t == error_mark_node
10864       || t == integer_type_node
10865       || t == void_type_node
10866       || t == char_type_node
10867       || t == unknown_type_node
10868       || TREE_CODE (t) == NAMESPACE_DECL
10869       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10870     return t;
10871
10872   if (DECL_P (t))
10873     return tsubst_decl (t, args, complain);
10874
10875   if (args == NULL_TREE)
10876     return t;
10877
10878   code = TREE_CODE (t);
10879
10880   if (code == IDENTIFIER_NODE)
10881     type = IDENTIFIER_TYPE_VALUE (t);
10882   else
10883     type = TREE_TYPE (t);
10884
10885   gcc_assert (type != unknown_type_node);
10886
10887   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10888      such as attribute aligned.  */
10889   if (TYPE_P (t)
10890       && typedef_variant_p (t))
10891     {
10892       tree decl = TYPE_NAME (t);
10893       
10894       if (DECL_CLASS_SCOPE_P (decl)
10895           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10896           && uses_template_parms (DECL_CONTEXT (decl)))
10897         {
10898           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10899           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10900           r = retrieve_specialization (tmpl, gen_args, 0);
10901         }
10902       else if (DECL_FUNCTION_SCOPE_P (decl)
10903                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10904                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10905         r = retrieve_local_specialization (decl);
10906       else
10907         /* The typedef is from a non-template context.  */
10908         return t;
10909
10910       if (r)
10911         {
10912           r = TREE_TYPE (r);
10913           r = cp_build_qualified_type_real
10914             (r, cp_type_quals (t) | cp_type_quals (r),
10915              complain | tf_ignore_bad_quals);
10916           return r;
10917         }
10918       /* Else we must be instantiating the typedef, so fall through.  */
10919     }
10920
10921   if (type
10922       && code != TYPENAME_TYPE
10923       && code != TEMPLATE_TYPE_PARM
10924       && code != IDENTIFIER_NODE
10925       && code != FUNCTION_TYPE
10926       && code != METHOD_TYPE)
10927     type = tsubst (type, args, complain, in_decl);
10928   if (type == error_mark_node)
10929     return error_mark_node;
10930
10931   switch (code)
10932     {
10933     case RECORD_TYPE:
10934     case UNION_TYPE:
10935     case ENUMERAL_TYPE:
10936       return tsubst_aggr_type (t, args, complain, in_decl,
10937                                /*entering_scope=*/0);
10938
10939     case ERROR_MARK:
10940     case IDENTIFIER_NODE:
10941     case VOID_TYPE:
10942     case REAL_TYPE:
10943     case COMPLEX_TYPE:
10944     case VECTOR_TYPE:
10945     case BOOLEAN_TYPE:
10946     case NULLPTR_TYPE:
10947     case LANG_TYPE:
10948       return t;
10949
10950     case INTEGER_TYPE:
10951       if (t == integer_type_node)
10952         return t;
10953
10954       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10955           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10956         return t;
10957
10958       {
10959         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10960
10961         max = tsubst_expr (omax, args, complain, in_decl,
10962                            /*integral_constant_expression_p=*/false);
10963
10964         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10965            needed.  */
10966         if (TREE_CODE (max) == NOP_EXPR
10967             && TREE_SIDE_EFFECTS (omax)
10968             && !TREE_TYPE (max))
10969           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10970
10971         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10972            with TREE_SIDE_EFFECTS that indicates this is not an integral
10973            constant expression.  */
10974         if (processing_template_decl
10975             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10976           {
10977             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10978             TREE_SIDE_EFFECTS (max) = 1;
10979           }
10980
10981         return compute_array_index_type (NULL_TREE, max, complain);
10982       }
10983
10984     case TEMPLATE_TYPE_PARM:
10985     case TEMPLATE_TEMPLATE_PARM:
10986     case BOUND_TEMPLATE_TEMPLATE_PARM:
10987     case TEMPLATE_PARM_INDEX:
10988       {
10989         int idx;
10990         int level;
10991         int levels;
10992         tree arg = NULL_TREE;
10993
10994         r = NULL_TREE;
10995
10996         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10997         template_parm_level_and_index (t, &level, &idx); 
10998
10999         levels = TMPL_ARGS_DEPTH (args);
11000         if (level <= levels)
11001           {
11002             arg = TMPL_ARG (args, level, idx);
11003
11004             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11005               /* See through ARGUMENT_PACK_SELECT arguments. */
11006               arg = ARGUMENT_PACK_SELECT_ARG (arg);
11007           }
11008
11009         if (arg == error_mark_node)
11010           return error_mark_node;
11011         else if (arg != NULL_TREE)
11012           {
11013             if (ARGUMENT_PACK_P (arg))
11014               /* If ARG is an argument pack, we don't actually want to
11015                  perform a substitution here, because substitutions
11016                  for argument packs are only done
11017                  element-by-element. We can get to this point when
11018                  substituting the type of a non-type template
11019                  parameter pack, when that type actually contains
11020                  template parameter packs from an outer template, e.g.,
11021
11022                  template<typename... Types> struct A {
11023                    template<Types... Values> struct B { };
11024                  };  */
11025               return t;
11026
11027             if (code == TEMPLATE_TYPE_PARM)
11028               {
11029                 int quals;
11030                 gcc_assert (TYPE_P (arg));
11031
11032                 quals = cp_type_quals (arg) | cp_type_quals (t);
11033                   
11034                 return cp_build_qualified_type_real
11035                   (arg, quals, complain | tf_ignore_bad_quals);
11036               }
11037             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11038               {
11039                 /* We are processing a type constructed from a
11040                    template template parameter.  */
11041                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11042                                       args, complain, in_decl);
11043                 if (argvec == error_mark_node)
11044                   return error_mark_node;
11045
11046                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11047                    are resolving nested-types in the signature of a
11048                    member function templates.  Otherwise ARG is a
11049                    TEMPLATE_DECL and is the real template to be
11050                    instantiated.  */
11051                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11052                   arg = TYPE_NAME (arg);
11053
11054                 r = lookup_template_class (arg,
11055                                            argvec, in_decl,
11056                                            DECL_CONTEXT (arg),
11057                                             /*entering_scope=*/0,
11058                                            complain);
11059                 return cp_build_qualified_type_real
11060                   (r, cp_type_quals (t), complain);
11061               }
11062             else
11063               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11064               return convert_from_reference (unshare_expr (arg));
11065           }
11066
11067         if (level == 1)
11068           /* This can happen during the attempted tsubst'ing in
11069              unify.  This means that we don't yet have any information
11070              about the template parameter in question.  */
11071           return t;
11072
11073         /* If we get here, we must have been looking at a parm for a
11074            more deeply nested template.  Make a new version of this
11075            template parameter, but with a lower level.  */
11076         switch (code)
11077           {
11078           case TEMPLATE_TYPE_PARM:
11079           case TEMPLATE_TEMPLATE_PARM:
11080           case BOUND_TEMPLATE_TEMPLATE_PARM:
11081             if (cp_type_quals (t))
11082               {
11083                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11084                 r = cp_build_qualified_type_real
11085                   (r, cp_type_quals (t),
11086                    complain | (code == TEMPLATE_TYPE_PARM
11087                                ? tf_ignore_bad_quals : 0));
11088               }
11089             else
11090               {
11091                 r = copy_type (t);
11092                 TEMPLATE_TYPE_PARM_INDEX (r)
11093                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11094                                                 r, levels, args, complain);
11095                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11096                 TYPE_MAIN_VARIANT (r) = r;
11097                 TYPE_POINTER_TO (r) = NULL_TREE;
11098                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11099
11100                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11101                   /* We have reduced the level of the template
11102                      template parameter, but not the levels of its
11103                      template parameters, so canonical_type_parameter
11104                      will not be able to find the canonical template
11105                      template parameter for this level. Thus, we
11106                      require structural equality checking to compare
11107                      TEMPLATE_TEMPLATE_PARMs. */
11108                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11109                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11110                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11111                 else
11112                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11113
11114                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11115                   {
11116                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11117                                           complain, in_decl);
11118                     if (argvec == error_mark_node)
11119                       return error_mark_node;
11120
11121                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11122                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11123                   }
11124               }
11125             break;
11126
11127           case TEMPLATE_PARM_INDEX:
11128             r = reduce_template_parm_level (t, type, levels, args, complain);
11129             break;
11130
11131           default:
11132             gcc_unreachable ();
11133           }
11134
11135         return r;
11136       }
11137
11138     case TREE_LIST:
11139       {
11140         tree purpose, value, chain;
11141
11142         if (t == void_list_node)
11143           return t;
11144
11145         purpose = TREE_PURPOSE (t);
11146         if (purpose)
11147           {
11148             purpose = tsubst (purpose, args, complain, in_decl);
11149             if (purpose == error_mark_node)
11150               return error_mark_node;
11151           }
11152         value = TREE_VALUE (t);
11153         if (value)
11154           {
11155             value = tsubst (value, args, complain, in_decl);
11156             if (value == error_mark_node)
11157               return error_mark_node;
11158           }
11159         chain = TREE_CHAIN (t);
11160         if (chain && chain != void_type_node)
11161           {
11162             chain = tsubst (chain, args, complain, in_decl);
11163             if (chain == error_mark_node)
11164               return error_mark_node;
11165           }
11166         if (purpose == TREE_PURPOSE (t)
11167             && value == TREE_VALUE (t)
11168             && chain == TREE_CHAIN (t))
11169           return t;
11170         return hash_tree_cons (purpose, value, chain);
11171       }
11172
11173     case TREE_BINFO:
11174       /* We should never be tsubsting a binfo.  */
11175       gcc_unreachable ();
11176
11177     case TREE_VEC:
11178       /* A vector of template arguments.  */
11179       gcc_assert (!type);
11180       return tsubst_template_args (t, args, complain, in_decl);
11181
11182     case POINTER_TYPE:
11183     case REFERENCE_TYPE:
11184       {
11185         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11186           return t;
11187
11188         /* [temp.deduct]
11189
11190            Type deduction may fail for any of the following
11191            reasons:
11192
11193            -- Attempting to create a pointer to reference type.
11194            -- Attempting to create a reference to a reference type or
11195               a reference to void.
11196
11197           Core issue 106 says that creating a reference to a reference
11198           during instantiation is no longer a cause for failure. We
11199           only enforce this check in strict C++98 mode.  */
11200         if ((TREE_CODE (type) == REFERENCE_TYPE
11201              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11202             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11203           {
11204             static location_t last_loc;
11205
11206             /* We keep track of the last time we issued this error
11207                message to avoid spewing a ton of messages during a
11208                single bad template instantiation.  */
11209             if (complain & tf_error
11210                 && last_loc != input_location)
11211               {
11212                 if (TREE_CODE (type) == VOID_TYPE)
11213                   error ("forming reference to void");
11214                else if (code == POINTER_TYPE)
11215                  error ("forming pointer to reference type %qT", type);
11216                else
11217                   error ("forming reference to reference type %qT", type);
11218                 last_loc = input_location;
11219               }
11220
11221             return error_mark_node;
11222           }
11223         else if (code == POINTER_TYPE)
11224           {
11225             r = build_pointer_type (type);
11226             if (TREE_CODE (type) == METHOD_TYPE)
11227               r = build_ptrmemfunc_type (r);
11228           }
11229         else if (TREE_CODE (type) == REFERENCE_TYPE)
11230           /* In C++0x, during template argument substitution, when there is an
11231              attempt to create a reference to a reference type, reference
11232              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11233
11234              "If a template-argument for a template-parameter T names a type
11235              that is a reference to a type A, an attempt to create the type
11236              'lvalue reference to cv T' creates the type 'lvalue reference to
11237              A,' while an attempt to create the type type rvalue reference to
11238              cv T' creates the type T"
11239           */
11240           r = cp_build_reference_type
11241               (TREE_TYPE (type),
11242                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11243         else
11244           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11245         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11246
11247         if (r != error_mark_node)
11248           /* Will this ever be needed for TYPE_..._TO values?  */
11249           layout_type (r);
11250
11251         return r;
11252       }
11253     case OFFSET_TYPE:
11254       {
11255         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11256         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11257           {
11258             /* [temp.deduct]
11259
11260                Type deduction may fail for any of the following
11261                reasons:
11262
11263                -- Attempting to create "pointer to member of T" when T
11264                   is not a class type.  */
11265             if (complain & tf_error)
11266               error ("creating pointer to member of non-class type %qT", r);
11267             return error_mark_node;
11268           }
11269         if (TREE_CODE (type) == REFERENCE_TYPE)
11270           {
11271             if (complain & tf_error)
11272               error ("creating pointer to member reference type %qT", type);
11273             return error_mark_node;
11274           }
11275         if (TREE_CODE (type) == VOID_TYPE)
11276           {
11277             if (complain & tf_error)
11278               error ("creating pointer to member of type void");
11279             return error_mark_node;
11280           }
11281         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11282         if (TREE_CODE (type) == FUNCTION_TYPE)
11283           {
11284             /* The type of the implicit object parameter gets its
11285                cv-qualifiers from the FUNCTION_TYPE. */
11286             tree memptr;
11287             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11288             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11289             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11290                                                  complain);
11291           }
11292         else
11293           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11294                                                cp_type_quals (t),
11295                                                complain);
11296       }
11297     case FUNCTION_TYPE:
11298     case METHOD_TYPE:
11299       {
11300         tree fntype;
11301         tree specs;
11302         fntype = tsubst_function_type (t, args, complain, in_decl);
11303         if (fntype == error_mark_node)
11304           return error_mark_node;
11305
11306         /* Substitute the exception specification.  */
11307         specs = tsubst_exception_specification (t, args, complain,
11308                                                 in_decl, /*defer_ok*/true);
11309         if (specs == error_mark_node)
11310           return error_mark_node;
11311         if (specs)
11312           fntype = build_exception_variant (fntype, specs);
11313         return fntype;
11314       }
11315     case ARRAY_TYPE:
11316       {
11317         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11318         if (domain == error_mark_node)
11319           return error_mark_node;
11320
11321         /* As an optimization, we avoid regenerating the array type if
11322            it will obviously be the same as T.  */
11323         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11324           return t;
11325
11326         /* These checks should match the ones in grokdeclarator.
11327
11328            [temp.deduct]
11329
11330            The deduction may fail for any of the following reasons:
11331
11332            -- Attempting to create an array with an element type that
11333               is void, a function type, or a reference type, or [DR337]
11334               an abstract class type.  */
11335         if (TREE_CODE (type) == VOID_TYPE
11336             || TREE_CODE (type) == FUNCTION_TYPE
11337             || TREE_CODE (type) == REFERENCE_TYPE)
11338           {
11339             if (complain & tf_error)
11340               error ("creating array of %qT", type);
11341             return error_mark_node;
11342           }
11343         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11344           {
11345             if (complain & tf_error)
11346               error ("creating array of %qT, which is an abstract class type",
11347                      type);
11348             return error_mark_node;
11349           }
11350
11351         r = build_cplus_array_type (type, domain);
11352
11353         if (TYPE_USER_ALIGN (t))
11354           {
11355             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11356             TYPE_USER_ALIGN (r) = 1;
11357           }
11358
11359         return r;
11360       }
11361
11362     case TYPENAME_TYPE:
11363       {
11364         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11365                                      in_decl, /*entering_scope=*/1);
11366         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11367                               complain, in_decl);
11368
11369         if (ctx == error_mark_node || f == error_mark_node)
11370           return error_mark_node;
11371
11372         if (!MAYBE_CLASS_TYPE_P (ctx))
11373           {
11374             if (complain & tf_error)
11375               error ("%qT is not a class, struct, or union type", ctx);
11376             return error_mark_node;
11377           }
11378         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11379           {
11380             /* Normally, make_typename_type does not require that the CTX
11381                have complete type in order to allow things like:
11382
11383                  template <class T> struct S { typename S<T>::X Y; };
11384
11385                But, such constructs have already been resolved by this
11386                point, so here CTX really should have complete type, unless
11387                it's a partial instantiation.  */
11388             ctx = complete_type (ctx);
11389             if (!COMPLETE_TYPE_P (ctx))
11390               {
11391                 if (complain & tf_error)
11392                   cxx_incomplete_type_error (NULL_TREE, ctx);
11393                 return error_mark_node;
11394               }
11395           }
11396
11397         f = make_typename_type (ctx, f, typename_type,
11398                                 (complain & tf_error) | tf_keep_type_decl);
11399         if (f == error_mark_node)
11400           return f;
11401         if (TREE_CODE (f) == TYPE_DECL)
11402           {
11403             complain |= tf_ignore_bad_quals;
11404             f = TREE_TYPE (f);
11405           }
11406
11407         if (TREE_CODE (f) != TYPENAME_TYPE)
11408           {
11409             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11410               {
11411                 if (complain & tf_error)
11412                   error ("%qT resolves to %qT, which is not an enumeration type",
11413                          t, f);
11414                 else
11415                   return error_mark_node;
11416               }
11417             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11418               {
11419                 if (complain & tf_error)
11420                   error ("%qT resolves to %qT, which is is not a class type",
11421                          t, f);
11422                 else
11423                   return error_mark_node;
11424               }
11425           }
11426
11427         return cp_build_qualified_type_real
11428           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11429       }
11430
11431     case UNBOUND_CLASS_TEMPLATE:
11432       {
11433         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11434                                      in_decl, /*entering_scope=*/1);
11435         tree name = TYPE_IDENTIFIER (t);
11436         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11437
11438         if (ctx == error_mark_node || name == error_mark_node)
11439           return error_mark_node;
11440
11441         if (parm_list)
11442           parm_list = tsubst_template_parms (parm_list, args, complain);
11443         return make_unbound_class_template (ctx, name, parm_list, complain);
11444       }
11445
11446     case TYPEOF_TYPE:
11447       {
11448         tree type;
11449
11450         ++cp_unevaluated_operand;
11451         ++c_inhibit_evaluation_warnings;
11452
11453         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11454                             complain, in_decl,
11455                             /*integral_constant_expression_p=*/false);
11456
11457         --cp_unevaluated_operand;
11458         --c_inhibit_evaluation_warnings;
11459
11460         type = finish_typeof (type);
11461         return cp_build_qualified_type_real (type,
11462                                              cp_type_quals (t)
11463                                              | cp_type_quals (type),
11464                                              complain);
11465       }
11466
11467     case DECLTYPE_TYPE:
11468       {
11469         tree type;
11470
11471         ++cp_unevaluated_operand;
11472         ++c_inhibit_evaluation_warnings;
11473
11474         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11475                             complain, in_decl,
11476                             /*integral_constant_expression_p=*/false);
11477
11478         --cp_unevaluated_operand;
11479         --c_inhibit_evaluation_warnings;
11480
11481         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11482           type = lambda_capture_field_type (type);
11483         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11484           type = lambda_proxy_type (type);
11485         else
11486           type = finish_decltype_type
11487             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11488         return cp_build_qualified_type_real (type,
11489                                              cp_type_quals (t)
11490                                              | cp_type_quals (type),
11491                                              complain);
11492       }
11493
11494     case UNDERLYING_TYPE:
11495       {
11496         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11497                             complain, in_decl);
11498         return finish_underlying_type (type);
11499       }
11500
11501     case TYPE_ARGUMENT_PACK:
11502     case NONTYPE_ARGUMENT_PACK:
11503       {
11504         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11505         tree packed_out = 
11506           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11507                                 args,
11508                                 complain,
11509                                 in_decl);
11510         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11511
11512         /* For template nontype argument packs, also substitute into
11513            the type.  */
11514         if (code == NONTYPE_ARGUMENT_PACK)
11515           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11516
11517         return r;
11518       }
11519       break;
11520
11521     case INTEGER_CST:
11522     case REAL_CST:
11523     case STRING_CST:
11524     case PLUS_EXPR:
11525     case MINUS_EXPR:
11526     case NEGATE_EXPR:
11527     case NOP_EXPR:
11528     case INDIRECT_REF:
11529     case ADDR_EXPR:
11530     case CALL_EXPR:
11531     case ARRAY_REF:
11532     case SCOPE_REF:
11533       /* We should use one of the expression tsubsts for these codes.  */
11534       gcc_unreachable ();
11535
11536     default:
11537       sorry ("use of %qs in template", tree_code_name [(int) code]);
11538       return error_mark_node;
11539     }
11540 }
11541
11542 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11543    type of the expression on the left-hand side of the "." or "->"
11544    operator.  */
11545
11546 static tree
11547 tsubst_baselink (tree baselink, tree object_type,
11548                  tree args, tsubst_flags_t complain, tree in_decl)
11549 {
11550     tree name;
11551     tree qualifying_scope;
11552     tree fns;
11553     tree optype;
11554     tree template_args = 0;
11555     bool template_id_p = false;
11556
11557     /* A baselink indicates a function from a base class.  Both the
11558        BASELINK_ACCESS_BINFO and the base class referenced may
11559        indicate bases of the template class, rather than the
11560        instantiated class.  In addition, lookups that were not
11561        ambiguous before may be ambiguous now.  Therefore, we perform
11562        the lookup again.  */
11563     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11564     qualifying_scope = tsubst (qualifying_scope, args,
11565                                complain, in_decl);
11566     fns = BASELINK_FUNCTIONS (baselink);
11567     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11568     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11569       {
11570         template_id_p = true;
11571         template_args = TREE_OPERAND (fns, 1);
11572         fns = TREE_OPERAND (fns, 0);
11573         if (template_args)
11574           template_args = tsubst_template_args (template_args, args,
11575                                                 complain, in_decl);
11576       }
11577     name = DECL_NAME (get_first_fn (fns));
11578     if (IDENTIFIER_TYPENAME_P (name))
11579       name = mangle_conv_op_name_for_type (optype);
11580     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11581     if (!baselink)
11582       return error_mark_node;
11583
11584     /* If lookup found a single function, mark it as used at this
11585        point.  (If it lookup found multiple functions the one selected
11586        later by overload resolution will be marked as used at that
11587        point.)  */
11588     if (BASELINK_P (baselink))
11589       fns = BASELINK_FUNCTIONS (baselink);
11590     if (!template_id_p && !really_overloaded_fn (fns))
11591       mark_used (OVL_CURRENT (fns));
11592
11593     /* Add back the template arguments, if present.  */
11594     if (BASELINK_P (baselink) && template_id_p)
11595       BASELINK_FUNCTIONS (baselink)
11596         = build_nt (TEMPLATE_ID_EXPR,
11597                     BASELINK_FUNCTIONS (baselink),
11598                     template_args);
11599     /* Update the conversion operator type.  */
11600     BASELINK_OPTYPE (baselink) = optype;
11601
11602     if (!object_type)
11603       object_type = current_class_type;
11604     return adjust_result_of_qualified_name_lookup (baselink,
11605                                                    qualifying_scope,
11606                                                    object_type);
11607 }
11608
11609 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11610    true if the qualified-id will be a postfix-expression in-and-of
11611    itself; false if more of the postfix-expression follows the
11612    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11613    of "&".  */
11614
11615 static tree
11616 tsubst_qualified_id (tree qualified_id, tree args,
11617                      tsubst_flags_t complain, tree in_decl,
11618                      bool done, bool address_p)
11619 {
11620   tree expr;
11621   tree scope;
11622   tree name;
11623   bool is_template;
11624   tree template_args;
11625
11626   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11627
11628   /* Figure out what name to look up.  */
11629   name = TREE_OPERAND (qualified_id, 1);
11630   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11631     {
11632       is_template = true;
11633       template_args = TREE_OPERAND (name, 1);
11634       if (template_args)
11635         template_args = tsubst_template_args (template_args, args,
11636                                               complain, in_decl);
11637       name = TREE_OPERAND (name, 0);
11638     }
11639   else
11640     {
11641       is_template = false;
11642       template_args = NULL_TREE;
11643     }
11644
11645   /* Substitute into the qualifying scope.  When there are no ARGS, we
11646      are just trying to simplify a non-dependent expression.  In that
11647      case the qualifying scope may be dependent, and, in any case,
11648      substituting will not help.  */
11649   scope = TREE_OPERAND (qualified_id, 0);
11650   if (args)
11651     {
11652       scope = tsubst (scope, args, complain, in_decl);
11653       expr = tsubst_copy (name, args, complain, in_decl);
11654     }
11655   else
11656     expr = name;
11657
11658   if (dependent_scope_p (scope))
11659     {
11660       if (is_template)
11661         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11662       return build_qualified_name (NULL_TREE, scope, expr,
11663                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11664     }
11665
11666   if (!BASELINK_P (name) && !DECL_P (expr))
11667     {
11668       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11669         {
11670           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11671           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11672             {
11673               error ("qualifying type %qT does not match destructor name ~%qT",
11674                      scope, TREE_OPERAND (expr, 0));
11675               expr = error_mark_node;
11676             }
11677           else
11678             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11679                                           /*is_type_p=*/0, false);
11680         }
11681       else
11682         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11683       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11684                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11685         {
11686           if (complain & tf_error)
11687             {
11688               error ("dependent-name %qE is parsed as a non-type, but "
11689                      "instantiation yields a type", qualified_id);
11690               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11691             }
11692           return error_mark_node;
11693         }
11694     }
11695
11696   if (DECL_P (expr))
11697     {
11698       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11699                                            scope);
11700       /* Remember that there was a reference to this entity.  */
11701       mark_used (expr);
11702     }
11703
11704   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11705     {
11706       if (complain & tf_error)
11707         qualified_name_lookup_error (scope,
11708                                      TREE_OPERAND (qualified_id, 1),
11709                                      expr, input_location);
11710       return error_mark_node;
11711     }
11712
11713   if (is_template)
11714     expr = lookup_template_function (expr, template_args);
11715
11716   if (expr == error_mark_node && complain & tf_error)
11717     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11718                                  expr, input_location);
11719   else if (TYPE_P (scope))
11720     {
11721       expr = (adjust_result_of_qualified_name_lookup
11722               (expr, scope, current_class_type));
11723       expr = (finish_qualified_id_expr
11724               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11725                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11726                /*template_arg_p=*/false));
11727     }
11728
11729   /* Expressions do not generally have reference type.  */
11730   if (TREE_CODE (expr) != SCOPE_REF
11731       /* However, if we're about to form a pointer-to-member, we just
11732          want the referenced member referenced.  */
11733       && TREE_CODE (expr) != OFFSET_REF)
11734     expr = convert_from_reference (expr);
11735
11736   return expr;
11737 }
11738
11739 /* Like tsubst, but deals with expressions.  This function just replaces
11740    template parms; to finish processing the resultant expression, use
11741    tsubst_copy_and_build or tsubst_expr.  */
11742
11743 static tree
11744 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11745 {
11746   enum tree_code code;
11747   tree r;
11748
11749   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11750     return t;
11751
11752   code = TREE_CODE (t);
11753
11754   switch (code)
11755     {
11756     case PARM_DECL:
11757       r = retrieve_local_specialization (t);
11758
11759       if (r == NULL)
11760         {
11761           tree c;
11762
11763           /* We get here for a use of 'this' in an NSDMI.  */
11764           if (DECL_NAME (t) == this_identifier
11765               && at_function_scope_p ()
11766               && DECL_CONSTRUCTOR_P (current_function_decl))
11767             return current_class_ptr;
11768
11769           /* This can happen for a parameter name used later in a function
11770              declaration (such as in a late-specified return type).  Just
11771              make a dummy decl, since it's only used for its type.  */
11772           gcc_assert (cp_unevaluated_operand != 0);
11773           /* We copy T because want to tsubst the PARM_DECL only,
11774              not the following PARM_DECLs that are chained to T.  */
11775           c = copy_node (t);
11776           r = tsubst_decl (c, args, complain);
11777           /* Give it the template pattern as its context; its true context
11778              hasn't been instantiated yet and this is good enough for
11779              mangling.  */
11780           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11781         }
11782       
11783       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11784         r = ARGUMENT_PACK_SELECT_ARG (r);
11785       mark_used (r);
11786       return r;
11787
11788     case CONST_DECL:
11789       {
11790         tree enum_type;
11791         tree v;
11792
11793         if (DECL_TEMPLATE_PARM_P (t))
11794           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11795         /* There is no need to substitute into namespace-scope
11796            enumerators.  */
11797         if (DECL_NAMESPACE_SCOPE_P (t))
11798           return t;
11799         /* If ARGS is NULL, then T is known to be non-dependent.  */
11800         if (args == NULL_TREE)
11801           return integral_constant_value (t);
11802
11803         /* Unfortunately, we cannot just call lookup_name here.
11804            Consider:
11805
11806              template <int I> int f() {
11807              enum E { a = I };
11808              struct S { void g() { E e = a; } };
11809              };
11810
11811            When we instantiate f<7>::S::g(), say, lookup_name is not
11812            clever enough to find f<7>::a.  */
11813         enum_type
11814           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11815                               /*entering_scope=*/0);
11816
11817         for (v = TYPE_VALUES (enum_type);
11818              v != NULL_TREE;
11819              v = TREE_CHAIN (v))
11820           if (TREE_PURPOSE (v) == DECL_NAME (t))
11821             return TREE_VALUE (v);
11822
11823           /* We didn't find the name.  That should never happen; if
11824              name-lookup found it during preliminary parsing, we
11825              should find it again here during instantiation.  */
11826         gcc_unreachable ();
11827       }
11828       return t;
11829
11830     case FIELD_DECL:
11831       if (DECL_CONTEXT (t))
11832         {
11833           tree ctx;
11834
11835           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11836                                   /*entering_scope=*/1);
11837           if (ctx != DECL_CONTEXT (t))
11838             {
11839               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11840               if (!r)
11841                 {
11842                   if (complain & tf_error)
11843                     error ("using invalid field %qD", t);
11844                   return error_mark_node;
11845                 }
11846               return r;
11847             }
11848         }
11849
11850       return t;
11851
11852     case VAR_DECL:
11853     case FUNCTION_DECL:
11854       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11855           || local_variable_p (t))
11856         t = tsubst (t, args, complain, in_decl);
11857       mark_used (t);
11858       return t;
11859
11860     case OVERLOAD:
11861       /* An OVERLOAD will always be a non-dependent overload set; an
11862          overload set from function scope will just be represented with an
11863          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11864       gcc_assert (!uses_template_parms (t));
11865       return t;
11866
11867     case BASELINK:
11868       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11869
11870     case TEMPLATE_DECL:
11871       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11872         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11873                        args, complain, in_decl);
11874       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11875         return tsubst (t, args, complain, in_decl);
11876       else if (DECL_CLASS_SCOPE_P (t)
11877                && uses_template_parms (DECL_CONTEXT (t)))
11878         {
11879           /* Template template argument like the following example need
11880              special treatment:
11881
11882                template <template <class> class TT> struct C {};
11883                template <class T> struct D {
11884                  template <class U> struct E {};
11885                  C<E> c;                                // #1
11886                };
11887                D<int> d;                                // #2
11888
11889              We are processing the template argument `E' in #1 for
11890              the template instantiation #2.  Originally, `E' is a
11891              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11892              have to substitute this with one having context `D<int>'.  */
11893
11894           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11895           return lookup_field (context, DECL_NAME(t), 0, false);
11896         }
11897       else
11898         /* Ordinary template template argument.  */
11899         return t;
11900
11901     case CAST_EXPR:
11902     case REINTERPRET_CAST_EXPR:
11903     case CONST_CAST_EXPR:
11904     case STATIC_CAST_EXPR:
11905     case DYNAMIC_CAST_EXPR:
11906     case IMPLICIT_CONV_EXPR:
11907     case CONVERT_EXPR:
11908     case NOP_EXPR:
11909       return build1
11910         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11911          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11912
11913     case SIZEOF_EXPR:
11914       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11915         {
11916
11917           tree expanded;
11918           int len = 0;
11919
11920           ++cp_unevaluated_operand;
11921           ++c_inhibit_evaluation_warnings;
11922           /* We only want to compute the number of arguments.  */
11923           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11924                                             complain, in_decl);
11925           --cp_unevaluated_operand;
11926           --c_inhibit_evaluation_warnings;
11927
11928           if (TREE_CODE (expanded) == TREE_VEC)
11929             len = TREE_VEC_LENGTH (expanded);
11930
11931           if (expanded == error_mark_node)
11932             return error_mark_node;
11933           else if (PACK_EXPANSION_P (expanded)
11934                    || (TREE_CODE (expanded) == TREE_VEC
11935                        && len > 0
11936                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11937             {
11938               if (TREE_CODE (expanded) == TREE_VEC)
11939                 expanded = TREE_VEC_ELT (expanded, len - 1);
11940
11941               if (TYPE_P (expanded))
11942                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11943                                                    complain & tf_error);
11944               else
11945                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11946                                                    complain & tf_error);
11947             }
11948           else
11949             return build_int_cst (size_type_node, len);
11950         }
11951       /* Fall through */
11952
11953     case INDIRECT_REF:
11954     case NEGATE_EXPR:
11955     case TRUTH_NOT_EXPR:
11956     case BIT_NOT_EXPR:
11957     case ADDR_EXPR:
11958     case UNARY_PLUS_EXPR:      /* Unary + */
11959     case ALIGNOF_EXPR:
11960     case AT_ENCODE_EXPR:
11961     case ARROW_EXPR:
11962     case THROW_EXPR:
11963     case TYPEID_EXPR:
11964     case REALPART_EXPR:
11965     case IMAGPART_EXPR:
11966       return build1
11967         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11968          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11969
11970     case COMPONENT_REF:
11971       {
11972         tree object;
11973         tree name;
11974
11975         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11976         name = TREE_OPERAND (t, 1);
11977         if (TREE_CODE (name) == BIT_NOT_EXPR)
11978           {
11979             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11980                                 complain, in_decl);
11981             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11982           }
11983         else if (TREE_CODE (name) == SCOPE_REF
11984                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11985           {
11986             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11987                                      complain, in_decl);
11988             name = TREE_OPERAND (name, 1);
11989             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11990                                 complain, in_decl);
11991             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11992             name = build_qualified_name (/*type=*/NULL_TREE,
11993                                          base, name,
11994                                          /*template_p=*/false);
11995           }
11996         else if (BASELINK_P (name))
11997           name = tsubst_baselink (name,
11998                                   non_reference (TREE_TYPE (object)),
11999                                   args, complain,
12000                                   in_decl);
12001         else
12002           name = tsubst_copy (name, args, complain, in_decl);
12003         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
12004       }
12005
12006     case PLUS_EXPR:
12007     case MINUS_EXPR:
12008     case MULT_EXPR:
12009     case TRUNC_DIV_EXPR:
12010     case CEIL_DIV_EXPR:
12011     case FLOOR_DIV_EXPR:
12012     case ROUND_DIV_EXPR:
12013     case EXACT_DIV_EXPR:
12014     case BIT_AND_EXPR:
12015     case BIT_IOR_EXPR:
12016     case BIT_XOR_EXPR:
12017     case TRUNC_MOD_EXPR:
12018     case FLOOR_MOD_EXPR:
12019     case TRUTH_ANDIF_EXPR:
12020     case TRUTH_ORIF_EXPR:
12021     case TRUTH_AND_EXPR:
12022     case TRUTH_OR_EXPR:
12023     case RSHIFT_EXPR:
12024     case LSHIFT_EXPR:
12025     case RROTATE_EXPR:
12026     case LROTATE_EXPR:
12027     case EQ_EXPR:
12028     case NE_EXPR:
12029     case MAX_EXPR:
12030     case MIN_EXPR:
12031     case LE_EXPR:
12032     case GE_EXPR:
12033     case LT_EXPR:
12034     case GT_EXPR:
12035     case COMPOUND_EXPR:
12036     case DOTSTAR_EXPR:
12037     case MEMBER_REF:
12038     case PREDECREMENT_EXPR:
12039     case PREINCREMENT_EXPR:
12040     case POSTDECREMENT_EXPR:
12041     case POSTINCREMENT_EXPR:
12042       return build_nt
12043         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12044          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12045
12046     case SCOPE_REF:
12047       return build_qualified_name (/*type=*/NULL_TREE,
12048                                    tsubst_copy (TREE_OPERAND (t, 0),
12049                                                 args, complain, in_decl),
12050                                    tsubst_copy (TREE_OPERAND (t, 1),
12051                                                 args, complain, in_decl),
12052                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12053
12054     case ARRAY_REF:
12055       return build_nt
12056         (ARRAY_REF,
12057          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12058          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12059          NULL_TREE, NULL_TREE);
12060
12061     case CALL_EXPR:
12062       {
12063         int n = VL_EXP_OPERAND_LENGTH (t);
12064         tree result = build_vl_exp (CALL_EXPR, n);
12065         int i;
12066         for (i = 0; i < n; i++)
12067           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12068                                              complain, in_decl);
12069         return result;
12070       }
12071
12072     case COND_EXPR:
12073     case MODOP_EXPR:
12074     case PSEUDO_DTOR_EXPR:
12075       {
12076         r = build_nt
12077           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12078            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12079            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12080         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12081         return r;
12082       }
12083
12084     case NEW_EXPR:
12085       {
12086         r = build_nt
12087         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12088          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12089          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12090         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12091         return r;
12092       }
12093
12094     case DELETE_EXPR:
12095       {
12096         r = build_nt
12097         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12098          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12099         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12100         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12101         return r;
12102       }
12103
12104     case TEMPLATE_ID_EXPR:
12105       {
12106         /* Substituted template arguments */
12107         tree fn = TREE_OPERAND (t, 0);
12108         tree targs = TREE_OPERAND (t, 1);
12109
12110         fn = tsubst_copy (fn, args, complain, in_decl);
12111         if (targs)
12112           targs = tsubst_template_args (targs, args, complain, in_decl);
12113
12114         return lookup_template_function (fn, targs);
12115       }
12116
12117     case TREE_LIST:
12118       {
12119         tree purpose, value, chain;
12120
12121         if (t == void_list_node)
12122           return t;
12123
12124         purpose = TREE_PURPOSE (t);
12125         if (purpose)
12126           purpose = tsubst_copy (purpose, args, complain, in_decl);
12127         value = TREE_VALUE (t);
12128         if (value)
12129           value = tsubst_copy (value, args, complain, in_decl);
12130         chain = TREE_CHAIN (t);
12131         if (chain && chain != void_type_node)
12132           chain = tsubst_copy (chain, args, complain, in_decl);
12133         if (purpose == TREE_PURPOSE (t)
12134             && value == TREE_VALUE (t)
12135             && chain == TREE_CHAIN (t))
12136           return t;
12137         return tree_cons (purpose, value, chain);
12138       }
12139
12140     case RECORD_TYPE:
12141     case UNION_TYPE:
12142     case ENUMERAL_TYPE:
12143     case INTEGER_TYPE:
12144     case TEMPLATE_TYPE_PARM:
12145     case TEMPLATE_TEMPLATE_PARM:
12146     case BOUND_TEMPLATE_TEMPLATE_PARM:
12147     case TEMPLATE_PARM_INDEX:
12148     case POINTER_TYPE:
12149     case REFERENCE_TYPE:
12150     case OFFSET_TYPE:
12151     case FUNCTION_TYPE:
12152     case METHOD_TYPE:
12153     case ARRAY_TYPE:
12154     case TYPENAME_TYPE:
12155     case UNBOUND_CLASS_TEMPLATE:
12156     case TYPEOF_TYPE:
12157     case DECLTYPE_TYPE:
12158     case TYPE_DECL:
12159       return tsubst (t, args, complain, in_decl);
12160
12161     case IDENTIFIER_NODE:
12162       if (IDENTIFIER_TYPENAME_P (t))
12163         {
12164           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12165           return mangle_conv_op_name_for_type (new_type);
12166         }
12167       else
12168         return t;
12169
12170     case CONSTRUCTOR:
12171       /* This is handled by tsubst_copy_and_build.  */
12172       gcc_unreachable ();
12173
12174     case VA_ARG_EXPR:
12175       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12176                                           in_decl),
12177                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12178
12179     case CLEANUP_POINT_EXPR:
12180       /* We shouldn't have built any of these during initial template
12181          generation.  Instead, they should be built during instantiation
12182          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12183       gcc_unreachable ();
12184
12185     case OFFSET_REF:
12186       r = build2
12187         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12188          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12189          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12190       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12191       mark_used (TREE_OPERAND (r, 1));
12192       return r;
12193
12194     case EXPR_PACK_EXPANSION:
12195       error ("invalid use of pack expansion expression");
12196       return error_mark_node;
12197
12198     case NONTYPE_ARGUMENT_PACK:
12199       error ("use %<...%> to expand argument pack");
12200       return error_mark_node;
12201
12202     case INTEGER_CST:
12203     case REAL_CST:
12204     case STRING_CST:
12205     case COMPLEX_CST:
12206       {
12207         /* Instantiate any typedefs in the type.  */
12208         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12209         r = fold_convert (type, t);
12210         gcc_assert (TREE_CODE (r) == code);
12211         return r;
12212       }
12213
12214     case PTRMEM_CST:
12215       /* These can sometimes show up in a partial instantiation, but never
12216          involve template parms.  */
12217       gcc_assert (!uses_template_parms (t));
12218       return t;
12219
12220     default:
12221       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12222       gcc_checking_assert (false);
12223       return t;
12224     }
12225 }
12226
12227 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12228
12229 static tree
12230 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12231                     tree in_decl)
12232 {
12233   tree new_clauses = NULL, nc, oc;
12234
12235   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12236     {
12237       nc = copy_node (oc);
12238       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12239       new_clauses = nc;
12240
12241       switch (OMP_CLAUSE_CODE (nc))
12242         {
12243         case OMP_CLAUSE_LASTPRIVATE:
12244           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12245             {
12246               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12247               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12248                            in_decl, /*integral_constant_expression_p=*/false);
12249               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12250                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12251             }
12252           /* FALLTHRU */
12253         case OMP_CLAUSE_PRIVATE:
12254         case OMP_CLAUSE_SHARED:
12255         case OMP_CLAUSE_FIRSTPRIVATE:
12256         case OMP_CLAUSE_REDUCTION:
12257         case OMP_CLAUSE_COPYIN:
12258         case OMP_CLAUSE_COPYPRIVATE:
12259         case OMP_CLAUSE_IF:
12260         case OMP_CLAUSE_NUM_THREADS:
12261         case OMP_CLAUSE_SCHEDULE:
12262         case OMP_CLAUSE_COLLAPSE:
12263         case OMP_CLAUSE_FINAL:
12264           OMP_CLAUSE_OPERAND (nc, 0)
12265             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12266                            in_decl, /*integral_constant_expression_p=*/false);
12267           break;
12268         case OMP_CLAUSE_NOWAIT:
12269         case OMP_CLAUSE_ORDERED:
12270         case OMP_CLAUSE_DEFAULT:
12271         case OMP_CLAUSE_UNTIED:
12272         case OMP_CLAUSE_MERGEABLE:
12273           break;
12274         default:
12275           gcc_unreachable ();
12276         }
12277     }
12278
12279   return finish_omp_clauses (nreverse (new_clauses));
12280 }
12281
12282 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12283
12284 static tree
12285 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12286                           tree in_decl)
12287 {
12288 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12289
12290   tree purpose, value, chain;
12291
12292   if (t == NULL)
12293     return t;
12294
12295   if (TREE_CODE (t) != TREE_LIST)
12296     return tsubst_copy_and_build (t, args, complain, in_decl,
12297                                   /*function_p=*/false,
12298                                   /*integral_constant_expression_p=*/false);
12299
12300   if (t == void_list_node)
12301     return t;
12302
12303   purpose = TREE_PURPOSE (t);
12304   if (purpose)
12305     purpose = RECUR (purpose);
12306   value = TREE_VALUE (t);
12307   if (value && TREE_CODE (value) != LABEL_DECL)
12308     value = RECUR (value);
12309   chain = TREE_CHAIN (t);
12310   if (chain && chain != void_type_node)
12311     chain = RECUR (chain);
12312   return tree_cons (purpose, value, chain);
12313 #undef RECUR
12314 }
12315
12316 /* Substitute one OMP_FOR iterator.  */
12317
12318 static void
12319 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12320                          tree condv, tree incrv, tree *clauses,
12321                          tree args, tsubst_flags_t complain, tree in_decl,
12322                          bool integral_constant_expression_p)
12323 {
12324 #define RECUR(NODE)                             \
12325   tsubst_expr ((NODE), args, complain, in_decl, \
12326                integral_constant_expression_p)
12327   tree decl, init, cond, incr, auto_node;
12328
12329   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12330   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12331   decl = RECUR (TREE_OPERAND (init, 0));
12332   init = TREE_OPERAND (init, 1);
12333   auto_node = type_uses_auto (TREE_TYPE (decl));
12334   if (auto_node && init)
12335     {
12336       tree init_expr = init;
12337       if (TREE_CODE (init_expr) == DECL_EXPR)
12338         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12339       init_expr = RECUR (init_expr);
12340       TREE_TYPE (decl)
12341         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12342     }
12343   gcc_assert (!type_dependent_expression_p (decl));
12344
12345   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12346     {
12347       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12348       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12349       if (TREE_CODE (incr) == MODIFY_EXPR)
12350         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12351                                     RECUR (TREE_OPERAND (incr, 1)),
12352                                     complain);
12353       else
12354         incr = RECUR (incr);
12355       TREE_VEC_ELT (declv, i) = decl;
12356       TREE_VEC_ELT (initv, i) = init;
12357       TREE_VEC_ELT (condv, i) = cond;
12358       TREE_VEC_ELT (incrv, i) = incr;
12359       return;
12360     }
12361
12362   if (init && TREE_CODE (init) != DECL_EXPR)
12363     {
12364       tree c;
12365       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12366         {
12367           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12368                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12369               && OMP_CLAUSE_DECL (c) == decl)
12370             break;
12371           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12372                    && OMP_CLAUSE_DECL (c) == decl)
12373             error ("iteration variable %qD should not be firstprivate", decl);
12374           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12375                    && OMP_CLAUSE_DECL (c) == decl)
12376             error ("iteration variable %qD should not be reduction", decl);
12377         }
12378       if (c == NULL)
12379         {
12380           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12381           OMP_CLAUSE_DECL (c) = decl;
12382           c = finish_omp_clauses (c);
12383           if (c)
12384             {
12385               OMP_CLAUSE_CHAIN (c) = *clauses;
12386               *clauses = c;
12387             }
12388         }
12389     }
12390   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12391   if (COMPARISON_CLASS_P (cond))
12392     cond = build2 (TREE_CODE (cond), boolean_type_node,
12393                    RECUR (TREE_OPERAND (cond, 0)),
12394                    RECUR (TREE_OPERAND (cond, 1)));
12395   else
12396     cond = RECUR (cond);
12397   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12398   switch (TREE_CODE (incr))
12399     {
12400     case PREINCREMENT_EXPR:
12401     case PREDECREMENT_EXPR:
12402     case POSTINCREMENT_EXPR:
12403     case POSTDECREMENT_EXPR:
12404       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12405                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12406       break;
12407     case MODIFY_EXPR:
12408       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12409           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12410         {
12411           tree rhs = TREE_OPERAND (incr, 1);
12412           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12413                          RECUR (TREE_OPERAND (incr, 0)),
12414                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12415                                  RECUR (TREE_OPERAND (rhs, 0)),
12416                                  RECUR (TREE_OPERAND (rhs, 1))));
12417         }
12418       else
12419         incr = RECUR (incr);
12420       break;
12421     case MODOP_EXPR:
12422       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12423           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12424         {
12425           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12426           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12427                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12428                                  TREE_TYPE (decl), lhs,
12429                                  RECUR (TREE_OPERAND (incr, 2))));
12430         }
12431       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12432                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12433                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12434         {
12435           tree rhs = TREE_OPERAND (incr, 2);
12436           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12437                          RECUR (TREE_OPERAND (incr, 0)),
12438                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12439                                  RECUR (TREE_OPERAND (rhs, 0)),
12440                                  RECUR (TREE_OPERAND (rhs, 1))));
12441         }
12442       else
12443         incr = RECUR (incr);
12444       break;
12445     default:
12446       incr = RECUR (incr);
12447       break;
12448     }
12449
12450   TREE_VEC_ELT (declv, i) = decl;
12451   TREE_VEC_ELT (initv, i) = init;
12452   TREE_VEC_ELT (condv, i) = cond;
12453   TREE_VEC_ELT (incrv, i) = incr;
12454 #undef RECUR
12455 }
12456
12457 /* Like tsubst_copy for expressions, etc. but also does semantic
12458    processing.  */
12459
12460 static tree
12461 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12462              bool integral_constant_expression_p)
12463 {
12464 #define RECUR(NODE)                             \
12465   tsubst_expr ((NODE), args, complain, in_decl, \
12466                integral_constant_expression_p)
12467
12468   tree stmt, tmp;
12469
12470   if (t == NULL_TREE || t == error_mark_node)
12471     return t;
12472
12473   if (EXPR_HAS_LOCATION (t))
12474     input_location = EXPR_LOCATION (t);
12475   if (STATEMENT_CODE_P (TREE_CODE (t)))
12476     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12477
12478   switch (TREE_CODE (t))
12479     {
12480     case STATEMENT_LIST:
12481       {
12482         tree_stmt_iterator i;
12483         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12484           RECUR (tsi_stmt (i));
12485         break;
12486       }
12487
12488     case CTOR_INITIALIZER:
12489       finish_mem_initializers (tsubst_initializer_list
12490                                (TREE_OPERAND (t, 0), args));
12491       break;
12492
12493     case RETURN_EXPR:
12494       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12495       break;
12496
12497     case EXPR_STMT:
12498       tmp = RECUR (EXPR_STMT_EXPR (t));
12499       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12500         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12501       else
12502         finish_expr_stmt (tmp);
12503       break;
12504
12505     case USING_STMT:
12506       do_using_directive (USING_STMT_NAMESPACE (t));
12507       break;
12508
12509     case DECL_EXPR:
12510       {
12511         tree decl, pattern_decl;
12512         tree init;
12513
12514         pattern_decl = decl = DECL_EXPR_DECL (t);
12515         if (TREE_CODE (decl) == LABEL_DECL)
12516           finish_label_decl (DECL_NAME (decl));
12517         else if (TREE_CODE (decl) == USING_DECL)
12518           {
12519             tree scope = USING_DECL_SCOPE (decl);
12520             tree name = DECL_NAME (decl);
12521             tree decl;
12522
12523             scope = tsubst (scope, args, complain, in_decl);
12524             decl = lookup_qualified_name (scope, name,
12525                                           /*is_type_p=*/false,
12526                                           /*complain=*/false);
12527             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12528               qualified_name_lookup_error (scope, name, decl, input_location);
12529             else
12530               do_local_using_decl (decl, scope, name);
12531           }
12532         else
12533           {
12534             init = DECL_INITIAL (decl);
12535             decl = tsubst (decl, args, complain, in_decl);
12536             if (decl != error_mark_node)
12537               {
12538                 /* By marking the declaration as instantiated, we avoid
12539                    trying to instantiate it.  Since instantiate_decl can't
12540                    handle local variables, and since we've already done
12541                    all that needs to be done, that's the right thing to
12542                    do.  */
12543                 if (TREE_CODE (decl) == VAR_DECL)
12544                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12545                 if (TREE_CODE (decl) == VAR_DECL
12546                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12547                   /* Anonymous aggregates are a special case.  */
12548                   finish_anon_union (decl);
12549                 else
12550                   {
12551                     int const_init = false;
12552                     maybe_push_decl (decl);
12553                     if (TREE_CODE (decl) == VAR_DECL
12554                         && DECL_PRETTY_FUNCTION_P (decl))
12555                       {
12556                         /* For __PRETTY_FUNCTION__ we have to adjust the
12557                            initializer.  */
12558                         const char *const name
12559                           = cxx_printable_name (current_function_decl, 2);
12560                         init = cp_fname_init (name, &TREE_TYPE (decl));
12561                       }
12562                     else
12563                       {
12564                         tree t = RECUR (init);
12565
12566                         if (init && !t)
12567                           {
12568                             /* If we had an initializer but it
12569                                instantiated to nothing,
12570                                value-initialize the object.  This will
12571                                only occur when the initializer was a
12572                                pack expansion where the parameter packs
12573                                used in that expansion were of length
12574                                zero.  */
12575                             init = build_value_init (TREE_TYPE (decl),
12576                                                      complain);
12577                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12578                               init = get_target_expr_sfinae (init, complain);
12579                           }
12580                         else
12581                           init = t;
12582                       }
12583
12584                     if (TREE_CODE (decl) == VAR_DECL)
12585                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12586                                     (pattern_decl));
12587                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12588                   }
12589               }
12590           }
12591
12592         /* A DECL_EXPR can also be used as an expression, in the condition
12593            clause of an if/for/while construct.  */
12594         return decl;
12595       }
12596
12597     case FOR_STMT:
12598       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12599       RECUR (FOR_INIT_STMT (t));
12600       finish_for_init_stmt (stmt);
12601       tmp = RECUR (FOR_COND (t));
12602       finish_for_cond (tmp, stmt);
12603       tmp = RECUR (FOR_EXPR (t));
12604       finish_for_expr (tmp, stmt);
12605       RECUR (FOR_BODY (t));
12606       finish_for_stmt (stmt);
12607       break;
12608
12609     case RANGE_FOR_STMT:
12610       {
12611         tree decl, expr;
12612         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12613         decl = RANGE_FOR_DECL (t);
12614         decl = tsubst (decl, args, complain, in_decl);
12615         maybe_push_decl (decl);
12616         expr = RECUR (RANGE_FOR_EXPR (t));
12617         stmt = cp_convert_range_for (stmt, decl, expr);
12618         RECUR (RANGE_FOR_BODY (t));
12619         finish_for_stmt (stmt);
12620       }
12621       break;
12622
12623     case WHILE_STMT:
12624       stmt = begin_while_stmt ();
12625       tmp = RECUR (WHILE_COND (t));
12626       finish_while_stmt_cond (tmp, stmt);
12627       RECUR (WHILE_BODY (t));
12628       finish_while_stmt (stmt);
12629       break;
12630
12631     case DO_STMT:
12632       stmt = begin_do_stmt ();
12633       RECUR (DO_BODY (t));
12634       finish_do_body (stmt);
12635       tmp = RECUR (DO_COND (t));
12636       finish_do_stmt (tmp, stmt);
12637       break;
12638
12639     case IF_STMT:
12640       stmt = begin_if_stmt ();
12641       tmp = RECUR (IF_COND (t));
12642       finish_if_stmt_cond (tmp, stmt);
12643       RECUR (THEN_CLAUSE (t));
12644       finish_then_clause (stmt);
12645
12646       if (ELSE_CLAUSE (t))
12647         {
12648           begin_else_clause (stmt);
12649           RECUR (ELSE_CLAUSE (t));
12650           finish_else_clause (stmt);
12651         }
12652
12653       finish_if_stmt (stmt);
12654       break;
12655
12656     case BIND_EXPR:
12657       if (BIND_EXPR_BODY_BLOCK (t))
12658         stmt = begin_function_body ();
12659       else
12660         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12661                                     ? BCS_TRY_BLOCK : 0);
12662
12663       RECUR (BIND_EXPR_BODY (t));
12664
12665       if (BIND_EXPR_BODY_BLOCK (t))
12666         finish_function_body (stmt);
12667       else
12668         finish_compound_stmt (stmt);
12669       break;
12670
12671     case BREAK_STMT:
12672       finish_break_stmt ();
12673       break;
12674
12675     case CONTINUE_STMT:
12676       finish_continue_stmt ();
12677       break;
12678
12679     case SWITCH_STMT:
12680       stmt = begin_switch_stmt ();
12681       tmp = RECUR (SWITCH_STMT_COND (t));
12682       finish_switch_cond (tmp, stmt);
12683       RECUR (SWITCH_STMT_BODY (t));
12684       finish_switch_stmt (stmt);
12685       break;
12686
12687     case CASE_LABEL_EXPR:
12688       finish_case_label (EXPR_LOCATION (t),
12689                          RECUR (CASE_LOW (t)),
12690                          RECUR (CASE_HIGH (t)));
12691       break;
12692
12693     case LABEL_EXPR:
12694       {
12695         tree decl = LABEL_EXPR_LABEL (t);
12696         tree label;
12697
12698         label = finish_label_stmt (DECL_NAME (decl));
12699         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12700           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12701       }
12702       break;
12703
12704     case GOTO_EXPR:
12705       tmp = GOTO_DESTINATION (t);
12706       if (TREE_CODE (tmp) != LABEL_DECL)
12707         /* Computed goto's must be tsubst'd into.  On the other hand,
12708            non-computed gotos must not be; the identifier in question
12709            will have no binding.  */
12710         tmp = RECUR (tmp);
12711       else
12712         tmp = DECL_NAME (tmp);
12713       finish_goto_stmt (tmp);
12714       break;
12715
12716     case ASM_EXPR:
12717       tmp = finish_asm_stmt
12718         (ASM_VOLATILE_P (t),
12719          RECUR (ASM_STRING (t)),
12720          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12721          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12722          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12723          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12724       {
12725         tree asm_expr = tmp;
12726         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12727           asm_expr = TREE_OPERAND (asm_expr, 0);
12728         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12729       }
12730       break;
12731
12732     case TRY_BLOCK:
12733       if (CLEANUP_P (t))
12734         {
12735           stmt = begin_try_block ();
12736           RECUR (TRY_STMTS (t));
12737           finish_cleanup_try_block (stmt);
12738           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12739         }
12740       else
12741         {
12742           tree compound_stmt = NULL_TREE;
12743
12744           if (FN_TRY_BLOCK_P (t))
12745             stmt = begin_function_try_block (&compound_stmt);
12746           else
12747             stmt = begin_try_block ();
12748
12749           RECUR (TRY_STMTS (t));
12750
12751           if (FN_TRY_BLOCK_P (t))
12752             finish_function_try_block (stmt);
12753           else
12754             finish_try_block (stmt);
12755
12756           RECUR (TRY_HANDLERS (t));
12757           if (FN_TRY_BLOCK_P (t))
12758             finish_function_handler_sequence (stmt, compound_stmt);
12759           else
12760             finish_handler_sequence (stmt);
12761         }
12762       break;
12763
12764     case HANDLER:
12765       {
12766         tree decl = HANDLER_PARMS (t);
12767
12768         if (decl)
12769           {
12770             decl = tsubst (decl, args, complain, in_decl);
12771             /* Prevent instantiate_decl from trying to instantiate
12772                this variable.  We've already done all that needs to be
12773                done.  */
12774             if (decl != error_mark_node)
12775               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12776           }
12777         stmt = begin_handler ();
12778         finish_handler_parms (decl, stmt);
12779         RECUR (HANDLER_BODY (t));
12780         finish_handler (stmt);
12781       }
12782       break;
12783
12784     case TAG_DEFN:
12785       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12786       break;
12787
12788     case STATIC_ASSERT:
12789       {
12790         tree condition = 
12791           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12792                        args,
12793                        complain, in_decl,
12794                        /*integral_constant_expression_p=*/true);
12795         finish_static_assert (condition,
12796                               STATIC_ASSERT_MESSAGE (t),
12797                               STATIC_ASSERT_SOURCE_LOCATION (t),
12798                               /*member_p=*/false);
12799       }
12800       break;
12801
12802     case OMP_PARALLEL:
12803       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12804                                 args, complain, in_decl);
12805       stmt = begin_omp_parallel ();
12806       RECUR (OMP_PARALLEL_BODY (t));
12807       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12808         = OMP_PARALLEL_COMBINED (t);
12809       break;
12810
12811     case OMP_TASK:
12812       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12813                                 args, complain, in_decl);
12814       stmt = begin_omp_task ();
12815       RECUR (OMP_TASK_BODY (t));
12816       finish_omp_task (tmp, stmt);
12817       break;
12818
12819     case OMP_FOR:
12820       {
12821         tree clauses, body, pre_body;
12822         tree declv, initv, condv, incrv;
12823         int i;
12824
12825         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12826                                       args, complain, in_decl);
12827         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12828         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12829         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12830         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12831
12832         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12833           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12834                                    &clauses, args, complain, in_decl,
12835                                    integral_constant_expression_p);
12836
12837         stmt = begin_omp_structured_block ();
12838
12839         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12840           if (TREE_VEC_ELT (initv, i) == NULL
12841               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12842             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12843           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12844             {
12845               tree init = RECUR (TREE_VEC_ELT (initv, i));
12846               gcc_assert (init == TREE_VEC_ELT (declv, i));
12847               TREE_VEC_ELT (initv, i) = NULL_TREE;
12848             }
12849           else
12850             {
12851               tree decl_expr = TREE_VEC_ELT (initv, i);
12852               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12853               gcc_assert (init != NULL);
12854               TREE_VEC_ELT (initv, i) = RECUR (init);
12855               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12856               RECUR (decl_expr);
12857               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12858             }
12859
12860         pre_body = push_stmt_list ();
12861         RECUR (OMP_FOR_PRE_BODY (t));
12862         pre_body = pop_stmt_list (pre_body);
12863
12864         body = push_stmt_list ();
12865         RECUR (OMP_FOR_BODY (t));
12866         body = pop_stmt_list (body);
12867
12868         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12869                             body, pre_body, clauses);
12870
12871         add_stmt (finish_omp_structured_block (stmt));
12872       }
12873       break;
12874
12875     case OMP_SECTIONS:
12876     case OMP_SINGLE:
12877       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12878       stmt = push_stmt_list ();
12879       RECUR (OMP_BODY (t));
12880       stmt = pop_stmt_list (stmt);
12881
12882       t = copy_node (t);
12883       OMP_BODY (t) = stmt;
12884       OMP_CLAUSES (t) = tmp;
12885       add_stmt (t);
12886       break;
12887
12888     case OMP_SECTION:
12889     case OMP_CRITICAL:
12890     case OMP_MASTER:
12891     case OMP_ORDERED:
12892       stmt = push_stmt_list ();
12893       RECUR (OMP_BODY (t));
12894       stmt = pop_stmt_list (stmt);
12895
12896       t = copy_node (t);
12897       OMP_BODY (t) = stmt;
12898       add_stmt (t);
12899       break;
12900
12901     case OMP_ATOMIC:
12902       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12903       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12904         {
12905           tree op1 = TREE_OPERAND (t, 1);
12906           tree rhs1 = NULL_TREE;
12907           tree lhs, rhs;
12908           if (TREE_CODE (op1) == COMPOUND_EXPR)
12909             {
12910               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12911               op1 = TREE_OPERAND (op1, 1);
12912             }
12913           lhs = RECUR (TREE_OPERAND (op1, 0));
12914           rhs = RECUR (TREE_OPERAND (op1, 1));
12915           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12916                              NULL_TREE, NULL_TREE, rhs1);
12917         }
12918       else
12919         {
12920           tree op1 = TREE_OPERAND (t, 1);
12921           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12922           tree rhs1 = NULL_TREE;
12923           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12924           enum tree_code opcode = NOP_EXPR;
12925           if (code == OMP_ATOMIC_READ)
12926             {
12927               v = RECUR (TREE_OPERAND (op1, 0));
12928               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12929             }
12930           else if (code == OMP_ATOMIC_CAPTURE_OLD
12931                    || code == OMP_ATOMIC_CAPTURE_NEW)
12932             {
12933               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12934               v = RECUR (TREE_OPERAND (op1, 0));
12935               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12936               if (TREE_CODE (op11) == COMPOUND_EXPR)
12937                 {
12938                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12939                   op11 = TREE_OPERAND (op11, 1);
12940                 }
12941               lhs = RECUR (TREE_OPERAND (op11, 0));
12942               rhs = RECUR (TREE_OPERAND (op11, 1));
12943               opcode = TREE_CODE (op11);
12944             }
12945           else
12946             {
12947               code = OMP_ATOMIC;
12948               lhs = RECUR (TREE_OPERAND (op1, 0));
12949               rhs = RECUR (TREE_OPERAND (op1, 1));
12950             }
12951           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12952         }
12953       break;
12954
12955     case EXPR_PACK_EXPANSION:
12956       error ("invalid use of pack expansion expression");
12957       return error_mark_node;
12958
12959     case NONTYPE_ARGUMENT_PACK:
12960       error ("use %<...%> to expand argument pack");
12961       return error_mark_node;
12962
12963     default:
12964       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12965
12966       return tsubst_copy_and_build (t, args, complain, in_decl,
12967                                     /*function_p=*/false,
12968                                     integral_constant_expression_p);
12969     }
12970
12971   return NULL_TREE;
12972 #undef RECUR
12973 }
12974
12975 /* T is a postfix-expression that is not being used in a function
12976    call.  Return the substituted version of T.  */
12977
12978 static tree
12979 tsubst_non_call_postfix_expression (tree t, tree args,
12980                                     tsubst_flags_t complain,
12981                                     tree in_decl)
12982 {
12983   if (TREE_CODE (t) == SCOPE_REF)
12984     t = tsubst_qualified_id (t, args, complain, in_decl,
12985                              /*done=*/false, /*address_p=*/false);
12986   else
12987     t = tsubst_copy_and_build (t, args, complain, in_decl,
12988                                /*function_p=*/false,
12989                                /*integral_constant_expression_p=*/false);
12990
12991   return t;
12992 }
12993
12994 /* Like tsubst but deals with expressions and performs semantic
12995    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12996
12997 tree
12998 tsubst_copy_and_build (tree t,
12999                        tree args,
13000                        tsubst_flags_t complain,
13001                        tree in_decl,
13002                        bool function_p,
13003                        bool integral_constant_expression_p)
13004 {
13005 #define RECUR(NODE)                                             \
13006   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
13007                          /*function_p=*/false,                  \
13008                          integral_constant_expression_p)
13009
13010   tree op1;
13011
13012   if (t == NULL_TREE || t == error_mark_node)
13013     return t;
13014
13015   switch (TREE_CODE (t))
13016     {
13017     case USING_DECL:
13018       t = DECL_NAME (t);
13019       /* Fall through.  */
13020     case IDENTIFIER_NODE:
13021       {
13022         tree decl;
13023         cp_id_kind idk;
13024         bool non_integral_constant_expression_p;
13025         const char *error_msg;
13026
13027         if (IDENTIFIER_TYPENAME_P (t))
13028           {
13029             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13030             t = mangle_conv_op_name_for_type (new_type);
13031           }
13032
13033         /* Look up the name.  */
13034         decl = lookup_name (t);
13035
13036         /* By convention, expressions use ERROR_MARK_NODE to indicate
13037            failure, not NULL_TREE.  */
13038         if (decl == NULL_TREE)
13039           decl = error_mark_node;
13040
13041         decl = finish_id_expression (t, decl, NULL_TREE,
13042                                      &idk,
13043                                      integral_constant_expression_p,
13044                                      /*allow_non_integral_constant_expression_p=*/false,
13045                                      &non_integral_constant_expression_p,
13046                                      /*template_p=*/false,
13047                                      /*done=*/true,
13048                                      /*address_p=*/false,
13049                                      /*template_arg_p=*/false,
13050                                      &error_msg,
13051                                      input_location);
13052         if (error_msg)
13053           error (error_msg);
13054         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13055           {
13056             if (complain & tf_error)
13057               unqualified_name_lookup_error (decl);
13058             decl = error_mark_node;
13059           }
13060         return decl;
13061       }
13062
13063     case TEMPLATE_ID_EXPR:
13064       {
13065         tree object;
13066         tree templ = RECUR (TREE_OPERAND (t, 0));
13067         tree targs = TREE_OPERAND (t, 1);
13068
13069         if (targs)
13070           targs = tsubst_template_args (targs, args, complain, in_decl);
13071
13072         if (TREE_CODE (templ) == COMPONENT_REF)
13073           {
13074             object = TREE_OPERAND (templ, 0);
13075             templ = TREE_OPERAND (templ, 1);
13076           }
13077         else
13078           object = NULL_TREE;
13079         templ = lookup_template_function (templ, targs);
13080
13081         if (object)
13082           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13083                          object, templ, NULL_TREE);
13084         else
13085           return baselink_for_fns (templ);
13086       }
13087
13088     case INDIRECT_REF:
13089       {
13090         tree r = RECUR (TREE_OPERAND (t, 0));
13091
13092         if (REFERENCE_REF_P (t))
13093           {
13094             /* A type conversion to reference type will be enclosed in
13095                such an indirect ref, but the substitution of the cast
13096                will have also added such an indirect ref.  */
13097             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13098               r = convert_from_reference (r);
13099           }
13100         else
13101           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13102         return r;
13103       }
13104
13105     case NOP_EXPR:
13106       return build_nop
13107         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13108          RECUR (TREE_OPERAND (t, 0)));
13109
13110     case IMPLICIT_CONV_EXPR:
13111       {
13112         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13113         tree expr = RECUR (TREE_OPERAND (t, 0));
13114         int flags = LOOKUP_IMPLICIT;
13115         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13116           flags = LOOKUP_NORMAL;
13117         return perform_implicit_conversion_flags (type, expr, complain,
13118                                                   flags);
13119       }
13120
13121     case CONVERT_EXPR:
13122       return build1
13123         (CONVERT_EXPR,
13124          tsubst (TREE_TYPE (t), args, complain, in_decl),
13125          RECUR (TREE_OPERAND (t, 0)));
13126
13127     case CAST_EXPR:
13128     case REINTERPRET_CAST_EXPR:
13129     case CONST_CAST_EXPR:
13130     case DYNAMIC_CAST_EXPR:
13131     case STATIC_CAST_EXPR:
13132       {
13133         tree type;
13134         tree op;
13135
13136         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13137         if (integral_constant_expression_p
13138             && !cast_valid_in_integral_constant_expression_p (type))
13139           {
13140             if (complain & tf_error)
13141               error ("a cast to a type other than an integral or "
13142                      "enumeration type cannot appear in a constant-expression");
13143             return error_mark_node; 
13144           }
13145
13146         op = RECUR (TREE_OPERAND (t, 0));
13147
13148         switch (TREE_CODE (t))
13149           {
13150           case CAST_EXPR:
13151             return build_functional_cast (type, op, complain);
13152           case REINTERPRET_CAST_EXPR:
13153             return build_reinterpret_cast (type, op, complain);
13154           case CONST_CAST_EXPR:
13155             return build_const_cast (type, op, complain);
13156           case DYNAMIC_CAST_EXPR:
13157             return build_dynamic_cast (type, op, complain);
13158           case STATIC_CAST_EXPR:
13159             return build_static_cast (type, op, complain);
13160           default:
13161             gcc_unreachable ();
13162           }
13163       }
13164
13165     case POSTDECREMENT_EXPR:
13166     case POSTINCREMENT_EXPR:
13167       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13168                                                 args, complain, in_decl);
13169       return build_x_unary_op (TREE_CODE (t), op1, complain);
13170
13171     case PREDECREMENT_EXPR:
13172     case PREINCREMENT_EXPR:
13173     case NEGATE_EXPR:
13174     case BIT_NOT_EXPR:
13175     case ABS_EXPR:
13176     case TRUTH_NOT_EXPR:
13177     case UNARY_PLUS_EXPR:  /* Unary + */
13178     case REALPART_EXPR:
13179     case IMAGPART_EXPR:
13180       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13181                                complain);
13182
13183     case ADDR_EXPR:
13184       op1 = TREE_OPERAND (t, 0);
13185       if (TREE_CODE (op1) == LABEL_DECL)
13186         return finish_label_address_expr (DECL_NAME (op1),
13187                                           EXPR_LOCATION (op1));
13188       if (TREE_CODE (op1) == SCOPE_REF)
13189         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13190                                    /*done=*/true, /*address_p=*/true);
13191       else
13192         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13193                                                   in_decl);
13194       return build_x_unary_op (ADDR_EXPR, op1, complain);
13195
13196     case PLUS_EXPR:
13197     case MINUS_EXPR:
13198     case MULT_EXPR:
13199     case TRUNC_DIV_EXPR:
13200     case CEIL_DIV_EXPR:
13201     case FLOOR_DIV_EXPR:
13202     case ROUND_DIV_EXPR:
13203     case EXACT_DIV_EXPR:
13204     case BIT_AND_EXPR:
13205     case BIT_IOR_EXPR:
13206     case BIT_XOR_EXPR:
13207     case TRUNC_MOD_EXPR:
13208     case FLOOR_MOD_EXPR:
13209     case TRUTH_ANDIF_EXPR:
13210     case TRUTH_ORIF_EXPR:
13211     case TRUTH_AND_EXPR:
13212     case TRUTH_OR_EXPR:
13213     case RSHIFT_EXPR:
13214     case LSHIFT_EXPR:
13215     case RROTATE_EXPR:
13216     case LROTATE_EXPR:
13217     case EQ_EXPR:
13218     case NE_EXPR:
13219     case MAX_EXPR:
13220     case MIN_EXPR:
13221     case LE_EXPR:
13222     case GE_EXPR:
13223     case LT_EXPR:
13224     case GT_EXPR:
13225     case MEMBER_REF:
13226     case DOTSTAR_EXPR:
13227       return build_x_binary_op
13228         (TREE_CODE (t),
13229          RECUR (TREE_OPERAND (t, 0)),
13230          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13231           ? ERROR_MARK
13232           : TREE_CODE (TREE_OPERAND (t, 0))),
13233          RECUR (TREE_OPERAND (t, 1)),
13234          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13235           ? ERROR_MARK
13236           : TREE_CODE (TREE_OPERAND (t, 1))),
13237          /*overload=*/NULL,
13238          complain);
13239
13240     case SCOPE_REF:
13241       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13242                                   /*address_p=*/false);
13243     case ARRAY_REF:
13244       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13245                                                 args, complain, in_decl);
13246       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13247
13248     case SIZEOF_EXPR:
13249       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13250         return tsubst_copy (t, args, complain, in_decl);
13251       /* Fall through */
13252       
13253     case ALIGNOF_EXPR:
13254       op1 = TREE_OPERAND (t, 0);
13255       if (!args)
13256         {
13257           /* When there are no ARGS, we are trying to evaluate a
13258              non-dependent expression from the parser.  Trying to do
13259              the substitutions may not work.  */
13260           if (!TYPE_P (op1))
13261             op1 = TREE_TYPE (op1);
13262         }
13263       else
13264         {
13265           ++cp_unevaluated_operand;
13266           ++c_inhibit_evaluation_warnings;
13267           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13268                                        /*function_p=*/false,
13269                                        /*integral_constant_expression_p=*/false);
13270           --cp_unevaluated_operand;
13271           --c_inhibit_evaluation_warnings;
13272         }
13273       if (TYPE_P (op1))
13274         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13275                                            complain & tf_error);
13276       else
13277         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13278                                            complain & tf_error);
13279
13280     case AT_ENCODE_EXPR:
13281       {
13282         op1 = TREE_OPERAND (t, 0);
13283         ++cp_unevaluated_operand;
13284         ++c_inhibit_evaluation_warnings;
13285         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13286                                      /*function_p=*/false,
13287                                      /*integral_constant_expression_p=*/false);
13288         --cp_unevaluated_operand;
13289         --c_inhibit_evaluation_warnings;
13290         return objc_build_encode_expr (op1);
13291       }
13292
13293     case NOEXCEPT_EXPR:
13294       op1 = TREE_OPERAND (t, 0);
13295       ++cp_unevaluated_operand;
13296       ++c_inhibit_evaluation_warnings;
13297       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13298                                    /*function_p=*/false,
13299                                    /*integral_constant_expression_p=*/false);
13300       --cp_unevaluated_operand;
13301       --c_inhibit_evaluation_warnings;
13302       return finish_noexcept_expr (op1, complain);
13303
13304     case MODOP_EXPR:
13305       {
13306         tree r = build_x_modify_expr
13307           (RECUR (TREE_OPERAND (t, 0)),
13308            TREE_CODE (TREE_OPERAND (t, 1)),
13309            RECUR (TREE_OPERAND (t, 2)),
13310            complain);
13311         /* TREE_NO_WARNING must be set if either the expression was
13312            parenthesized or it uses an operator such as >>= rather
13313            than plain assignment.  In the former case, it was already
13314            set and must be copied.  In the latter case,
13315            build_x_modify_expr sets it and it must not be reset
13316            here.  */
13317         if (TREE_NO_WARNING (t))
13318           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13319         return r;
13320       }
13321
13322     case ARROW_EXPR:
13323       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13324                                                 args, complain, in_decl);
13325       /* Remember that there was a reference to this entity.  */
13326       if (DECL_P (op1))
13327         mark_used (op1);
13328       return build_x_arrow (op1);
13329
13330     case NEW_EXPR:
13331       {
13332         tree placement = RECUR (TREE_OPERAND (t, 0));
13333         tree init = RECUR (TREE_OPERAND (t, 3));
13334         VEC(tree,gc) *placement_vec;
13335         VEC(tree,gc) *init_vec;
13336         tree ret;
13337
13338         if (placement == NULL_TREE)
13339           placement_vec = NULL;
13340         else
13341           {
13342             placement_vec = make_tree_vector ();
13343             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13344               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13345           }
13346
13347         /* If there was an initializer in the original tree, but it
13348            instantiated to an empty list, then we should pass a
13349            non-NULL empty vector to tell build_new that it was an
13350            empty initializer() rather than no initializer.  This can
13351            only happen when the initializer is a pack expansion whose
13352            parameter packs are of length zero.  */
13353         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13354           init_vec = NULL;
13355         else
13356           {
13357             init_vec = make_tree_vector ();
13358             if (init == void_zero_node)
13359               gcc_assert (init_vec != NULL);
13360             else
13361               {
13362                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13363                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13364               }
13365           }
13366
13367         ret = build_new (&placement_vec,
13368                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13369                          RECUR (TREE_OPERAND (t, 2)),
13370                          &init_vec,
13371                          NEW_EXPR_USE_GLOBAL (t),
13372                          complain);
13373
13374         if (placement_vec != NULL)
13375           release_tree_vector (placement_vec);
13376         if (init_vec != NULL)
13377           release_tree_vector (init_vec);
13378
13379         return ret;
13380       }
13381
13382     case DELETE_EXPR:
13383      return delete_sanity
13384        (RECUR (TREE_OPERAND (t, 0)),
13385         RECUR (TREE_OPERAND (t, 1)),
13386         DELETE_EXPR_USE_VEC (t),
13387         DELETE_EXPR_USE_GLOBAL (t),
13388         complain);
13389
13390     case COMPOUND_EXPR:
13391       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13392                                     RECUR (TREE_OPERAND (t, 1)),
13393                                     complain);
13394
13395     case CALL_EXPR:
13396       {
13397         tree function;
13398         VEC(tree,gc) *call_args;
13399         unsigned int nargs, i;
13400         bool qualified_p;
13401         bool koenig_p;
13402         tree ret;
13403
13404         function = CALL_EXPR_FN (t);
13405         /* When we parsed the expression,  we determined whether or
13406            not Koenig lookup should be performed.  */
13407         koenig_p = KOENIG_LOOKUP_P (t);
13408         if (TREE_CODE (function) == SCOPE_REF)
13409           {
13410             qualified_p = true;
13411             function = tsubst_qualified_id (function, args, complain, in_decl,
13412                                             /*done=*/false,
13413                                             /*address_p=*/false);
13414           }
13415         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13416           {
13417             /* Do nothing; calling tsubst_copy_and_build on an identifier
13418                would incorrectly perform unqualified lookup again.
13419
13420                Note that we can also have an IDENTIFIER_NODE if the earlier
13421                unqualified lookup found a member function; in that case
13422                koenig_p will be false and we do want to do the lookup
13423                again to find the instantiated member function.
13424
13425                FIXME but doing that causes c++/15272, so we need to stop
13426                using IDENTIFIER_NODE in that situation.  */
13427             qualified_p = false;
13428           }
13429         else
13430           {
13431             if (TREE_CODE (function) == COMPONENT_REF)
13432               {
13433                 tree op = TREE_OPERAND (function, 1);
13434
13435                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13436                                || (BASELINK_P (op)
13437                                    && BASELINK_QUALIFIED_P (op)));
13438               }
13439             else
13440               qualified_p = false;
13441
13442             function = tsubst_copy_and_build (function, args, complain,
13443                                               in_decl,
13444                                               !qualified_p,
13445                                               integral_constant_expression_p);
13446
13447             if (BASELINK_P (function))
13448               qualified_p = true;
13449           }
13450
13451         nargs = call_expr_nargs (t);
13452         call_args = make_tree_vector ();
13453         for (i = 0; i < nargs; ++i)
13454           {
13455             tree arg = CALL_EXPR_ARG (t, i);
13456
13457             if (!PACK_EXPANSION_P (arg))
13458               VEC_safe_push (tree, gc, call_args,
13459                              RECUR (CALL_EXPR_ARG (t, i)));
13460             else
13461               {
13462                 /* Expand the pack expansion and push each entry onto
13463                    CALL_ARGS.  */
13464                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13465                 if (TREE_CODE (arg) == TREE_VEC)
13466                   {
13467                     unsigned int len, j;
13468
13469                     len = TREE_VEC_LENGTH (arg);
13470                     for (j = 0; j < len; ++j)
13471                       {
13472                         tree value = TREE_VEC_ELT (arg, j);
13473                         if (value != NULL_TREE)
13474                           value = convert_from_reference (value);
13475                         VEC_safe_push (tree, gc, call_args, value);
13476                       }
13477                   }
13478                 else
13479                   {
13480                     /* A partial substitution.  Add one entry.  */
13481                     VEC_safe_push (tree, gc, call_args, arg);
13482                   }
13483               }
13484           }
13485
13486         /* We do not perform argument-dependent lookup if normal
13487            lookup finds a non-function, in accordance with the
13488            expected resolution of DR 218.  */
13489         if (koenig_p
13490             && ((is_overloaded_fn (function)
13491                  /* If lookup found a member function, the Koenig lookup is
13492                     not appropriate, even if an unqualified-name was used
13493                     to denote the function.  */
13494                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13495                 || TREE_CODE (function) == IDENTIFIER_NODE)
13496             /* Only do this when substitution turns a dependent call
13497                into a non-dependent call.  */
13498             && type_dependent_expression_p_push (t)
13499             && !any_type_dependent_arguments_p (call_args))
13500           function = perform_koenig_lookup (function, call_args, false,
13501                                             tf_none);
13502
13503         if (TREE_CODE (function) == IDENTIFIER_NODE
13504             && !any_type_dependent_arguments_p (call_args))
13505           {
13506             if (koenig_p && (complain & tf_warning_or_error))
13507               {
13508                 /* For backwards compatibility and good diagnostics, try
13509                    the unqualified lookup again if we aren't in SFINAE
13510                    context.  */
13511                 tree unq = (tsubst_copy_and_build
13512                             (function, args, complain, in_decl, true,
13513                              integral_constant_expression_p));
13514                 if (unq == error_mark_node)
13515                   return error_mark_node;
13516
13517                 if (unq != function)
13518                   {
13519                     tree fn = unq;
13520                     if (TREE_CODE (fn) == COMPONENT_REF)
13521                       fn = TREE_OPERAND (fn, 1);
13522                     if (is_overloaded_fn (fn))
13523                       fn = get_first_fn (fn);
13524                     permerror (EXPR_LOC_OR_HERE (t),
13525                                "%qD was not declared in this scope, "
13526                                "and no declarations were found by "
13527                                "argument-dependent lookup at the point "
13528                                "of instantiation", function);
13529                     if (DECL_CLASS_SCOPE_P (fn))
13530                       {
13531                         inform (EXPR_LOC_OR_HERE (t),
13532                                 "declarations in dependent base %qT are "
13533                                 "not found by unqualified lookup",
13534                                 DECL_CLASS_CONTEXT (fn));
13535                         if (current_class_ptr)
13536                           inform (EXPR_LOC_OR_HERE (t),
13537                                   "use %<this->%D%> instead", function);
13538                         else
13539                           inform (EXPR_LOC_OR_HERE (t),
13540                                   "use %<%T::%D%> instead",
13541                                   current_class_name, function);
13542                       }
13543                     else
13544                       inform (0, "%q+D declared here, later in the "
13545                                 "translation unit", fn);
13546                     function = unq;
13547                   }
13548               }
13549             if (TREE_CODE (function) == IDENTIFIER_NODE)
13550               {
13551                 unqualified_name_lookup_error (function);
13552                 release_tree_vector (call_args);
13553                 return error_mark_node;
13554               }
13555           }
13556
13557         /* Remember that there was a reference to this entity.  */
13558         if (DECL_P (function))
13559           mark_used (function);
13560
13561         if (TREE_CODE (function) == OFFSET_REF)
13562           ret = build_offset_ref_call_from_tree (function, &call_args);
13563         else if (TREE_CODE (function) == COMPONENT_REF)
13564           {
13565             tree instance = TREE_OPERAND (function, 0);
13566             tree fn = TREE_OPERAND (function, 1);
13567
13568             if (processing_template_decl
13569                 && (type_dependent_expression_p (instance)
13570                     || (!BASELINK_P (fn)
13571                         && TREE_CODE (fn) != FIELD_DECL)
13572                     || type_dependent_expression_p (fn)
13573                     || any_type_dependent_arguments_p (call_args)))
13574               ret = build_nt_call_vec (function, call_args);
13575             else if (!BASELINK_P (fn))
13576               ret = finish_call_expr (function, &call_args,
13577                                        /*disallow_virtual=*/false,
13578                                        /*koenig_p=*/false,
13579                                        complain);
13580             else
13581               ret = (build_new_method_call
13582                       (instance, fn,
13583                        &call_args, NULL_TREE,
13584                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13585                        /*fn_p=*/NULL,
13586                        complain));
13587           }
13588         else
13589           ret = finish_call_expr (function, &call_args,
13590                                   /*disallow_virtual=*/qualified_p,
13591                                   koenig_p,
13592                                   complain);
13593
13594         release_tree_vector (call_args);
13595
13596         return ret;
13597       }
13598
13599     case COND_EXPR:
13600       return build_x_conditional_expr
13601         (RECUR (TREE_OPERAND (t, 0)),
13602          RECUR (TREE_OPERAND (t, 1)),
13603          RECUR (TREE_OPERAND (t, 2)),
13604          complain);
13605
13606     case PSEUDO_DTOR_EXPR:
13607       return finish_pseudo_destructor_expr
13608         (RECUR (TREE_OPERAND (t, 0)),
13609          RECUR (TREE_OPERAND (t, 1)),
13610          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13611
13612     case TREE_LIST:
13613       {
13614         tree purpose, value, chain;
13615
13616         if (t == void_list_node)
13617           return t;
13618
13619         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13620             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13621           {
13622             /* We have pack expansions, so expand those and
13623                create a new list out of it.  */
13624             tree purposevec = NULL_TREE;
13625             tree valuevec = NULL_TREE;
13626             tree chain;
13627             int i, len = -1;
13628
13629             /* Expand the argument expressions.  */
13630             if (TREE_PURPOSE (t))
13631               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13632                                                  complain, in_decl);
13633             if (TREE_VALUE (t))
13634               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13635                                                complain, in_decl);
13636
13637             /* Build the rest of the list.  */
13638             chain = TREE_CHAIN (t);
13639             if (chain && chain != void_type_node)
13640               chain = RECUR (chain);
13641
13642             /* Determine the number of arguments.  */
13643             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13644               {
13645                 len = TREE_VEC_LENGTH (purposevec);
13646                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13647               }
13648             else if (TREE_CODE (valuevec) == TREE_VEC)
13649               len = TREE_VEC_LENGTH (valuevec);
13650             else
13651               {
13652                 /* Since we only performed a partial substitution into
13653                    the argument pack, we only return a single list
13654                    node.  */
13655                 if (purposevec == TREE_PURPOSE (t)
13656                     && valuevec == TREE_VALUE (t)
13657                     && chain == TREE_CHAIN (t))
13658                   return t;
13659
13660                 return tree_cons (purposevec, valuevec, chain);
13661               }
13662             
13663             /* Convert the argument vectors into a TREE_LIST */
13664             i = len;
13665             while (i > 0)
13666               {
13667                 /* Grab the Ith values.  */
13668                 i--;
13669                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13670                                      : NULL_TREE;
13671                 value 
13672                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13673                              : NULL_TREE;
13674
13675                 /* Build the list (backwards).  */
13676                 chain = tree_cons (purpose, value, chain);
13677               }
13678
13679             return chain;
13680           }
13681
13682         purpose = TREE_PURPOSE (t);
13683         if (purpose)
13684           purpose = RECUR (purpose);
13685         value = TREE_VALUE (t);
13686         if (value)
13687           value = RECUR (value);
13688         chain = TREE_CHAIN (t);
13689         if (chain && chain != void_type_node)
13690           chain = RECUR (chain);
13691         if (purpose == TREE_PURPOSE (t)
13692             && value == TREE_VALUE (t)
13693             && chain == TREE_CHAIN (t))
13694           return t;
13695         return tree_cons (purpose, value, chain);
13696       }
13697
13698     case COMPONENT_REF:
13699       {
13700         tree object;
13701         tree object_type;
13702         tree member;
13703
13704         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13705                                                      args, complain, in_decl);
13706         /* Remember that there was a reference to this entity.  */
13707         if (DECL_P (object))
13708           mark_used (object);
13709         object_type = TREE_TYPE (object);
13710
13711         member = TREE_OPERAND (t, 1);
13712         if (BASELINK_P (member))
13713           member = tsubst_baselink (member,
13714                                     non_reference (TREE_TYPE (object)),
13715                                     args, complain, in_decl);
13716         else
13717           member = tsubst_copy (member, args, complain, in_decl);
13718         if (member == error_mark_node)
13719           return error_mark_node;
13720
13721         if (object_type && !CLASS_TYPE_P (object_type))
13722           {
13723             if (SCALAR_TYPE_P (object_type))
13724               {
13725                 tree s = NULL_TREE;
13726                 tree dtor = member;
13727
13728                 if (TREE_CODE (dtor) == SCOPE_REF)
13729                   {
13730                     s = TREE_OPERAND (dtor, 0);
13731                     dtor = TREE_OPERAND (dtor, 1);
13732                   }
13733                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13734                   {
13735                     dtor = TREE_OPERAND (dtor, 0);
13736                     if (TYPE_P (dtor))
13737                       return finish_pseudo_destructor_expr (object, s, dtor);
13738                   }
13739               }
13740           }
13741         else if (TREE_CODE (member) == SCOPE_REF
13742                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13743           {
13744             /* Lookup the template functions now that we know what the
13745                scope is.  */
13746             tree scope = TREE_OPERAND (member, 0);
13747             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13748             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13749             member = lookup_qualified_name (scope, tmpl,
13750                                             /*is_type_p=*/false,
13751                                             /*complain=*/false);
13752             if (BASELINK_P (member))
13753               {
13754                 BASELINK_FUNCTIONS (member)
13755                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13756                               args);
13757                 member = (adjust_result_of_qualified_name_lookup
13758                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13759                            object_type));
13760               }
13761             else
13762               {
13763                 qualified_name_lookup_error (scope, tmpl, member,
13764                                              input_location);
13765                 return error_mark_node;
13766               }
13767           }
13768         else if (TREE_CODE (member) == SCOPE_REF
13769                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13770                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13771           {
13772             if (complain & tf_error)
13773               {
13774                 if (TYPE_P (TREE_OPERAND (member, 0)))
13775                   error ("%qT is not a class or namespace",
13776                          TREE_OPERAND (member, 0));
13777                 else
13778                   error ("%qD is not a class or namespace",
13779                          TREE_OPERAND (member, 0));
13780               }
13781             return error_mark_node;
13782           }
13783         else if (TREE_CODE (member) == FIELD_DECL)
13784           return finish_non_static_data_member (member, object, NULL_TREE);
13785
13786         return finish_class_member_access_expr (object, member,
13787                                                 /*template_p=*/false,
13788                                                 complain);
13789       }
13790
13791     case THROW_EXPR:
13792       return build_throw
13793         (RECUR (TREE_OPERAND (t, 0)));
13794
13795     case CONSTRUCTOR:
13796       {
13797         VEC(constructor_elt,gc) *n;
13798         constructor_elt *ce;
13799         unsigned HOST_WIDE_INT idx;
13800         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13801         bool process_index_p;
13802         int newlen;
13803         bool need_copy_p = false;
13804         tree r;
13805
13806         if (type == error_mark_node)
13807           return error_mark_node;
13808
13809         /* digest_init will do the wrong thing if we let it.  */
13810         if (type && TYPE_PTRMEMFUNC_P (type))
13811           return t;
13812
13813         /* We do not want to process the index of aggregate
13814            initializers as they are identifier nodes which will be
13815            looked up by digest_init.  */
13816         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13817
13818         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13819         newlen = VEC_length (constructor_elt, n);
13820         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13821           {
13822             if (ce->index && process_index_p)
13823               ce->index = RECUR (ce->index);
13824
13825             if (PACK_EXPANSION_P (ce->value))
13826               {
13827                 /* Substitute into the pack expansion.  */
13828                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13829                                                   in_decl);
13830
13831                 if (ce->value == error_mark_node
13832                     || PACK_EXPANSION_P (ce->value))
13833                   ;
13834                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13835                   /* Just move the argument into place.  */
13836                   ce->value = TREE_VEC_ELT (ce->value, 0);
13837                 else
13838                   {
13839                     /* Update the length of the final CONSTRUCTOR
13840                        arguments vector, and note that we will need to
13841                        copy.*/
13842                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13843                     need_copy_p = true;
13844                   }
13845               }
13846             else
13847               ce->value = RECUR (ce->value);
13848           }
13849
13850         if (need_copy_p)
13851           {
13852             VEC(constructor_elt,gc) *old_n = n;
13853
13854             n = VEC_alloc (constructor_elt, gc, newlen);
13855             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13856               {
13857                 if (TREE_CODE (ce->value) == TREE_VEC)
13858                   {
13859                     int i, len = TREE_VEC_LENGTH (ce->value);
13860                     for (i = 0; i < len; ++i)
13861                       CONSTRUCTOR_APPEND_ELT (n, 0,
13862                                               TREE_VEC_ELT (ce->value, i));
13863                   }
13864                 else
13865                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13866               }
13867           }
13868
13869         r = build_constructor (init_list_type_node, n);
13870         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13871
13872         if (TREE_HAS_CONSTRUCTOR (t))
13873           return finish_compound_literal (type, r, complain);
13874
13875         TREE_TYPE (r) = type;
13876         return r;
13877       }
13878
13879     case TYPEID_EXPR:
13880       {
13881         tree operand_0 = TREE_OPERAND (t, 0);
13882         if (TYPE_P (operand_0))
13883           {
13884             operand_0 = tsubst (operand_0, args, complain, in_decl);
13885             return get_typeid (operand_0);
13886           }
13887         else
13888           {
13889             operand_0 = RECUR (operand_0);
13890             return build_typeid (operand_0);
13891           }
13892       }
13893
13894     case VAR_DECL:
13895       if (!args)
13896         return t;
13897       /* Fall through */
13898
13899     case PARM_DECL:
13900       {
13901         tree r = tsubst_copy (t, args, complain, in_decl);
13902
13903         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13904           /* If the original type was a reference, we'll be wrapped in
13905              the appropriate INDIRECT_REF.  */
13906           r = convert_from_reference (r);
13907         return r;
13908       }
13909
13910     case VA_ARG_EXPR:
13911       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13912                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13913
13914     case OFFSETOF_EXPR:
13915       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13916
13917     case TRAIT_EXPR:
13918       {
13919         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13920                                   complain, in_decl);
13921
13922         tree type2 = TRAIT_EXPR_TYPE2 (t);
13923         if (type2)
13924           type2 = tsubst_copy (type2, args, complain, in_decl);
13925         
13926         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13927       }
13928
13929     case STMT_EXPR:
13930       {
13931         tree old_stmt_expr = cur_stmt_expr;
13932         tree stmt_expr = begin_stmt_expr ();
13933
13934         cur_stmt_expr = stmt_expr;
13935         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13936                      integral_constant_expression_p);
13937         stmt_expr = finish_stmt_expr (stmt_expr, false);
13938         cur_stmt_expr = old_stmt_expr;
13939
13940         /* If the resulting list of expression statement is empty,
13941            fold it further into void_zero_node.  */
13942         if (empty_expr_stmt_p (stmt_expr))
13943           stmt_expr = void_zero_node;
13944
13945         return stmt_expr;
13946       }
13947
13948     case CONST_DECL:
13949       t = tsubst_copy (t, args, complain, in_decl);
13950       /* As in finish_id_expression, we resolve enumeration constants
13951          to their underlying values.  */
13952       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
13953         {
13954           used_types_insert (TREE_TYPE (t));
13955           return DECL_INITIAL (t);
13956         }
13957       return t;
13958
13959     case LAMBDA_EXPR:
13960       {
13961         tree r = build_lambda_expr ();
13962
13963         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
13964         LAMBDA_EXPR_CLOSURE (r) = type;
13965         CLASSTYPE_LAMBDA_EXPR (type) = r;
13966
13967         LAMBDA_EXPR_LOCATION (r)
13968           = LAMBDA_EXPR_LOCATION (t);
13969         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13970           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13971         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13972         LAMBDA_EXPR_DISCRIMINATOR (r)
13973           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13974         LAMBDA_EXPR_EXTRA_SCOPE (r)
13975           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13976         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
13977           {
13978             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
13979             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
13980           }
13981         else
13982           LAMBDA_EXPR_RETURN_TYPE (r)
13983             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13984
13985         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13986                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13987
13988         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13989         determine_visibility (TYPE_NAME (type));
13990         /* Now that we know visibility, instantiate the type so we have a
13991            declaration of the op() for later calls to lambda_function.  */
13992         complete_type (type);
13993
13994         /* The capture list refers to closure members, so this needs to
13995            wait until after we finish instantiating the type.  */
13996         LAMBDA_EXPR_CAPTURE_LIST (r)
13997           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13998
13999         return build_lambda_object (r);
14000       }
14001
14002     case TARGET_EXPR:
14003       /* We can get here for a constant initializer of non-dependent type.
14004          FIXME stop folding in cp_parser_initializer_clause.  */
14005       gcc_assert (TREE_CONSTANT (t));
14006       {
14007         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
14008         TREE_CONSTANT (r) = true;
14009         return r;
14010       }
14011
14012     default:
14013       /* Handle Objective-C++ constructs, if appropriate.  */
14014       {
14015         tree subst
14016           = objcp_tsubst_copy_and_build (t, args, complain,
14017                                          in_decl, /*function_p=*/false);
14018         if (subst)
14019           return subst;
14020       }
14021       return tsubst_copy (t, args, complain, in_decl);
14022     }
14023
14024 #undef RECUR
14025 }
14026
14027 /* Verify that the instantiated ARGS are valid. For type arguments,
14028    make sure that the type's linkage is ok. For non-type arguments,
14029    make sure they are constants if they are integral or enumerations.
14030    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14031
14032 static bool
14033 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14034 {
14035   if (ARGUMENT_PACK_P (t))
14036     {
14037       tree vec = ARGUMENT_PACK_ARGS (t);
14038       int len = TREE_VEC_LENGTH (vec);
14039       bool result = false;
14040       int i;
14041
14042       for (i = 0; i < len; ++i)
14043         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14044           result = true;
14045       return result;
14046     }
14047   else if (TYPE_P (t))
14048     {
14049       /* [basic.link]: A name with no linkage (notably, the name
14050          of a class or enumeration declared in a local scope)
14051          shall not be used to declare an entity with linkage.
14052          This implies that names with no linkage cannot be used as
14053          template arguments
14054
14055          DR 757 relaxes this restriction for C++0x.  */
14056       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14057                  : no_linkage_check (t, /*relaxed_p=*/false));
14058
14059       if (nt)
14060         {
14061           /* DR 488 makes use of a type with no linkage cause
14062              type deduction to fail.  */
14063           if (complain & tf_error)
14064             {
14065               if (TYPE_ANONYMOUS_P (nt))
14066                 error ("%qT is/uses anonymous type", t);
14067               else
14068                 error ("template argument for %qD uses local type %qT",
14069                        tmpl, t);
14070             }
14071           return true;
14072         }
14073       /* In order to avoid all sorts of complications, we do not
14074          allow variably-modified types as template arguments.  */
14075       else if (variably_modified_type_p (t, NULL_TREE))
14076         {
14077           if (complain & tf_error)
14078             error ("%qT is a variably modified type", t);
14079           return true;
14080         }
14081     }
14082   /* A non-type argument of integral or enumerated type must be a
14083      constant.  */
14084   else if (TREE_TYPE (t)
14085            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14086            && !TREE_CONSTANT (t))
14087     {
14088       if (complain & tf_error)
14089         error ("integral expression %qE is not constant", t);
14090       return true;
14091     }
14092   return false;
14093 }
14094
14095 static bool
14096 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14097 {
14098   int ix, len = DECL_NTPARMS (tmpl);
14099   bool result = false;
14100
14101   for (ix = 0; ix != len; ix++)
14102     {
14103       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14104         result = true;
14105     }
14106   if (result && (complain & tf_error))
14107     error ("  trying to instantiate %qD", tmpl);
14108   return result;
14109 }
14110
14111 /* In C++0x, it's possible to have a function template whose type depends
14112    on itself recursively.  This is most obvious with decltype, but can also
14113    occur with enumeration scope (c++/48969).  So we need to catch infinite
14114    recursion and reject the substitution at deduction time; this function
14115    will return error_mark_node for any repeated substitution.
14116
14117    This also catches excessive recursion such as when f<N> depends on
14118    f<N-1> across all integers, and returns error_mark_node for all the
14119    substitutions back up to the initial one.
14120
14121    This is, of course, not reentrant.  */
14122
14123 static tree
14124 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14125 {
14126   static bool excessive_deduction_depth;
14127   static int deduction_depth;
14128   struct pending_template *old_last_pend = last_pending_template;
14129   struct tinst_level *old_error_tinst = last_error_tinst_level;
14130
14131   tree fntype = TREE_TYPE (fn);
14132   tree tinst;
14133   tree r;
14134
14135   if (excessive_deduction_depth)
14136     return error_mark_node;
14137
14138   tinst = build_tree_list (fn, targs);
14139   if (!push_tinst_level (tinst))
14140     {
14141       excessive_deduction_depth = true;
14142       ggc_free (tinst);
14143       return error_mark_node;
14144     }
14145
14146   input_location = DECL_SOURCE_LOCATION (fn);
14147   ++deduction_depth;
14148   push_deduction_access_scope (fn);
14149   r = tsubst (fntype, targs, complain, NULL_TREE);
14150   pop_deduction_access_scope (fn);
14151   --deduction_depth;
14152
14153   if (excessive_deduction_depth)
14154     {
14155       r = error_mark_node;
14156       if (deduction_depth == 0)
14157         /* Reset once we're all the way out.  */
14158         excessive_deduction_depth = false;
14159     }
14160
14161   pop_tinst_level ();
14162   /* We can't free this if a pending_template entry or last_error_tinst_level
14163      is pointing at it.  */
14164   if (last_pending_template == old_last_pend
14165       && last_error_tinst_level == old_error_tinst)
14166     ggc_free (tinst);
14167   return r;
14168 }
14169
14170 /* Instantiate the indicated variable or function template TMPL with
14171    the template arguments in TARG_PTR.  */
14172
14173 static tree
14174 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14175 {
14176   tree targ_ptr = orig_args;
14177   tree fndecl;
14178   tree gen_tmpl;
14179   tree spec;
14180   HOST_WIDE_INT saved_processing_template_decl;
14181
14182   if (tmpl == error_mark_node)
14183     return error_mark_node;
14184
14185   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14186
14187   /* If this function is a clone, handle it specially.  */
14188   if (DECL_CLONED_FUNCTION_P (tmpl))
14189     {
14190       tree spec;
14191       tree clone;
14192
14193       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14194          DECL_CLONED_FUNCTION.  */
14195       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14196                                    targ_ptr, complain);
14197       if (spec == error_mark_node)
14198         return error_mark_node;
14199
14200       /* Look for the clone.  */
14201       FOR_EACH_CLONE (clone, spec)
14202         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14203           return clone;
14204       /* We should always have found the clone by now.  */
14205       gcc_unreachable ();
14206       return NULL_TREE;
14207     }
14208
14209   /* Check to see if we already have this specialization.  */
14210   gen_tmpl = most_general_template (tmpl);
14211   if (tmpl != gen_tmpl)
14212     /* The TMPL is a partial instantiation.  To get a full set of
14213        arguments we must add the arguments used to perform the
14214        partial instantiation.  */
14215     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14216                                             targ_ptr);
14217
14218   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14219      but it doesn't seem to be on the hot path.  */
14220   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14221
14222   gcc_assert (tmpl == gen_tmpl
14223               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14224                   == spec)
14225               || fndecl == NULL_TREE);
14226
14227   if (spec != NULL_TREE)
14228     return spec;
14229
14230   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14231                                complain))
14232     return error_mark_node;
14233
14234   /* We are building a FUNCTION_DECL, during which the access of its
14235      parameters and return types have to be checked.  However this
14236      FUNCTION_DECL which is the desired context for access checking
14237      is not built yet.  We solve this chicken-and-egg problem by
14238      deferring all checks until we have the FUNCTION_DECL.  */
14239   push_deferring_access_checks (dk_deferred);
14240
14241   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14242      (because, for example, we have encountered a non-dependent
14243      function call in the body of a template function and must now
14244      determine which of several overloaded functions will be called),
14245      within the instantiation itself we are not processing a
14246      template.  */  
14247   saved_processing_template_decl = processing_template_decl;
14248   processing_template_decl = 0;
14249   /* Substitute template parameters to obtain the specialization.  */
14250   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14251                    targ_ptr, complain, gen_tmpl);
14252   processing_template_decl = saved_processing_template_decl;
14253   if (fndecl == error_mark_node)
14254     return error_mark_node;
14255
14256   /* Now we know the specialization, compute access previously
14257      deferred.  */
14258   push_access_scope (fndecl);
14259
14260   /* Some typedefs referenced from within the template code need to be access
14261      checked at template instantiation time, i.e now. These types were
14262      added to the template at parsing time. Let's get those and perfom
14263      the acces checks then.  */
14264   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14265   perform_deferred_access_checks ();
14266   pop_access_scope (fndecl);
14267   pop_deferring_access_checks ();
14268
14269   /* The DECL_TI_TEMPLATE should always be the immediate parent
14270      template, not the most general template.  */
14271   DECL_TI_TEMPLATE (fndecl) = tmpl;
14272
14273   /* If we've just instantiated the main entry point for a function,
14274      instantiate all the alternate entry points as well.  We do this
14275      by cloning the instantiation of the main entry point, not by
14276      instantiating the template clones.  */
14277   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14278     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14279
14280   return fndecl;
14281 }
14282
14283 /* Wrapper for instantiate_template_1.  */
14284
14285 tree
14286 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14287 {
14288   tree ret;
14289   timevar_push (TV_TEMPLATE_INST);
14290   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14291   timevar_pop (TV_TEMPLATE_INST);
14292   return ret;
14293 }
14294
14295 /* We're going to do deduction substitution on the type of TMPL, a function
14296    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14297    disable access checking.  */
14298
14299 static void
14300 push_deduction_access_scope (tree tmpl)
14301 {
14302   if (cxx_dialect >= cxx0x)
14303     {
14304       int ptd = processing_template_decl;
14305       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14306       /* Preserve processing_template_decl across push_to_top_level.  */
14307       if (ptd && !processing_template_decl)
14308         ++processing_template_decl;
14309     }
14310   else
14311     push_deferring_access_checks (dk_no_check);
14312 }
14313
14314 /* And pop back out.  */
14315
14316 static void
14317 pop_deduction_access_scope (tree tmpl)
14318 {
14319   if (cxx_dialect >= cxx0x)
14320     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14321   else
14322     pop_deferring_access_checks ();
14323 }
14324
14325 /* PARM is a template parameter pack for FN.  Returns true iff
14326    PARM is used in a deducible way in the argument list of FN.  */
14327
14328 static bool
14329 pack_deducible_p (tree parm, tree fn)
14330 {
14331   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14332   for (; t; t = TREE_CHAIN (t))
14333     {
14334       tree type = TREE_VALUE (t);
14335       tree packs;
14336       if (!PACK_EXPANSION_P (type))
14337         continue;
14338       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14339            packs; packs = TREE_CHAIN (packs))
14340         if (TREE_VALUE (packs) == parm)
14341           {
14342             /* The template parameter pack is used in a function parameter
14343                pack.  If this is the end of the parameter list, the
14344                template parameter pack is deducible.  */
14345             if (TREE_CHAIN (t) == void_list_node)
14346               return true;
14347             else
14348               /* Otherwise, not.  Well, it could be deduced from
14349                  a non-pack parameter, but doing so would end up with
14350                  a deduction mismatch, so don't bother.  */
14351               return false;
14352           }
14353     }
14354   /* The template parameter pack isn't used in any function parameter
14355      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14356   return true;
14357 }
14358
14359 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14360    NARGS elements of the arguments that are being used when calling
14361    it.  TARGS is a vector into which the deduced template arguments
14362    are placed.
14363
14364    Return zero for success, 2 for an incomplete match that doesn't resolve
14365    all the types, and 1 for complete failure.  An error message will be
14366    printed only for an incomplete match.
14367
14368    If FN is a conversion operator, or we are trying to produce a specific
14369    specialization, RETURN_TYPE is the return type desired.
14370
14371    The EXPLICIT_TARGS are explicit template arguments provided via a
14372    template-id.
14373
14374    The parameter STRICT is one of:
14375
14376    DEDUCE_CALL:
14377      We are deducing arguments for a function call, as in
14378      [temp.deduct.call].
14379
14380    DEDUCE_CONV:
14381      We are deducing arguments for a conversion function, as in
14382      [temp.deduct.conv].
14383
14384    DEDUCE_EXACT:
14385      We are deducing arguments when doing an explicit instantiation
14386      as in [temp.explicit], when determining an explicit specialization
14387      as in [temp.expl.spec], or when taking the address of a function
14388      template, as in [temp.deduct.funcaddr].  */
14389
14390 int
14391 fn_type_unification (tree fn,
14392                      tree explicit_targs,
14393                      tree targs,
14394                      const tree *args,
14395                      unsigned int nargs,
14396                      tree return_type,
14397                      unification_kind_t strict,
14398                      int flags,
14399                      bool explain_p)
14400 {
14401   tree parms;
14402   tree fntype;
14403   int result;
14404
14405   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14406
14407   fntype = TREE_TYPE (fn);
14408   if (explicit_targs)
14409     {
14410       /* [temp.deduct]
14411
14412          The specified template arguments must match the template
14413          parameters in kind (i.e., type, nontype, template), and there
14414          must not be more arguments than there are parameters;
14415          otherwise type deduction fails.
14416
14417          Nontype arguments must match the types of the corresponding
14418          nontype template parameters, or must be convertible to the
14419          types of the corresponding nontype parameters as specified in
14420          _temp.arg.nontype_, otherwise type deduction fails.
14421
14422          All references in the function type of the function template
14423          to the corresponding template parameters are replaced by the
14424          specified template argument values.  If a substitution in a
14425          template parameter or in the function type of the function
14426          template results in an invalid type, type deduction fails.  */
14427       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14428       int i, len = TREE_VEC_LENGTH (tparms);
14429       tree converted_args;
14430       bool incomplete = false;
14431
14432       if (explicit_targs == error_mark_node)
14433         return unify_invalid (explain_p);
14434
14435       converted_args
14436         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14437                                   (explain_p
14438                                    ? tf_warning_or_error
14439                                    : tf_none),
14440                                    /*require_all_args=*/false,
14441                                    /*use_default_args=*/false));
14442       if (converted_args == error_mark_node)
14443         return 1;
14444
14445       /* Substitute the explicit args into the function type.  This is
14446          necessary so that, for instance, explicitly declared function
14447          arguments can match null pointed constants.  If we were given
14448          an incomplete set of explicit args, we must not do semantic
14449          processing during substitution as we could create partial
14450          instantiations.  */
14451       for (i = 0; i < len; i++)
14452         {
14453           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14454           bool parameter_pack = false;
14455           tree targ = TREE_VEC_ELT (converted_args, i);
14456
14457           /* Dig out the actual parm.  */
14458           if (TREE_CODE (parm) == TYPE_DECL
14459               || TREE_CODE (parm) == TEMPLATE_DECL)
14460             {
14461               parm = TREE_TYPE (parm);
14462               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14463             }
14464           else if (TREE_CODE (parm) == PARM_DECL)
14465             {
14466               parm = DECL_INITIAL (parm);
14467               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14468             }
14469
14470           if (!parameter_pack && targ == NULL_TREE)
14471             /* No explicit argument for this template parameter.  */
14472             incomplete = true;
14473
14474           if (parameter_pack && pack_deducible_p (parm, fn))
14475             {
14476               /* Mark the argument pack as "incomplete". We could
14477                  still deduce more arguments during unification.
14478                  We remove this mark in type_unification_real.  */
14479               if (targ)
14480                 {
14481                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14482                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14483                     = ARGUMENT_PACK_ARGS (targ);
14484                 }
14485
14486               /* We have some incomplete argument packs.  */
14487               incomplete = true;
14488             }
14489         }
14490
14491       processing_template_decl += incomplete;
14492       fntype = deduction_tsubst_fntype (fn, converted_args,
14493                                         (explain_p
14494                                          ? tf_warning_or_error
14495                                          : tf_none));
14496       processing_template_decl -= incomplete;
14497
14498       if (fntype == error_mark_node)
14499         return 1;
14500
14501       /* Place the explicitly specified arguments in TARGS.  */
14502       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14503         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14504     }
14505
14506   /* Never do unification on the 'this' parameter.  */
14507   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14508
14509   if (return_type)
14510     {
14511       tree *new_args;
14512
14513       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14514       new_args = XALLOCAVEC (tree, nargs + 1);
14515       new_args[0] = return_type;
14516       memcpy (new_args + 1, args, nargs * sizeof (tree));
14517       args = new_args;
14518       ++nargs;
14519     }
14520
14521   /* We allow incomplete unification without an error message here
14522      because the standard doesn't seem to explicitly prohibit it.  Our
14523      callers must be ready to deal with unification failures in any
14524      event.  */
14525   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14526                                   targs, parms, args, nargs, /*subr=*/0,
14527                                   strict, flags, explain_p);
14528
14529   /* Now that we have bindings for all of the template arguments,
14530      ensure that the arguments deduced for the template template
14531      parameters have compatible template parameter lists.  We cannot
14532      check this property before we have deduced all template
14533      arguments, because the template parameter types of a template
14534      template parameter might depend on prior template parameters
14535      deduced after the template template parameter.  The following
14536      ill-formed example illustrates this issue:
14537
14538        template<typename T, template<T> class C> void f(C<5>, T);
14539
14540        template<int N> struct X {};
14541
14542        void g() {
14543          f(X<5>(), 5l); // error: template argument deduction fails
14544        }
14545
14546      The template parameter list of 'C' depends on the template type
14547      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14548      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14549      time that we deduce 'C'.  */
14550   if (result == 0
14551       && !template_template_parm_bindings_ok_p 
14552            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14553     return unify_inconsistent_template_template_parameters (explain_p);
14554
14555   if (result == 0)
14556     /* All is well so far.  Now, check:
14557
14558        [temp.deduct]
14559
14560        When all template arguments have been deduced, all uses of
14561        template parameters in nondeduced contexts are replaced with
14562        the corresponding deduced argument values.  If the
14563        substitution results in an invalid type, as described above,
14564        type deduction fails.  */
14565     {
14566       tree substed = deduction_tsubst_fntype (fn, targs,
14567                                               (explain_p
14568                                                ? tf_warning_or_error
14569                                                : tf_none));
14570       if (substed == error_mark_node)
14571         return 1;
14572
14573       /* If we're looking for an exact match, check that what we got
14574          is indeed an exact match.  It might not be if some template
14575          parameters are used in non-deduced contexts.  */
14576       if (strict == DEDUCE_EXACT)
14577         {
14578           unsigned int i;
14579
14580           tree sarg
14581             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14582           if (return_type)
14583             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14584           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14585             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14586               return unify_type_mismatch (explain_p, args[i],
14587                                           TREE_VALUE (sarg));
14588         }
14589     }
14590
14591   return result;
14592 }
14593
14594 /* Adjust types before performing type deduction, as described in
14595    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14596    sections are symmetric.  PARM is the type of a function parameter
14597    or the return type of the conversion function.  ARG is the type of
14598    the argument passed to the call, or the type of the value
14599    initialized with the result of the conversion function.
14600    ARG_EXPR is the original argument expression, which may be null.  */
14601
14602 static int
14603 maybe_adjust_types_for_deduction (unification_kind_t strict,
14604                                   tree* parm,
14605                                   tree* arg,
14606                                   tree arg_expr)
14607 {
14608   int result = 0;
14609
14610   switch (strict)
14611     {
14612     case DEDUCE_CALL:
14613       break;
14614
14615     case DEDUCE_CONV:
14616       {
14617         /* Swap PARM and ARG throughout the remainder of this
14618            function; the handling is precisely symmetric since PARM
14619            will initialize ARG rather than vice versa.  */
14620         tree* temp = parm;
14621         parm = arg;
14622         arg = temp;
14623         break;
14624       }
14625
14626     case DEDUCE_EXACT:
14627       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14628          too, but here handle it by stripping the reference from PARM
14629          rather than by adding it to ARG.  */
14630       if (TREE_CODE (*parm) == REFERENCE_TYPE
14631           && TYPE_REF_IS_RVALUE (*parm)
14632           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14633           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14634           && TREE_CODE (*arg) == REFERENCE_TYPE
14635           && !TYPE_REF_IS_RVALUE (*arg))
14636         *parm = TREE_TYPE (*parm);
14637       /* Nothing else to do in this case.  */
14638       return 0;
14639
14640     default:
14641       gcc_unreachable ();
14642     }
14643
14644   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14645     {
14646       /* [temp.deduct.call]
14647
14648          If P is not a reference type:
14649
14650          --If A is an array type, the pointer type produced by the
14651          array-to-pointer standard conversion (_conv.array_) is
14652          used in place of A for type deduction; otherwise,
14653
14654          --If A is a function type, the pointer type produced by
14655          the function-to-pointer standard conversion
14656          (_conv.func_) is used in place of A for type deduction;
14657          otherwise,
14658
14659          --If A is a cv-qualified type, the top level
14660          cv-qualifiers of A's type are ignored for type
14661          deduction.  */
14662       if (TREE_CODE (*arg) == ARRAY_TYPE)
14663         *arg = build_pointer_type (TREE_TYPE (*arg));
14664       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14665         *arg = build_pointer_type (*arg);
14666       else
14667         *arg = TYPE_MAIN_VARIANT (*arg);
14668     }
14669
14670   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14671      of the form T&&, where T is a template parameter, and the argument
14672      is an lvalue, T is deduced as A& */
14673   if (TREE_CODE (*parm) == REFERENCE_TYPE
14674       && TYPE_REF_IS_RVALUE (*parm)
14675       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14676       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14677       && (arg_expr ? real_lvalue_p (arg_expr)
14678           /* try_one_overload doesn't provide an arg_expr, but
14679              functions are always lvalues.  */
14680           : TREE_CODE (*arg) == FUNCTION_TYPE))
14681     *arg = build_reference_type (*arg);
14682
14683   /* [temp.deduct.call]
14684
14685      If P is a cv-qualified type, the top level cv-qualifiers
14686      of P's type are ignored for type deduction.  If P is a
14687      reference type, the type referred to by P is used for
14688      type deduction.  */
14689   *parm = TYPE_MAIN_VARIANT (*parm);
14690   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14691     {
14692       *parm = TREE_TYPE (*parm);
14693       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14694     }
14695
14696   /* DR 322. For conversion deduction, remove a reference type on parm
14697      too (which has been swapped into ARG).  */
14698   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14699     *arg = TREE_TYPE (*arg);
14700
14701   return result;
14702 }
14703
14704 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14705    template which does contain any deducible template parameters; check if
14706    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14707    unify_one_argument.  */
14708
14709 static int
14710 check_non_deducible_conversion (tree parm, tree arg, int strict,
14711                                 int flags, bool explain_p)
14712 {
14713   tree type;
14714
14715   if (!TYPE_P (arg))
14716     type = TREE_TYPE (arg);
14717   else
14718     type = arg;
14719
14720   if (same_type_p (parm, type))
14721     return unify_success (explain_p);
14722
14723   if (strict == DEDUCE_CONV)
14724     {
14725       if (can_convert_arg (type, parm, NULL_TREE, flags))
14726         return unify_success (explain_p);
14727     }
14728   else if (strict != DEDUCE_EXACT)
14729     {
14730       if (can_convert_arg (parm, type,
14731                            TYPE_P (arg) ? NULL_TREE : arg,
14732                            flags))
14733         return unify_success (explain_p);
14734     }
14735
14736   if (strict == DEDUCE_EXACT)
14737     return unify_type_mismatch (explain_p, parm, arg);
14738   else
14739     return unify_arg_conversion (explain_p, parm, type, arg);
14740 }
14741
14742 /* Subroutine of type_unification_real and unify_pack_expansion to
14743    handle unification of a single P/A pair.  Parameters are as
14744    for those functions.  */
14745
14746 static int
14747 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14748                     int subr, unification_kind_t strict, int flags,
14749                     bool explain_p)
14750 {
14751   tree arg_expr = NULL_TREE;
14752   int arg_strict;
14753
14754   if (arg == error_mark_node || parm == error_mark_node)
14755     return unify_invalid (explain_p);
14756   if (arg == unknown_type_node)
14757     /* We can't deduce anything from this, but we might get all the
14758        template args from other function args.  */
14759     return unify_success (explain_p);
14760
14761   /* FIXME uses_deducible_template_parms */
14762   if (TYPE_P (parm) && !uses_template_parms (parm))
14763     return check_non_deducible_conversion (parm, arg, strict, flags,
14764                                            explain_p);
14765
14766   switch (strict)
14767     {
14768     case DEDUCE_CALL:
14769       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14770                     | UNIFY_ALLOW_MORE_CV_QUAL
14771                     | UNIFY_ALLOW_DERIVED);
14772       break;
14773
14774     case DEDUCE_CONV:
14775       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14776       break;
14777
14778     case DEDUCE_EXACT:
14779       arg_strict = UNIFY_ALLOW_NONE;
14780       break;
14781
14782     default:
14783       gcc_unreachable ();
14784     }
14785
14786   /* We only do these transformations if this is the top-level
14787      parameter_type_list in a call or declaration matching; in other
14788      situations (nested function declarators, template argument lists) we
14789      won't be comparing a type to an expression, and we don't do any type
14790      adjustments.  */
14791   if (!subr)
14792     {
14793       if (!TYPE_P (arg))
14794         {
14795           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14796           if (type_unknown_p (arg))
14797             {
14798               /* [temp.deduct.type] A template-argument can be
14799                  deduced from a pointer to function or pointer
14800                  to member function argument if the set of
14801                  overloaded functions does not contain function
14802                  templates and at most one of a set of
14803                  overloaded functions provides a unique
14804                  match.  */
14805
14806               if (resolve_overloaded_unification
14807                   (tparms, targs, parm, arg, strict,
14808                    arg_strict, explain_p))
14809                 return unify_success (explain_p);
14810               return unify_overload_resolution_failure (explain_p, arg);
14811             }
14812
14813           arg_expr = arg;
14814           arg = unlowered_expr_type (arg);
14815           if (arg == error_mark_node)
14816             return unify_invalid (explain_p);
14817         }
14818
14819       arg_strict |=
14820         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
14821     }
14822   else
14823     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
14824                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
14825
14826   /* For deduction from an init-list we need the actual list.  */
14827   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14828     arg = arg_expr;
14829   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
14830 }
14831
14832 /* Most parms like fn_type_unification.
14833
14834    If SUBR is 1, we're being called recursively (to unify the
14835    arguments of a function or method parameter of a function
14836    template). */
14837
14838 static int
14839 type_unification_real (tree tparms,
14840                        tree targs,
14841                        tree xparms,
14842                        const tree *xargs,
14843                        unsigned int xnargs,
14844                        int subr,
14845                        unification_kind_t strict,
14846                        int flags,
14847                        bool explain_p)
14848 {
14849   tree parm, arg;
14850   int i;
14851   int ntparms = TREE_VEC_LENGTH (tparms);
14852   int saw_undeduced = 0;
14853   tree parms;
14854   const tree *args;
14855   unsigned int nargs;
14856   unsigned int ia;
14857
14858   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14859   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14860   gcc_assert (ntparms > 0);
14861
14862   /* Reset the number of non-defaulted template arguments contained
14863      in TARGS.  */
14864   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14865
14866  again:
14867   parms = xparms;
14868   args = xargs;
14869   nargs = xnargs;
14870
14871   ia = 0;
14872   while (parms && parms != void_list_node
14873          && ia < nargs)
14874     {
14875       parm = TREE_VALUE (parms);
14876
14877       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14878           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14879         /* For a function parameter pack that occurs at the end of the
14880            parameter-declaration-list, the type A of each remaining
14881            argument of the call is compared with the type P of the
14882            declarator-id of the function parameter pack.  */
14883         break;
14884
14885       parms = TREE_CHAIN (parms);
14886
14887       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14888         /* For a function parameter pack that does not occur at the
14889            end of the parameter-declaration-list, the type of the
14890            parameter pack is a non-deduced context.  */
14891         continue;
14892
14893       arg = args[ia];
14894       ++ia;
14895
14896       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
14897                               flags, explain_p))
14898         return 1;
14899     }
14900
14901   if (parms 
14902       && parms != void_list_node
14903       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14904     {
14905       /* Unify the remaining arguments with the pack expansion type.  */
14906       tree argvec;
14907       tree parmvec = make_tree_vec (1);
14908
14909       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14910       argvec = make_tree_vec (nargs - ia);
14911       for (i = 0; ia < nargs; ++ia, ++i)
14912         TREE_VEC_ELT (argvec, i) = args[ia];
14913
14914       /* Copy the parameter into parmvec.  */
14915       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14916       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14917                                 /*subr=*/subr, explain_p))
14918         return 1;
14919
14920       /* Advance to the end of the list of parameters.  */
14921       parms = TREE_CHAIN (parms);
14922     }
14923
14924   /* Fail if we've reached the end of the parm list, and more args
14925      are present, and the parm list isn't variadic.  */
14926   if (ia < nargs && parms == void_list_node)
14927     return unify_too_many_arguments (explain_p, nargs, ia);
14928   /* Fail if parms are left and they don't have default values.  */
14929   if (parms && parms != void_list_node
14930       && TREE_PURPOSE (parms) == NULL_TREE)
14931     {
14932       unsigned int count = nargs;
14933       tree p = parms;
14934       while (p && p != void_list_node)
14935         {
14936           count++;
14937           p = TREE_CHAIN (p);
14938         }
14939       return unify_too_few_arguments (explain_p, ia, count);
14940     }
14941
14942   if (!subr)
14943     {
14944       tsubst_flags_t complain = (explain_p
14945                                  ? tf_warning_or_error
14946                                  : tf_none);
14947
14948       /* Check to see if we need another pass before we start clearing
14949          ARGUMENT_PACK_INCOMPLETE_P.  */
14950       for (i = 0; i < ntparms; i++)
14951         {
14952           tree targ = TREE_VEC_ELT (targs, i);
14953           tree tparm = TREE_VEC_ELT (tparms, i);
14954
14955           if (targ || tparm == error_mark_node)
14956             continue;
14957           tparm = TREE_VALUE (tparm);
14958
14959           /* If this is an undeduced nontype parameter that depends on
14960              a type parameter, try another pass; its type may have been
14961              deduced from a later argument than the one from which
14962              this parameter can be deduced.  */
14963           if (TREE_CODE (tparm) == PARM_DECL
14964               && uses_template_parms (TREE_TYPE (tparm))
14965               && !saw_undeduced++)
14966             goto again;
14967         }
14968
14969       for (i = 0; i < ntparms; i++)
14970         {
14971           tree targ = TREE_VEC_ELT (targs, i);
14972           tree tparm = TREE_VEC_ELT (tparms, i);
14973
14974           /* Clear the "incomplete" flags on all argument packs now so that
14975              substituting them into later default arguments works.  */
14976           if (targ && ARGUMENT_PACK_P (targ))
14977             {
14978               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14979               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14980             }
14981
14982           if (targ || tparm == error_mark_node)
14983             continue;
14984           tparm = TREE_VALUE (tparm);
14985
14986           /* Core issue #226 (C++0x) [temp.deduct]:
14987
14988              If a template argument has not been deduced, its
14989              default template argument, if any, is used. 
14990
14991              When we are in C++98 mode, TREE_PURPOSE will either
14992              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14993              to explicitly check cxx_dialect here.  */
14994           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14995             {
14996               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14997               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14998               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
14999               arg = convert_template_argument (parm, arg, targs, complain,
15000                                                i, NULL_TREE);
15001               if (arg == error_mark_node)
15002                 return 1;
15003               else
15004                 {
15005                   TREE_VEC_ELT (targs, i) = arg;
15006                   /* The position of the first default template argument,
15007                      is also the number of non-defaulted arguments in TARGS.
15008                      Record that.  */
15009                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15010                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
15011                   continue;
15012                 }
15013             }
15014
15015           /* If the type parameter is a parameter pack, then it will
15016              be deduced to an empty parameter pack.  */
15017           if (template_parameter_pack_p (tparm))
15018             {
15019               tree arg;
15020
15021               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15022                 {
15023                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15024                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15025                   TREE_CONSTANT (arg) = 1;
15026                 }
15027               else
15028                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15029
15030               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15031
15032               TREE_VEC_ELT (targs, i) = arg;
15033               continue;
15034             }
15035
15036           return unify_parameter_deduction_failure (explain_p, tparm);
15037         }
15038     }
15039 #ifdef ENABLE_CHECKING
15040   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15041     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15042 #endif
15043
15044   return unify_success (explain_p);
15045 }
15046
15047 /* Subroutine of type_unification_real.  Args are like the variables
15048    at the call site.  ARG is an overloaded function (or template-id);
15049    we try deducing template args from each of the overloads, and if
15050    only one succeeds, we go with that.  Modifies TARGS and returns
15051    true on success.  */
15052
15053 static bool
15054 resolve_overloaded_unification (tree tparms,
15055                                 tree targs,
15056                                 tree parm,
15057                                 tree arg,
15058                                 unification_kind_t strict,
15059                                 int sub_strict,
15060                                 bool explain_p)
15061 {
15062   tree tempargs = copy_node (targs);
15063   int good = 0;
15064   tree goodfn = NULL_TREE;
15065   bool addr_p;
15066
15067   if (TREE_CODE (arg) == ADDR_EXPR)
15068     {
15069       arg = TREE_OPERAND (arg, 0);
15070       addr_p = true;
15071     }
15072   else
15073     addr_p = false;
15074
15075   if (TREE_CODE (arg) == COMPONENT_REF)
15076     /* Handle `&x' where `x' is some static or non-static member
15077        function name.  */
15078     arg = TREE_OPERAND (arg, 1);
15079
15080   if (TREE_CODE (arg) == OFFSET_REF)
15081     arg = TREE_OPERAND (arg, 1);
15082
15083   /* Strip baselink information.  */
15084   if (BASELINK_P (arg))
15085     arg = BASELINK_FUNCTIONS (arg);
15086
15087   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15088     {
15089       /* If we got some explicit template args, we need to plug them into
15090          the affected templates before we try to unify, in case the
15091          explicit args will completely resolve the templates in question.  */
15092
15093       int ok = 0;
15094       tree expl_subargs = TREE_OPERAND (arg, 1);
15095       arg = TREE_OPERAND (arg, 0);
15096
15097       for (; arg; arg = OVL_NEXT (arg))
15098         {
15099           tree fn = OVL_CURRENT (arg);
15100           tree subargs, elem;
15101
15102           if (TREE_CODE (fn) != TEMPLATE_DECL)
15103             continue;
15104
15105           ++processing_template_decl;
15106           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15107                                   expl_subargs, /*check_ret=*/false);
15108           if (subargs && !any_dependent_template_arguments_p (subargs))
15109             {
15110               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15111               if (try_one_overload (tparms, targs, tempargs, parm,
15112                                     elem, strict, sub_strict, addr_p, explain_p)
15113                   && (!goodfn || !decls_match (goodfn, elem)))
15114                 {
15115                   goodfn = elem;
15116                   ++good;
15117                 }
15118             }
15119           else if (subargs)
15120             ++ok;
15121           --processing_template_decl;
15122         }
15123       /* If no templates (or more than one) are fully resolved by the
15124          explicit arguments, this template-id is a non-deduced context; it
15125          could still be OK if we deduce all template arguments for the
15126          enclosing call through other arguments.  */
15127       if (good != 1)
15128         good = ok;
15129     }
15130   else if (TREE_CODE (arg) != OVERLOAD
15131            && TREE_CODE (arg) != FUNCTION_DECL)
15132     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15133        -- but the deduction does not succeed because the expression is
15134        not just the function on its own.  */
15135     return false;
15136   else
15137     for (; arg; arg = OVL_NEXT (arg))
15138       if (try_one_overload (tparms, targs, tempargs, parm,
15139                             TREE_TYPE (OVL_CURRENT (arg)),
15140                             strict, sub_strict, addr_p, explain_p)
15141           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15142         {
15143           goodfn = OVL_CURRENT (arg);
15144           ++good;
15145         }
15146
15147   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15148      to function or pointer to member function argument if the set of
15149      overloaded functions does not contain function templates and at most
15150      one of a set of overloaded functions provides a unique match.
15151
15152      So if we found multiple possibilities, we return success but don't
15153      deduce anything.  */
15154
15155   if (good == 1)
15156     {
15157       int i = TREE_VEC_LENGTH (targs);
15158       for (; i--; )
15159         if (TREE_VEC_ELT (tempargs, i))
15160           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15161     }
15162   if (good)
15163     return true;
15164
15165   return false;
15166 }
15167
15168 /* Core DR 115: In contexts where deduction is done and fails, or in
15169    contexts where deduction is not done, if a template argument list is
15170    specified and it, along with any default template arguments, identifies
15171    a single function template specialization, then the template-id is an
15172    lvalue for the function template specialization.  */
15173
15174 tree
15175 resolve_nondeduced_context (tree orig_expr)
15176 {
15177   tree expr, offset, baselink;
15178   bool addr;
15179
15180   if (!type_unknown_p (orig_expr))
15181     return orig_expr;
15182
15183   expr = orig_expr;
15184   addr = false;
15185   offset = NULL_TREE;
15186   baselink = NULL_TREE;
15187
15188   if (TREE_CODE (expr) == ADDR_EXPR)
15189     {
15190       expr = TREE_OPERAND (expr, 0);
15191       addr = true;
15192     }
15193   if (TREE_CODE (expr) == OFFSET_REF)
15194     {
15195       offset = expr;
15196       expr = TREE_OPERAND (expr, 1);
15197     }
15198   if (BASELINK_P (expr))
15199     {
15200       baselink = expr;
15201       expr = BASELINK_FUNCTIONS (expr);
15202     }
15203
15204   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15205     {
15206       int good = 0;
15207       tree goodfn = NULL_TREE;
15208
15209       /* If we got some explicit template args, we need to plug them into
15210          the affected templates before we try to unify, in case the
15211          explicit args will completely resolve the templates in question.  */
15212
15213       tree expl_subargs = TREE_OPERAND (expr, 1);
15214       tree arg = TREE_OPERAND (expr, 0);
15215       tree badfn = NULL_TREE;
15216       tree badargs = NULL_TREE;
15217
15218       for (; arg; arg = OVL_NEXT (arg))
15219         {
15220           tree fn = OVL_CURRENT (arg);
15221           tree subargs, elem;
15222
15223           if (TREE_CODE (fn) != TEMPLATE_DECL)
15224             continue;
15225
15226           ++processing_template_decl;
15227           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15228                                   expl_subargs, /*check_ret=*/false);
15229           if (subargs && !any_dependent_template_arguments_p (subargs))
15230             {
15231               elem = instantiate_template (fn, subargs, tf_none);
15232               if (elem == error_mark_node)
15233                 {
15234                   badfn = fn;
15235                   badargs = subargs;
15236                 }
15237               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15238                 {
15239                   goodfn = elem;
15240                   ++good;
15241                 }
15242             }
15243           --processing_template_decl;
15244         }
15245       if (good == 1)
15246         {
15247           mark_used (goodfn);
15248           expr = goodfn;
15249           if (baselink)
15250             expr = build_baselink (BASELINK_BINFO (baselink),
15251                                    BASELINK_ACCESS_BINFO (baselink),
15252                                    expr, BASELINK_OPTYPE (baselink));
15253           if (offset)
15254             {
15255               tree base
15256                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15257               expr = build_offset_ref (base, expr, addr);
15258             }
15259           if (addr)
15260             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15261           return expr;
15262         }
15263       else if (good == 0 && badargs)
15264         /* There were no good options and at least one bad one, so let the
15265            user know what the problem is.  */
15266         instantiate_template (badfn, badargs, tf_warning_or_error);
15267     }
15268   return orig_expr;
15269 }
15270
15271 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15272    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15273    different overloads deduce different arguments for a given parm.
15274    ADDR_P is true if the expression for which deduction is being
15275    performed was of the form "& fn" rather than simply "fn".
15276
15277    Returns 1 on success.  */
15278
15279 static int
15280 try_one_overload (tree tparms,
15281                   tree orig_targs,
15282                   tree targs,
15283                   tree parm,
15284                   tree arg,
15285                   unification_kind_t strict,
15286                   int sub_strict,
15287                   bool addr_p,
15288                   bool explain_p)
15289 {
15290   int nargs;
15291   tree tempargs;
15292   int i;
15293
15294   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15295      to function or pointer to member function argument if the set of
15296      overloaded functions does not contain function templates and at most
15297      one of a set of overloaded functions provides a unique match.
15298
15299      So if this is a template, just return success.  */
15300
15301   if (uses_template_parms (arg))
15302     return 1;
15303
15304   if (TREE_CODE (arg) == METHOD_TYPE)
15305     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15306   else if (addr_p)
15307     arg = build_pointer_type (arg);
15308
15309   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15310
15311   /* We don't copy orig_targs for this because if we have already deduced
15312      some template args from previous args, unify would complain when we
15313      try to deduce a template parameter for the same argument, even though
15314      there isn't really a conflict.  */
15315   nargs = TREE_VEC_LENGTH (targs);
15316   tempargs = make_tree_vec (nargs);
15317
15318   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15319     return 0;
15320
15321   /* First make sure we didn't deduce anything that conflicts with
15322      explicitly specified args.  */
15323   for (i = nargs; i--; )
15324     {
15325       tree elt = TREE_VEC_ELT (tempargs, i);
15326       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15327
15328       if (!elt)
15329         /*NOP*/;
15330       else if (uses_template_parms (elt))
15331         /* Since we're unifying against ourselves, we will fill in
15332            template args used in the function parm list with our own
15333            template parms.  Discard them.  */
15334         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15335       else if (oldelt && !template_args_equal (oldelt, elt))
15336         return 0;
15337     }
15338
15339   for (i = nargs; i--; )
15340     {
15341       tree elt = TREE_VEC_ELT (tempargs, i);
15342
15343       if (elt)
15344         TREE_VEC_ELT (targs, i) = elt;
15345     }
15346
15347   return 1;
15348 }
15349
15350 /* PARM is a template class (perhaps with unbound template
15351    parameters).  ARG is a fully instantiated type.  If ARG can be
15352    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15353    TARGS are as for unify.  */
15354
15355 static tree
15356 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15357                        bool explain_p)
15358 {
15359   tree copy_of_targs;
15360
15361   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15362       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15363           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15364     return NULL_TREE;
15365
15366   /* We need to make a new template argument vector for the call to
15367      unify.  If we used TARGS, we'd clutter it up with the result of
15368      the attempted unification, even if this class didn't work out.
15369      We also don't want to commit ourselves to all the unifications
15370      we've already done, since unification is supposed to be done on
15371      an argument-by-argument basis.  In other words, consider the
15372      following pathological case:
15373
15374        template <int I, int J, int K>
15375        struct S {};
15376
15377        template <int I, int J>
15378        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15379
15380        template <int I, int J, int K>
15381        void f(S<I, J, K>, S<I, I, I>);
15382
15383        void g() {
15384          S<0, 0, 0> s0;
15385          S<0, 1, 2> s2;
15386
15387          f(s0, s2);
15388        }
15389
15390      Now, by the time we consider the unification involving `s2', we
15391      already know that we must have `f<0, 0, 0>'.  But, even though
15392      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15393      because there are two ways to unify base classes of S<0, 1, 2>
15394      with S<I, I, I>.  If we kept the already deduced knowledge, we
15395      would reject the possibility I=1.  */
15396   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15397
15398   /* If unification failed, we're done.  */
15399   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15400              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15401     return NULL_TREE;
15402
15403   return arg;
15404 }
15405
15406 /* Given a template type PARM and a class type ARG, find the unique
15407    base type in ARG that is an instance of PARM.  We do not examine
15408    ARG itself; only its base-classes.  If there is not exactly one
15409    appropriate base class, return NULL_TREE.  PARM may be the type of
15410    a partial specialization, as well as a plain template type.  Used
15411    by unify.  */
15412
15413 static enum template_base_result
15414 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15415                    bool explain_p, tree *result)
15416 {
15417   tree rval = NULL_TREE;
15418   tree binfo;
15419
15420   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15421
15422   binfo = TYPE_BINFO (complete_type (arg));
15423   if (!binfo)
15424     {
15425       /* The type could not be completed.  */
15426       *result = NULL_TREE;
15427       return tbr_incomplete_type;
15428     }
15429
15430   /* Walk in inheritance graph order.  The search order is not
15431      important, and this avoids multiple walks of virtual bases.  */
15432   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15433     {
15434       tree r = try_class_unification (tparms, targs, parm,
15435                                       BINFO_TYPE (binfo), explain_p);
15436
15437       if (r)
15438         {
15439           /* If there is more than one satisfactory baseclass, then:
15440
15441                [temp.deduct.call]
15442
15443               If they yield more than one possible deduced A, the type
15444               deduction fails.
15445
15446              applies.  */
15447           if (rval && !same_type_p (r, rval))
15448             {
15449               *result = NULL_TREE;
15450               return tbr_ambiguous_baseclass;
15451             }
15452
15453           rval = r;
15454         }
15455     }
15456
15457   *result = rval;
15458   return tbr_success;
15459 }
15460
15461 /* Returns the level of DECL, which declares a template parameter.  */
15462
15463 static int
15464 template_decl_level (tree decl)
15465 {
15466   switch (TREE_CODE (decl))
15467     {
15468     case TYPE_DECL:
15469     case TEMPLATE_DECL:
15470       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15471
15472     case PARM_DECL:
15473       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15474
15475     default:
15476       gcc_unreachable ();
15477     }
15478   return 0;
15479 }
15480
15481 /* Decide whether ARG can be unified with PARM, considering only the
15482    cv-qualifiers of each type, given STRICT as documented for unify.
15483    Returns nonzero iff the unification is OK on that basis.  */
15484
15485 static int
15486 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15487 {
15488   int arg_quals = cp_type_quals (arg);
15489   int parm_quals = cp_type_quals (parm);
15490
15491   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15492       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15493     {
15494       /*  Although a CVR qualifier is ignored when being applied to a
15495           substituted template parameter ([8.3.2]/1 for example), that
15496           does not allow us to unify "const T" with "int&" because both
15497           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15498           It is ok when we're allowing additional CV qualifiers
15499           at the outer level [14.8.2.1]/3,1st bullet.  */
15500       if ((TREE_CODE (arg) == REFERENCE_TYPE
15501            || TREE_CODE (arg) == FUNCTION_TYPE
15502            || TREE_CODE (arg) == METHOD_TYPE)
15503           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15504         return 0;
15505
15506       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15507           && (parm_quals & TYPE_QUAL_RESTRICT))
15508         return 0;
15509     }
15510
15511   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15512       && (arg_quals & parm_quals) != parm_quals)
15513     return 0;
15514
15515   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15516       && (parm_quals & arg_quals) != arg_quals)
15517     return 0;
15518
15519   return 1;
15520 }
15521
15522 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15523 void 
15524 template_parm_level_and_index (tree parm, int* level, int* index)
15525 {
15526   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15527       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15528       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15529     {
15530       *index = TEMPLATE_TYPE_IDX (parm);
15531       *level = TEMPLATE_TYPE_LEVEL (parm);
15532     }
15533   else
15534     {
15535       *index = TEMPLATE_PARM_IDX (parm);
15536       *level = TEMPLATE_PARM_LEVEL (parm);
15537     }
15538 }
15539
15540 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15541   do {                                                                  \
15542     if (unify (TP, TA, P, A, S, EP))                                    \
15543       return 1;                                                         \
15544   } while (0);
15545
15546 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15547    expansion at the end of PACKED_PARMS. Returns 0 if the type
15548    deduction succeeds, 1 otherwise. STRICT is the same as in
15549    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15550    call argument list. We'll need to adjust the arguments to make them
15551    types. SUBR tells us if this is from a recursive call to
15552    type_unification_real, or for comparing two template argument
15553    lists. */
15554
15555 static int
15556 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15557                       tree packed_args, unification_kind_t strict,
15558                       bool subr, bool explain_p)
15559 {
15560   tree parm 
15561     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15562   tree pattern = PACK_EXPANSION_PATTERN (parm);
15563   tree pack, packs = NULL_TREE;
15564   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15565   int len = TREE_VEC_LENGTH (packed_args);
15566
15567   /* Determine the parameter packs we will be deducing from the
15568      pattern, and record their current deductions.  */
15569   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15570        pack; pack = TREE_CHAIN (pack))
15571     {
15572       tree parm_pack = TREE_VALUE (pack);
15573       int idx, level;
15574
15575       /* Determine the index and level of this parameter pack.  */
15576       template_parm_level_and_index (parm_pack, &level, &idx);
15577
15578       /* Keep track of the parameter packs and their corresponding
15579          argument packs.  */
15580       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15581       TREE_TYPE (packs) = make_tree_vec (len - start);
15582     }
15583   
15584   /* Loop through all of the arguments that have not yet been
15585      unified and unify each with the pattern.  */
15586   for (i = start; i < len; i++)
15587     {
15588       tree parm;
15589       bool any_explicit = false;
15590       tree arg = TREE_VEC_ELT (packed_args, i);
15591
15592       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15593          or the element of its argument pack at the current index if
15594          this argument was explicitly specified.  */
15595       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15596         {
15597           int idx, level;
15598           tree arg, pargs;
15599           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15600
15601           arg = NULL_TREE;
15602           if (TREE_VALUE (pack)
15603               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15604               && (i < TREE_VEC_LENGTH (pargs)))
15605             {
15606               any_explicit = true;
15607               arg = TREE_VEC_ELT (pargs, i);
15608             }
15609           TMPL_ARG (targs, level, idx) = arg;
15610         }
15611
15612       /* If we had explicit template arguments, substitute them into the
15613          pattern before deduction.  */
15614       if (any_explicit)
15615         {
15616           /* Some arguments might still be unspecified or dependent.  */
15617           bool dependent;
15618           ++processing_template_decl;
15619           dependent = any_dependent_template_arguments_p (targs);
15620           if (!dependent)
15621             --processing_template_decl;
15622           parm = tsubst (pattern, targs,
15623                          explain_p ? tf_warning_or_error : tf_none,
15624                          NULL_TREE);
15625           if (dependent)
15626             --processing_template_decl;
15627           if (parm == error_mark_node)
15628             return 1;
15629         }
15630       else
15631         parm = pattern;
15632
15633       /* Unify the pattern with the current argument.  */
15634       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15635                               LOOKUP_IMPLICIT, explain_p))
15636         return 1;
15637
15638       /* For each parameter pack, collect the deduced value.  */
15639       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15640         {
15641           int idx, level;
15642           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15643
15644           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15645             TMPL_ARG (targs, level, idx);
15646         }
15647     }
15648
15649   /* Verify that the results of unification with the parameter packs
15650      produce results consistent with what we've seen before, and make
15651      the deduced argument packs available.  */
15652   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15653     {
15654       tree old_pack = TREE_VALUE (pack);
15655       tree new_args = TREE_TYPE (pack);
15656       int i, len = TREE_VEC_LENGTH (new_args);
15657       int idx, level;
15658       bool nondeduced_p = false;
15659
15660       /* By default keep the original deduced argument pack.
15661          If necessary, more specific code is going to update the
15662          resulting deduced argument later down in this function.  */
15663       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15664       TMPL_ARG (targs, level, idx) = old_pack;
15665
15666       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15667          actually deduce anything.  */
15668       for (i = 0; i < len && !nondeduced_p; ++i)
15669         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15670           nondeduced_p = true;
15671       if (nondeduced_p)
15672         continue;
15673
15674       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15675         {
15676           /* If we had fewer function args than explicit template args,
15677              just use the explicits.  */
15678           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15679           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15680           if (len < explicit_len)
15681             new_args = explicit_args;
15682         }
15683
15684       if (!old_pack)
15685         {
15686           tree result;
15687           /* Build the deduced *_ARGUMENT_PACK.  */
15688           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15689             {
15690               result = make_node (NONTYPE_ARGUMENT_PACK);
15691               TREE_TYPE (result) = 
15692                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15693               TREE_CONSTANT (result) = 1;
15694             }
15695           else
15696             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15697
15698           SET_ARGUMENT_PACK_ARGS (result, new_args);
15699
15700           /* Note the deduced argument packs for this parameter
15701              pack.  */
15702           TMPL_ARG (targs, level, idx) = result;
15703         }
15704       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15705                && (ARGUMENT_PACK_ARGS (old_pack) 
15706                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15707         {
15708           /* We only had the explicitly-provided arguments before, but
15709              now we have a complete set of arguments.  */
15710           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15711
15712           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15713           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15714           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15715         }
15716       else
15717         {
15718           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
15719           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15720
15721           if (!comp_template_args_with_info (old_args, new_args,
15722                                              &bad_old_arg, &bad_new_arg))
15723             /* Inconsistent unification of this parameter pack.  */
15724             return unify_parameter_pack_inconsistent (explain_p,
15725                                                       bad_old_arg,
15726                                                       bad_new_arg);
15727         }
15728     }
15729
15730   return unify_success (explain_p);
15731 }
15732
15733 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15734    set of template parameters to a template.  TARGS is the bindings
15735    for those template parameters, as determined thus far; TARGS may
15736    include template arguments for outer levels of template parameters
15737    as well.  PARM is a parameter to a template function, or a
15738    subcomponent of that parameter; ARG is the corresponding argument.
15739    This function attempts to match PARM with ARG in a manner
15740    consistent with the existing assignments in TARGS.  If more values
15741    are deduced, then TARGS is updated.
15742
15743    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15744    parameter STRICT is a bitwise or of the following flags:
15745
15746      UNIFY_ALLOW_NONE:
15747        Require an exact match between PARM and ARG.
15748      UNIFY_ALLOW_MORE_CV_QUAL:
15749        Allow the deduced ARG to be more cv-qualified (by qualification
15750        conversion) than ARG.
15751      UNIFY_ALLOW_LESS_CV_QUAL:
15752        Allow the deduced ARG to be less cv-qualified than ARG.
15753      UNIFY_ALLOW_DERIVED:
15754        Allow the deduced ARG to be a template base class of ARG,
15755        or a pointer to a template base class of the type pointed to by
15756        ARG.
15757      UNIFY_ALLOW_INTEGER:
15758        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15759        case for more information.
15760      UNIFY_ALLOW_OUTER_LEVEL:
15761        This is the outermost level of a deduction. Used to determine validity
15762        of qualification conversions. A valid qualification conversion must
15763        have const qualified pointers leading up to the inner type which
15764        requires additional CV quals, except at the outer level, where const
15765        is not required [conv.qual]. It would be normal to set this flag in
15766        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15767      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15768        This is the outermost level of a deduction, and PARM can be more CV
15769        qualified at this point.
15770      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15771        This is the outermost level of a deduction, and PARM can be less CV
15772        qualified at this point.  */
15773
15774 static int
15775 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15776        bool explain_p)
15777 {
15778   int idx;
15779   tree targ;
15780   tree tparm;
15781   int strict_in = strict;
15782
15783   /* I don't think this will do the right thing with respect to types.
15784      But the only case I've seen it in so far has been array bounds, where
15785      signedness is the only information lost, and I think that will be
15786      okay.  */
15787   while (TREE_CODE (parm) == NOP_EXPR)
15788     parm = TREE_OPERAND (parm, 0);
15789
15790   if (arg == error_mark_node)
15791     return unify_invalid (explain_p);
15792   if (arg == unknown_type_node
15793       || arg == init_list_type_node)
15794     /* We can't deduce anything from this, but we might get all the
15795        template args from other function args.  */
15796     return unify_success (explain_p);
15797
15798   /* If PARM uses template parameters, then we can't bail out here,
15799      even if ARG == PARM, since we won't record unifications for the
15800      template parameters.  We might need them if we're trying to
15801      figure out which of two things is more specialized.  */
15802   if (arg == parm && !uses_template_parms (parm))
15803     return unify_success (explain_p);
15804
15805   /* Handle init lists early, so the rest of the function can assume
15806      we're dealing with a type. */
15807   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15808     {
15809       tree elt, elttype;
15810       unsigned i;
15811       tree orig_parm = parm;
15812
15813       /* Replace T with std::initializer_list<T> for deduction.  */
15814       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15815           && flag_deduce_init_list)
15816         parm = listify (parm);
15817
15818       if (!is_std_init_list (parm))
15819         /* We can only deduce from an initializer list argument if the
15820            parameter is std::initializer_list; otherwise this is a
15821            non-deduced context. */
15822         return unify_success (explain_p);
15823
15824       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15825
15826       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15827         {
15828           int elt_strict = strict;
15829
15830           if (elt == error_mark_node)
15831             return unify_invalid (explain_p);
15832
15833           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15834             {
15835               tree type = TREE_TYPE (elt);
15836               /* It should only be possible to get here for a call.  */
15837               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15838               elt_strict |= maybe_adjust_types_for_deduction
15839                 (DEDUCE_CALL, &elttype, &type, elt);
15840               elt = type;
15841             }
15842
15843           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15844                                    explain_p);
15845         }
15846
15847       /* If the std::initializer_list<T> deduction worked, replace the
15848          deduced A with std::initializer_list<A>.  */
15849       if (orig_parm != parm)
15850         {
15851           idx = TEMPLATE_TYPE_IDX (orig_parm);
15852           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15853           targ = listify (targ);
15854           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15855         }
15856       return unify_success (explain_p);
15857     }
15858
15859   /* Immediately reject some pairs that won't unify because of
15860      cv-qualification mismatches.  */
15861   if (TREE_CODE (arg) == TREE_CODE (parm)
15862       && TYPE_P (arg)
15863       /* It is the elements of the array which hold the cv quals of an array
15864          type, and the elements might be template type parms. We'll check
15865          when we recurse.  */
15866       && TREE_CODE (arg) != ARRAY_TYPE
15867       /* We check the cv-qualifiers when unifying with template type
15868          parameters below.  We want to allow ARG `const T' to unify with
15869          PARM `T' for example, when computing which of two templates
15870          is more specialized, for example.  */
15871       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15872       && !check_cv_quals_for_unify (strict_in, arg, parm))
15873     return unify_cv_qual_mismatch (explain_p, parm, arg);
15874
15875   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15876       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15877     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15878   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15879   strict &= ~UNIFY_ALLOW_DERIVED;
15880   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15881   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15882
15883   switch (TREE_CODE (parm))
15884     {
15885     case TYPENAME_TYPE:
15886     case SCOPE_REF:
15887     case UNBOUND_CLASS_TEMPLATE:
15888       /* In a type which contains a nested-name-specifier, template
15889          argument values cannot be deduced for template parameters used
15890          within the nested-name-specifier.  */
15891       return unify_success (explain_p);
15892
15893     case TEMPLATE_TYPE_PARM:
15894     case TEMPLATE_TEMPLATE_PARM:
15895     case BOUND_TEMPLATE_TEMPLATE_PARM:
15896       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15897       if (tparm == error_mark_node)
15898         return unify_invalid (explain_p);
15899
15900       if (TEMPLATE_TYPE_LEVEL (parm)
15901           != template_decl_level (tparm))
15902         /* The PARM is not one we're trying to unify.  Just check
15903            to see if it matches ARG.  */
15904         {
15905           if (TREE_CODE (arg) == TREE_CODE (parm)
15906               && same_type_p (parm, arg))
15907             return unify_success (explain_p);
15908           else
15909             return unify_type_mismatch (explain_p, parm, arg);
15910         }
15911       idx = TEMPLATE_TYPE_IDX (parm);
15912       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15913       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15914
15915       /* Check for mixed types and values.  */
15916       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15917            && TREE_CODE (tparm) != TYPE_DECL)
15918           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15919               && TREE_CODE (tparm) != TEMPLATE_DECL))
15920         gcc_unreachable ();
15921
15922       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15923         {
15924           /* ARG must be constructed from a template class or a template
15925              template parameter.  */
15926           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15927               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15928             return unify_template_deduction_failure (explain_p, parm, arg);
15929
15930           {
15931             tree parmvec = TYPE_TI_ARGS (parm);
15932             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15933             tree full_argvec = add_to_template_args (targs, argvec);
15934             tree parm_parms 
15935               = DECL_INNERMOST_TEMPLATE_PARMS
15936                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15937             int i, len;
15938             int parm_variadic_p = 0;
15939
15940             /* The resolution to DR150 makes clear that default
15941                arguments for an N-argument may not be used to bind T
15942                to a template template parameter with fewer than N
15943                parameters.  It is not safe to permit the binding of
15944                default arguments as an extension, as that may change
15945                the meaning of a conforming program.  Consider:
15946
15947                   struct Dense { static const unsigned int dim = 1; };
15948
15949                   template <template <typename> class View,
15950                             typename Block>
15951                   void operator+(float, View<Block> const&);
15952
15953                   template <typename Block,
15954                             unsigned int Dim = Block::dim>
15955                   struct Lvalue_proxy { operator float() const; };
15956
15957                   void
15958                   test_1d (void) {
15959                     Lvalue_proxy<Dense> p;
15960                     float b;
15961                     b + p;
15962                   }
15963
15964               Here, if Lvalue_proxy is permitted to bind to View, then
15965               the global operator+ will be used; if they are not, the
15966               Lvalue_proxy will be converted to float.  */
15967             if (coerce_template_parms (parm_parms,
15968                                        full_argvec,
15969                                        TYPE_TI_TEMPLATE (parm),
15970                                        (explain_p
15971                                         ? tf_warning_or_error
15972                                         : tf_none),
15973                                        /*require_all_args=*/true,
15974                                        /*use_default_args=*/false)
15975                 == error_mark_node)
15976               return 1;
15977
15978             /* Deduce arguments T, i from TT<T> or TT<i>.
15979                We check each element of PARMVEC and ARGVEC individually
15980                rather than the whole TREE_VEC since they can have
15981                different number of elements.  */
15982
15983             parmvec = expand_template_argument_pack (parmvec);
15984             argvec = expand_template_argument_pack (argvec);
15985
15986             len = TREE_VEC_LENGTH (parmvec);
15987
15988             /* Check if the parameters end in a pack, making them
15989                variadic.  */
15990             if (len > 0
15991                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15992               parm_variadic_p = 1;
15993             
15994             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15995               return unify_too_few_arguments (explain_p,
15996                                               TREE_VEC_LENGTH (argvec), len);
15997
15998              for (i = 0; i < len - parm_variadic_p; ++i)
15999               {
16000                 RECUR_AND_CHECK_FAILURE (tparms, targs,
16001                                          TREE_VEC_ELT (parmvec, i),
16002                                          TREE_VEC_ELT (argvec, i),
16003                                          UNIFY_ALLOW_NONE, explain_p);
16004               }
16005
16006             if (parm_variadic_p
16007                 && unify_pack_expansion (tparms, targs,
16008                                          parmvec, argvec,
16009                                          DEDUCE_EXACT,
16010                                          /*subr=*/true, explain_p))
16011               return 1;
16012           }
16013           arg = TYPE_TI_TEMPLATE (arg);
16014
16015           /* Fall through to deduce template name.  */
16016         }
16017
16018       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16019           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16020         {
16021           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16022
16023           /* Simple cases: Value already set, does match or doesn't.  */
16024           if (targ != NULL_TREE && template_args_equal (targ, arg))
16025             return unify_success (explain_p);
16026           else if (targ)
16027             return unify_inconsistency (explain_p, parm, targ, arg);
16028         }
16029       else
16030         {
16031           /* If PARM is `const T' and ARG is only `int', we don't have
16032              a match unless we are allowing additional qualification.
16033              If ARG is `const int' and PARM is just `T' that's OK;
16034              that binds `const int' to `T'.  */
16035           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16036                                          arg, parm))
16037             return unify_cv_qual_mismatch (explain_p, parm, arg);
16038
16039           /* Consider the case where ARG is `const volatile int' and
16040              PARM is `const T'.  Then, T should be `volatile int'.  */
16041           arg = cp_build_qualified_type_real
16042             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16043           if (arg == error_mark_node)
16044             return unify_invalid (explain_p);
16045
16046           /* Simple cases: Value already set, does match or doesn't.  */
16047           if (targ != NULL_TREE && same_type_p (targ, arg))
16048             return unify_success (explain_p);
16049           else if (targ)
16050             return unify_inconsistency (explain_p, parm, targ, arg);
16051
16052           /* Make sure that ARG is not a variable-sized array.  (Note
16053              that were talking about variable-sized arrays (like
16054              `int[n]'), rather than arrays of unknown size (like
16055              `int[]').)  We'll get very confused by such a type since
16056              the bound of the array is not constant, and therefore
16057              not mangleable.  Besides, such types are not allowed in
16058              ISO C++, so we can do as we please here.  We do allow
16059              them for 'auto' deduction, since that isn't ABI-exposed.  */
16060           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16061             return unify_vla_arg (explain_p, arg);
16062
16063           /* Strip typedefs as in convert_template_argument.  */
16064           arg = canonicalize_type_argument (arg, tf_none);
16065         }
16066
16067       /* If ARG is a parameter pack or an expansion, we cannot unify
16068          against it unless PARM is also a parameter pack.  */
16069       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16070           && !template_parameter_pack_p (parm))
16071         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16072
16073       /* If the argument deduction results is a METHOD_TYPE,
16074          then there is a problem.
16075          METHOD_TYPE doesn't map to any real C++ type the result of
16076          the deduction can not be of that type.  */
16077       if (TREE_CODE (arg) == METHOD_TYPE)
16078         return unify_method_type_error (explain_p, arg);
16079
16080       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16081       return unify_success (explain_p);
16082
16083     case TEMPLATE_PARM_INDEX:
16084       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16085       if (tparm == error_mark_node)
16086         return unify_invalid (explain_p);
16087
16088       if (TEMPLATE_PARM_LEVEL (parm)
16089           != template_decl_level (tparm))
16090         {
16091           /* The PARM is not one we're trying to unify.  Just check
16092              to see if it matches ARG.  */
16093           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16094                          && cp_tree_equal (parm, arg));
16095           if (result)
16096             unify_expression_unequal (explain_p, parm, arg);
16097           return result;
16098         }
16099
16100       idx = TEMPLATE_PARM_IDX (parm);
16101       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16102
16103       if (targ)
16104         {
16105           int x = !cp_tree_equal (targ, arg);
16106           if (x)
16107             unify_inconsistency (explain_p, parm, targ, arg);
16108           return x;
16109         }
16110
16111       /* [temp.deduct.type] If, in the declaration of a function template
16112          with a non-type template-parameter, the non-type
16113          template-parameter is used in an expression in the function
16114          parameter-list and, if the corresponding template-argument is
16115          deduced, the template-argument type shall match the type of the
16116          template-parameter exactly, except that a template-argument
16117          deduced from an array bound may be of any integral type.
16118          The non-type parameter might use already deduced type parameters.  */
16119       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16120       if (!TREE_TYPE (arg))
16121         /* Template-parameter dependent expression.  Just accept it for now.
16122            It will later be processed in convert_template_argument.  */
16123         ;
16124       else if (same_type_p (TREE_TYPE (arg), tparm))
16125         /* OK */;
16126       else if ((strict & UNIFY_ALLOW_INTEGER)
16127                && (TREE_CODE (tparm) == INTEGER_TYPE
16128                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16129         /* Convert the ARG to the type of PARM; the deduced non-type
16130            template argument must exactly match the types of the
16131            corresponding parameter.  */
16132         arg = fold (build_nop (tparm, arg));
16133       else if (uses_template_parms (tparm))
16134         /* We haven't deduced the type of this parameter yet.  Try again
16135            later.  */
16136         return unify_success (explain_p);
16137       else
16138         return unify_type_mismatch (explain_p, tparm, arg);
16139
16140       /* If ARG is a parameter pack or an expansion, we cannot unify
16141          against it unless PARM is also a parameter pack.  */
16142       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16143           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16144         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16145
16146       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16147       return unify_success (explain_p);
16148
16149     case PTRMEM_CST:
16150      {
16151         /* A pointer-to-member constant can be unified only with
16152          another constant.  */
16153       if (TREE_CODE (arg) != PTRMEM_CST)
16154         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16155
16156       /* Just unify the class member. It would be useless (and possibly
16157          wrong, depending on the strict flags) to unify also
16158          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16159          arg refer to the same variable, even if through different
16160          classes. For instance:
16161
16162          struct A { int x; };
16163          struct B : A { };
16164
16165          Unification of &A::x and &B::x must succeed.  */
16166       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16167                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16168      }
16169
16170     case POINTER_TYPE:
16171       {
16172         if (TREE_CODE (arg) != POINTER_TYPE)
16173           return unify_type_mismatch (explain_p, parm, arg);
16174
16175         /* [temp.deduct.call]
16176
16177            A can be another pointer or pointer to member type that can
16178            be converted to the deduced A via a qualification
16179            conversion (_conv.qual_).
16180
16181            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16182            This will allow for additional cv-qualification of the
16183            pointed-to types if appropriate.  */
16184
16185         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16186           /* The derived-to-base conversion only persists through one
16187              level of pointers.  */
16188           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16189
16190         return unify (tparms, targs, TREE_TYPE (parm),
16191                       TREE_TYPE (arg), strict, explain_p);
16192       }
16193
16194     case REFERENCE_TYPE:
16195       if (TREE_CODE (arg) != REFERENCE_TYPE)
16196         return unify_type_mismatch (explain_p, parm, arg);
16197       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16198                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16199
16200     case ARRAY_TYPE:
16201       if (TREE_CODE (arg) != ARRAY_TYPE)
16202         return unify_type_mismatch (explain_p, parm, arg);
16203       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16204           != (TYPE_DOMAIN (arg) == NULL_TREE))
16205         return unify_type_mismatch (explain_p, parm, arg);
16206       if (TYPE_DOMAIN (parm) != NULL_TREE)
16207         {
16208           tree parm_max;
16209           tree arg_max;
16210           bool parm_cst;
16211           bool arg_cst;
16212
16213           /* Our representation of array types uses "N - 1" as the
16214              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16215              not an integer constant.  We cannot unify arbitrarily
16216              complex expressions, so we eliminate the MINUS_EXPRs
16217              here.  */
16218           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16219           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16220           if (!parm_cst)
16221             {
16222               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16223               parm_max = TREE_OPERAND (parm_max, 0);
16224             }
16225           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16226           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16227           if (!arg_cst)
16228             {
16229               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16230                  trying to unify the type of a variable with the type
16231                  of a template parameter.  For example:
16232
16233                    template <unsigned int N>
16234                    void f (char (&) [N]);
16235                    int g(); 
16236                    void h(int i) {
16237                      char a[g(i)];
16238                      f(a); 
16239                    }
16240
16241                 Here, the type of the ARG will be "int [g(i)]", and
16242                 may be a SAVE_EXPR, etc.  */
16243               if (TREE_CODE (arg_max) != MINUS_EXPR)
16244                 return unify_vla_arg (explain_p, arg);
16245               arg_max = TREE_OPERAND (arg_max, 0);
16246             }
16247
16248           /* If only one of the bounds used a MINUS_EXPR, compensate
16249              by adding one to the other bound.  */
16250           if (parm_cst && !arg_cst)
16251             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16252                                     integer_type_node,
16253                                     parm_max,
16254                                     integer_one_node);
16255           else if (arg_cst && !parm_cst)
16256             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16257                                    integer_type_node,
16258                                    arg_max,
16259                                    integer_one_node);
16260
16261           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16262                                    UNIFY_ALLOW_INTEGER, explain_p);
16263         }
16264       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16265                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16266
16267     case REAL_TYPE:
16268     case COMPLEX_TYPE:
16269     case VECTOR_TYPE:
16270     case INTEGER_TYPE:
16271     case BOOLEAN_TYPE:
16272     case ENUMERAL_TYPE:
16273     case VOID_TYPE:
16274       if (TREE_CODE (arg) != TREE_CODE (parm))
16275         return unify_type_mismatch (explain_p, parm, arg);
16276
16277       /* We have already checked cv-qualification at the top of the
16278          function.  */
16279       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16280         return unify_type_mismatch (explain_p, parm, arg);
16281
16282       /* As far as unification is concerned, this wins.  Later checks
16283          will invalidate it if necessary.  */
16284       return unify_success (explain_p);
16285
16286       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16287       /* Type INTEGER_CST can come from ordinary constant template args.  */
16288     case INTEGER_CST:
16289       while (TREE_CODE (arg) == NOP_EXPR)
16290         arg = TREE_OPERAND (arg, 0);
16291
16292       if (TREE_CODE (arg) != INTEGER_CST)
16293         return unify_template_argument_mismatch (explain_p, parm, arg);
16294       return (tree_int_cst_equal (parm, arg)
16295               ? unify_success (explain_p)
16296               : unify_template_argument_mismatch (explain_p, parm, arg));
16297
16298     case TREE_VEC:
16299       {
16300         int i, len, argslen;
16301         int parm_variadic_p = 0;
16302
16303         if (TREE_CODE (arg) != TREE_VEC)
16304           return unify_template_argument_mismatch (explain_p, parm, arg);
16305
16306         len = TREE_VEC_LENGTH (parm);
16307         argslen = TREE_VEC_LENGTH (arg);
16308
16309         /* Check for pack expansions in the parameters.  */
16310         for (i = 0; i < len; ++i)
16311           {
16312             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16313               {
16314                 if (i == len - 1)
16315                   /* We can unify against something with a trailing
16316                      parameter pack.  */
16317                   parm_variadic_p = 1;
16318                 else
16319                   /* [temp.deduct.type]/9: If the template argument list of
16320                      P contains a pack expansion that is not the last
16321                      template argument, the entire template argument list
16322                      is a non-deduced context.  */
16323                   return unify_success (explain_p);
16324               }
16325           }
16326
16327         /* If we don't have enough arguments to satisfy the parameters
16328            (not counting the pack expression at the end), or we have
16329            too many arguments for a parameter list that doesn't end in
16330            a pack expression, we can't unify.  */
16331         if (parm_variadic_p
16332             ? argslen < len - parm_variadic_p
16333             : argslen != len)
16334           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16335
16336         /* Unify all of the parameters that precede the (optional)
16337            pack expression.  */
16338         for (i = 0; i < len - parm_variadic_p; ++i)
16339           {
16340             RECUR_AND_CHECK_FAILURE (tparms, targs,
16341                                      TREE_VEC_ELT (parm, i),
16342                                      TREE_VEC_ELT (arg, i),
16343                                      UNIFY_ALLOW_NONE, explain_p);
16344           }
16345         if (parm_variadic_p)
16346           return unify_pack_expansion (tparms, targs, parm, arg,
16347                                        DEDUCE_EXACT,
16348                                        /*subr=*/true, explain_p);
16349         return unify_success (explain_p);
16350       }
16351
16352     case RECORD_TYPE:
16353     case UNION_TYPE:
16354       if (TREE_CODE (arg) != TREE_CODE (parm))
16355         return unify_type_mismatch (explain_p, parm, arg);
16356
16357       if (TYPE_PTRMEMFUNC_P (parm))
16358         {
16359           if (!TYPE_PTRMEMFUNC_P (arg))
16360             return unify_type_mismatch (explain_p, parm, arg);
16361
16362           return unify (tparms, targs,
16363                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16364                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16365                         strict, explain_p);
16366         }
16367
16368       if (CLASSTYPE_TEMPLATE_INFO (parm))
16369         {
16370           tree t = NULL_TREE;
16371
16372           if (strict_in & UNIFY_ALLOW_DERIVED)
16373             {
16374               /* First, we try to unify the PARM and ARG directly.  */
16375               t = try_class_unification (tparms, targs,
16376                                          parm, arg, explain_p);
16377
16378               if (!t)
16379                 {
16380                   /* Fallback to the special case allowed in
16381                      [temp.deduct.call]:
16382
16383                        If P is a class, and P has the form
16384                        template-id, then A can be a derived class of
16385                        the deduced A.  Likewise, if P is a pointer to
16386                        a class of the form template-id, A can be a
16387                        pointer to a derived class pointed to by the
16388                        deduced A.  */
16389                   enum template_base_result r;
16390                   r = get_template_base (tparms, targs, parm, arg,
16391                                          explain_p, &t);
16392
16393                   if (!t)
16394                     return unify_no_common_base (explain_p, r, parm, arg);
16395                 }
16396             }
16397           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16398                    && (CLASSTYPE_TI_TEMPLATE (parm)
16399                        == CLASSTYPE_TI_TEMPLATE (arg)))
16400             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16401                Then, we should unify `int' and `U'.  */
16402             t = arg;
16403           else
16404             /* There's no chance of unification succeeding.  */
16405             return unify_type_mismatch (explain_p, parm, arg);
16406
16407           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16408                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16409         }
16410       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16411         return unify_type_mismatch (explain_p, parm, arg);
16412       return unify_success (explain_p);
16413
16414     case METHOD_TYPE:
16415     case FUNCTION_TYPE:
16416       {
16417         unsigned int nargs;
16418         tree *args;
16419         tree a;
16420         unsigned int i;
16421
16422         if (TREE_CODE (arg) != TREE_CODE (parm))
16423           return unify_type_mismatch (explain_p, parm, arg);
16424
16425         /* CV qualifications for methods can never be deduced, they must
16426            match exactly.  We need to check them explicitly here,
16427            because type_unification_real treats them as any other
16428            cv-qualified parameter.  */
16429         if (TREE_CODE (parm) == METHOD_TYPE
16430             && (!check_cv_quals_for_unify
16431                 (UNIFY_ALLOW_NONE,
16432                  class_of_this_parm (arg),
16433                  class_of_this_parm (parm))))
16434           return unify_cv_qual_mismatch (explain_p, parm, arg);
16435
16436         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16437                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16438
16439         nargs = list_length (TYPE_ARG_TYPES (arg));
16440         args = XALLOCAVEC (tree, nargs);
16441         for (a = TYPE_ARG_TYPES (arg), i = 0;
16442              a != NULL_TREE && a != void_list_node;
16443              a = TREE_CHAIN (a), ++i)
16444           args[i] = TREE_VALUE (a);
16445         nargs = i;
16446
16447         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16448                                       args, nargs, 1, DEDUCE_EXACT,
16449                                       LOOKUP_NORMAL, explain_p);
16450       }
16451
16452     case OFFSET_TYPE:
16453       /* Unify a pointer to member with a pointer to member function, which
16454          deduces the type of the member as a function type. */
16455       if (TYPE_PTRMEMFUNC_P (arg))
16456         {
16457           tree method_type;
16458           tree fntype;
16459
16460           /* Check top-level cv qualifiers */
16461           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16462             return unify_cv_qual_mismatch (explain_p, parm, arg);
16463
16464           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16465                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16466                                    UNIFY_ALLOW_NONE, explain_p);
16467
16468           /* Determine the type of the function we are unifying against. */
16469           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16470           fntype =
16471             build_function_type (TREE_TYPE (method_type),
16472                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16473
16474           /* Extract the cv-qualifiers of the member function from the
16475              implicit object parameter and place them on the function
16476              type to be restored later. */
16477           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16478           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16479         }
16480
16481       if (TREE_CODE (arg) != OFFSET_TYPE)
16482         return unify_type_mismatch (explain_p, parm, arg);
16483       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16484                                TYPE_OFFSET_BASETYPE (arg),
16485                                UNIFY_ALLOW_NONE, explain_p);
16486       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16487                     strict, explain_p);
16488
16489     case CONST_DECL:
16490       if (DECL_TEMPLATE_PARM_P (parm))
16491         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16492       if (arg != integral_constant_value (parm))
16493         return unify_template_argument_mismatch (explain_p, parm, arg);
16494       return unify_success (explain_p);
16495
16496     case FIELD_DECL:
16497     case TEMPLATE_DECL:
16498       /* Matched cases are handled by the ARG == PARM test above.  */
16499       return unify_template_argument_mismatch (explain_p, parm, arg);
16500
16501     case VAR_DECL:
16502       /* A non-type template parameter that is a variable should be a
16503          an integral constant, in which case, it whould have been
16504          folded into its (constant) value. So we should not be getting
16505          a variable here.  */
16506       gcc_unreachable ();
16507
16508     case TYPE_ARGUMENT_PACK:
16509     case NONTYPE_ARGUMENT_PACK:
16510       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16511                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16512
16513     case TYPEOF_TYPE:
16514     case DECLTYPE_TYPE:
16515     case UNDERLYING_TYPE:
16516       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16517          or UNDERLYING_TYPE nodes.  */
16518       return unify_success (explain_p);
16519
16520     case ERROR_MARK:
16521       /* Unification fails if we hit an error node.  */
16522       return unify_invalid (explain_p);
16523
16524     default:
16525       /* An unresolved overload is a nondeduced context.  */
16526       if (type_unknown_p (parm))
16527         return unify_success (explain_p);
16528       gcc_assert (EXPR_P (parm));
16529
16530       /* We must be looking at an expression.  This can happen with
16531          something like:
16532
16533            template <int I>
16534            void foo(S<I>, S<I + 2>);
16535
16536          This is a "nondeduced context":
16537
16538            [deduct.type]
16539
16540            The nondeduced contexts are:
16541
16542            --A type that is a template-id in which one or more of
16543              the template-arguments is an expression that references
16544              a template-parameter.
16545
16546          In these cases, we assume deduction succeeded, but don't
16547          actually infer any unifications.  */
16548
16549       if (!uses_template_parms (parm)
16550           && !template_args_equal (parm, arg))
16551         return unify_expression_unequal (explain_p, parm, arg);
16552       else
16553         return unify_success (explain_p);
16554     }
16555 }
16556 #undef RECUR_AND_CHECK_FAILURE
16557 \f
16558 /* Note that DECL can be defined in this translation unit, if
16559    required.  */
16560
16561 static void
16562 mark_definable (tree decl)
16563 {
16564   tree clone;
16565   DECL_NOT_REALLY_EXTERN (decl) = 1;
16566   FOR_EACH_CLONE (clone, decl)
16567     DECL_NOT_REALLY_EXTERN (clone) = 1;
16568 }
16569
16570 /* Called if RESULT is explicitly instantiated, or is a member of an
16571    explicitly instantiated class.  */
16572
16573 void
16574 mark_decl_instantiated (tree result, int extern_p)
16575 {
16576   SET_DECL_EXPLICIT_INSTANTIATION (result);
16577
16578   /* If this entity has already been written out, it's too late to
16579      make any modifications.  */
16580   if (TREE_ASM_WRITTEN (result))
16581     return;
16582
16583   if (TREE_CODE (result) != FUNCTION_DECL)
16584     /* The TREE_PUBLIC flag for function declarations will have been
16585        set correctly by tsubst.  */
16586     TREE_PUBLIC (result) = 1;
16587
16588   /* This might have been set by an earlier implicit instantiation.  */
16589   DECL_COMDAT (result) = 0;
16590
16591   if (extern_p)
16592     DECL_NOT_REALLY_EXTERN (result) = 0;
16593   else
16594     {
16595       mark_definable (result);
16596       /* Always make artificials weak.  */
16597       if (DECL_ARTIFICIAL (result) && flag_weak)
16598         comdat_linkage (result);
16599       /* For WIN32 we also want to put explicit instantiations in
16600          linkonce sections.  */
16601       else if (TREE_PUBLIC (result))
16602         maybe_make_one_only (result);
16603     }
16604
16605   /* If EXTERN_P, then this function will not be emitted -- unless
16606      followed by an explicit instantiation, at which point its linkage
16607      will be adjusted.  If !EXTERN_P, then this function will be
16608      emitted here.  In neither circumstance do we want
16609      import_export_decl to adjust the linkage.  */
16610   DECL_INTERFACE_KNOWN (result) = 1;
16611 }
16612
16613 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16614    important template arguments.  If any are missing, we check whether
16615    they're important by using error_mark_node for substituting into any
16616    args that were used for partial ordering (the ones between ARGS and END)
16617    and seeing if it bubbles up.  */
16618
16619 static bool
16620 check_undeduced_parms (tree targs, tree args, tree end)
16621 {
16622   bool found = false;
16623   int i;
16624   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16625     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16626       {
16627         found = true;
16628         TREE_VEC_ELT (targs, i) = error_mark_node;
16629       }
16630   if (found)
16631     {
16632       for (; args != end; args = TREE_CHAIN (args))
16633         {
16634           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16635           if (substed == error_mark_node)
16636             return true;
16637         }
16638     }
16639   return false;
16640 }
16641
16642 /* Given two function templates PAT1 and PAT2, return:
16643
16644    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16645    -1 if PAT2 is more specialized than PAT1.
16646    0 if neither is more specialized.
16647
16648    LEN indicates the number of parameters we should consider
16649    (defaulted parameters should not be considered).
16650
16651    The 1998 std underspecified function template partial ordering, and
16652    DR214 addresses the issue.  We take pairs of arguments, one from
16653    each of the templates, and deduce them against each other.  One of
16654    the templates will be more specialized if all the *other*
16655    template's arguments deduce against its arguments and at least one
16656    of its arguments *does* *not* deduce against the other template's
16657    corresponding argument.  Deduction is done as for class templates.
16658    The arguments used in deduction have reference and top level cv
16659    qualifiers removed.  Iff both arguments were originally reference
16660    types *and* deduction succeeds in both directions, the template
16661    with the more cv-qualified argument wins for that pairing (if
16662    neither is more cv-qualified, they both are equal).  Unlike regular
16663    deduction, after all the arguments have been deduced in this way,
16664    we do *not* verify the deduced template argument values can be
16665    substituted into non-deduced contexts.
16666
16667    The logic can be a bit confusing here, because we look at deduce1 and
16668    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16669    can find template arguments for pat1 to make arg1 look like arg2, that
16670    means that arg2 is at least as specialized as arg1.  */
16671
16672 int
16673 more_specialized_fn (tree pat1, tree pat2, int len)
16674 {
16675   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16676   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16677   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16678   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16679   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16680   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16681   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16682   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16683   tree origs1, origs2;
16684   bool lose1 = false;
16685   bool lose2 = false;
16686
16687   /* Remove the this parameter from non-static member functions.  If
16688      one is a non-static member function and the other is not a static
16689      member function, remove the first parameter from that function
16690      also.  This situation occurs for operator functions where we
16691      locate both a member function (with this pointer) and non-member
16692      operator (with explicit first operand).  */
16693   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16694     {
16695       len--; /* LEN is the number of significant arguments for DECL1 */
16696       args1 = TREE_CHAIN (args1);
16697       if (!DECL_STATIC_FUNCTION_P (decl2))
16698         args2 = TREE_CHAIN (args2);
16699     }
16700   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16701     {
16702       args2 = TREE_CHAIN (args2);
16703       if (!DECL_STATIC_FUNCTION_P (decl1))
16704         {
16705           len--;
16706           args1 = TREE_CHAIN (args1);
16707         }
16708     }
16709
16710   /* If only one is a conversion operator, they are unordered.  */
16711   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16712     return 0;
16713
16714   /* Consider the return type for a conversion function */
16715   if (DECL_CONV_FN_P (decl1))
16716     {
16717       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16718       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16719       len++;
16720     }
16721
16722   processing_template_decl++;
16723
16724   origs1 = args1;
16725   origs2 = args2;
16726
16727   while (len--
16728          /* Stop when an ellipsis is seen.  */
16729          && args1 != NULL_TREE && args2 != NULL_TREE)
16730     {
16731       tree arg1 = TREE_VALUE (args1);
16732       tree arg2 = TREE_VALUE (args2);
16733       int deduce1, deduce2;
16734       int quals1 = -1;
16735       int quals2 = -1;
16736
16737       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16738           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16739         {
16740           /* When both arguments are pack expansions, we need only
16741              unify the patterns themselves.  */
16742           arg1 = PACK_EXPANSION_PATTERN (arg1);
16743           arg2 = PACK_EXPANSION_PATTERN (arg2);
16744
16745           /* This is the last comparison we need to do.  */
16746           len = 0;
16747         }
16748
16749       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16750         {
16751           arg1 = TREE_TYPE (arg1);
16752           quals1 = cp_type_quals (arg1);
16753         }
16754
16755       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16756         {
16757           arg2 = TREE_TYPE (arg2);
16758           quals2 = cp_type_quals (arg2);
16759         }
16760
16761       if ((quals1 < 0) != (quals2 < 0))
16762         {
16763           /* Only of the args is a reference, see if we should apply
16764              array/function pointer decay to it.  This is not part of
16765              DR214, but is, IMHO, consistent with the deduction rules
16766              for the function call itself, and with our earlier
16767              implementation of the underspecified partial ordering
16768              rules.  (nathan).  */
16769           if (quals1 >= 0)
16770             {
16771               switch (TREE_CODE (arg1))
16772                 {
16773                 case ARRAY_TYPE:
16774                   arg1 = TREE_TYPE (arg1);
16775                   /* FALLTHROUGH. */
16776                 case FUNCTION_TYPE:
16777                   arg1 = build_pointer_type (arg1);
16778                   break;
16779
16780                 default:
16781                   break;
16782                 }
16783             }
16784           else
16785             {
16786               switch (TREE_CODE (arg2))
16787                 {
16788                 case ARRAY_TYPE:
16789                   arg2 = TREE_TYPE (arg2);
16790                   /* FALLTHROUGH. */
16791                 case FUNCTION_TYPE:
16792                   arg2 = build_pointer_type (arg2);
16793                   break;
16794
16795                 default:
16796                   break;
16797                 }
16798             }
16799         }
16800
16801       arg1 = TYPE_MAIN_VARIANT (arg1);
16802       arg2 = TYPE_MAIN_VARIANT (arg2);
16803
16804       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16805         {
16806           int i, len2 = list_length (args2);
16807           tree parmvec = make_tree_vec (1);
16808           tree argvec = make_tree_vec (len2);
16809           tree ta = args2;
16810
16811           /* Setup the parameter vector, which contains only ARG1.  */
16812           TREE_VEC_ELT (parmvec, 0) = arg1;
16813
16814           /* Setup the argument vector, which contains the remaining
16815              arguments.  */
16816           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16817             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16818
16819           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16820                                            argvec, DEDUCE_EXACT,
16821                                            /*subr=*/true, /*explain_p=*/false)
16822                      == 0);
16823
16824           /* We cannot deduce in the other direction, because ARG1 is
16825              a pack expansion but ARG2 is not.  */
16826           deduce2 = 0;
16827         }
16828       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16829         {
16830           int i, len1 = list_length (args1);
16831           tree parmvec = make_tree_vec (1);
16832           tree argvec = make_tree_vec (len1);
16833           tree ta = args1;
16834
16835           /* Setup the parameter vector, which contains only ARG1.  */
16836           TREE_VEC_ELT (parmvec, 0) = arg2;
16837
16838           /* Setup the argument vector, which contains the remaining
16839              arguments.  */
16840           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16841             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16842
16843           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16844                                            argvec, DEDUCE_EXACT,
16845                                            /*subr=*/true, /*explain_p=*/false)
16846                      == 0);
16847
16848           /* We cannot deduce in the other direction, because ARG2 is
16849              a pack expansion but ARG1 is not.*/
16850           deduce1 = 0;
16851         }
16852
16853       else
16854         {
16855           /* The normal case, where neither argument is a pack
16856              expansion.  */
16857           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16858                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16859                      == 0);
16860           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16861                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16862                      == 0);
16863         }
16864
16865       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16866          arg2, then arg2 is not as specialized as arg1.  */
16867       if (!deduce1)
16868         lose2 = true;
16869       if (!deduce2)
16870         lose1 = true;
16871
16872       /* "If, for a given type, deduction succeeds in both directions
16873          (i.e., the types are identical after the transformations above)
16874          and if the type from the argument template is more cv-qualified
16875          than the type from the parameter template (as described above)
16876          that type is considered to be more specialized than the other. If
16877          neither type is more cv-qualified than the other then neither type
16878          is more specialized than the other."  */
16879
16880       if (deduce1 && deduce2
16881           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16882         {
16883           if ((quals1 & quals2) == quals2)
16884             lose2 = true;
16885           if ((quals1 & quals2) == quals1)
16886             lose1 = true;
16887         }
16888
16889       if (lose1 && lose2)
16890         /* We've failed to deduce something in either direction.
16891            These must be unordered.  */
16892         break;
16893
16894       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16895           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16896         /* We have already processed all of the arguments in our
16897            handing of the pack expansion type.  */
16898         len = 0;
16899
16900       args1 = TREE_CHAIN (args1);
16901       args2 = TREE_CHAIN (args2);
16902     }
16903
16904   /* "In most cases, all template parameters must have values in order for
16905      deduction to succeed, but for partial ordering purposes a template
16906      parameter may remain without a value provided it is not used in the
16907      types being used for partial ordering."
16908
16909      Thus, if we are missing any of the targs1 we need to substitute into
16910      origs1, then pat2 is not as specialized as pat1.  This can happen when
16911      there is a nondeduced context.  */
16912   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16913     lose2 = true;
16914   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16915     lose1 = true;
16916
16917   processing_template_decl--;
16918
16919   /* All things being equal, if the next argument is a pack expansion
16920      for one function but not for the other, prefer the
16921      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16922   if (lose1 == lose2
16923       && args1 && TREE_VALUE (args1)
16924       && args2 && TREE_VALUE (args2))
16925     {
16926       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16927       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16928     }
16929
16930   if (lose1 == lose2)
16931     return 0;
16932   else if (!lose1)
16933     return 1;
16934   else
16935     return -1;
16936 }
16937
16938 /* Determine which of two partial specializations is more specialized.
16939
16940    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16941    to the first partial specialization.  The TREE_VALUE is the
16942    innermost set of template parameters for the partial
16943    specialization.  PAT2 is similar, but for the second template.
16944
16945    Return 1 if the first partial specialization is more specialized;
16946    -1 if the second is more specialized; 0 if neither is more
16947    specialized.
16948
16949    See [temp.class.order] for information about determining which of
16950    two templates is more specialized.  */
16951
16952 static int
16953 more_specialized_class (tree pat1, tree pat2)
16954 {
16955   tree targs;
16956   tree tmpl1, tmpl2;
16957   int winner = 0;
16958   bool any_deductions = false;
16959
16960   tmpl1 = TREE_TYPE (pat1);
16961   tmpl2 = TREE_TYPE (pat2);
16962
16963   /* Just like what happens for functions, if we are ordering between
16964      different class template specializations, we may encounter dependent
16965      types in the arguments, and we need our dependency check functions
16966      to behave correctly.  */
16967   ++processing_template_decl;
16968   targs = get_class_bindings (TREE_VALUE (pat1),
16969                               CLASSTYPE_TI_ARGS (tmpl1),
16970                               CLASSTYPE_TI_ARGS (tmpl2));
16971   if (targs)
16972     {
16973       --winner;
16974       any_deductions = true;
16975     }
16976
16977   targs = get_class_bindings (TREE_VALUE (pat2),
16978                               CLASSTYPE_TI_ARGS (tmpl2),
16979                               CLASSTYPE_TI_ARGS (tmpl1));
16980   if (targs)
16981     {
16982       ++winner;
16983       any_deductions = true;
16984     }
16985   --processing_template_decl;
16986
16987   /* In the case of a tie where at least one of the class templates
16988      has a parameter pack at the end, the template with the most
16989      non-packed parameters wins.  */
16990   if (winner == 0
16991       && any_deductions
16992       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16993           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16994     {
16995       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16996       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16997       int len1 = TREE_VEC_LENGTH (args1);
16998       int len2 = TREE_VEC_LENGTH (args2);
16999
17000       /* We don't count the pack expansion at the end.  */
17001       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
17002         --len1;
17003       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
17004         --len2;
17005
17006       if (len1 > len2)
17007         return 1;
17008       else if (len1 < len2)
17009         return -1;
17010     }
17011
17012   return winner;
17013 }
17014
17015 /* Return the template arguments that will produce the function signature
17016    DECL from the function template FN, with the explicit template
17017    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17018    also match.  Return NULL_TREE if no satisfactory arguments could be
17019    found.  */
17020
17021 static tree
17022 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17023 {
17024   int ntparms = DECL_NTPARMS (fn);
17025   tree targs = make_tree_vec (ntparms);
17026   tree decl_type;
17027   tree decl_arg_types;
17028   tree *args;
17029   unsigned int nargs, ix;
17030   tree arg;
17031
17032   /* Substitute the explicit template arguments into the type of DECL.
17033      The call to fn_type_unification will handle substitution into the
17034      FN.  */
17035   decl_type = TREE_TYPE (decl);
17036   if (explicit_args && uses_template_parms (decl_type))
17037     {
17038       tree tmpl;
17039       tree converted_args;
17040
17041       if (DECL_TEMPLATE_INFO (decl))
17042         tmpl = DECL_TI_TEMPLATE (decl);
17043       else
17044         /* We can get here for some invalid specializations.  */
17045         return NULL_TREE;
17046
17047       converted_args
17048         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17049                                  explicit_args, NULL_TREE,
17050                                  tf_none,
17051                                  /*require_all_args=*/false,
17052                                  /*use_default_args=*/false);
17053       if (converted_args == error_mark_node)
17054         return NULL_TREE;
17055
17056       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17057       if (decl_type == error_mark_node)
17058         return NULL_TREE;
17059     }
17060
17061   /* Never do unification on the 'this' parameter.  */
17062   decl_arg_types = skip_artificial_parms_for (decl, 
17063                                               TYPE_ARG_TYPES (decl_type));
17064
17065   nargs = list_length (decl_arg_types);
17066   args = XALLOCAVEC (tree, nargs);
17067   for (arg = decl_arg_types, ix = 0;
17068        arg != NULL_TREE && arg != void_list_node;
17069        arg = TREE_CHAIN (arg), ++ix)
17070     args[ix] = TREE_VALUE (arg);
17071
17072   if (fn_type_unification (fn, explicit_args, targs,
17073                            args, ix,
17074                            (check_rettype || DECL_CONV_FN_P (fn)
17075                             ? TREE_TYPE (decl_type) : NULL_TREE),
17076                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17077     return NULL_TREE;
17078
17079   return targs;
17080 }
17081
17082 /* Return the innermost template arguments that, when applied to a
17083    template specialization whose innermost template parameters are
17084    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17085    ARGS.
17086
17087    For example, suppose we have:
17088
17089      template <class T, class U> struct S {};
17090      template <class T> struct S<T*, int> {};
17091
17092    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17093    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17094    int}.  The resulting vector will be {double}, indicating that `T'
17095    is bound to `double'.  */
17096
17097 static tree
17098 get_class_bindings (tree tparms, tree spec_args, tree args)
17099 {
17100   int i, ntparms = TREE_VEC_LENGTH (tparms);
17101   tree deduced_args;
17102   tree innermost_deduced_args;
17103
17104   innermost_deduced_args = make_tree_vec (ntparms);
17105   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17106     {
17107       deduced_args = copy_node (args);
17108       SET_TMPL_ARGS_LEVEL (deduced_args,
17109                            TMPL_ARGS_DEPTH (deduced_args),
17110                            innermost_deduced_args);
17111     }
17112   else
17113     deduced_args = innermost_deduced_args;
17114
17115   if (unify (tparms, deduced_args,
17116              INNERMOST_TEMPLATE_ARGS (spec_args),
17117              INNERMOST_TEMPLATE_ARGS (args),
17118              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17119     return NULL_TREE;
17120
17121   for (i =  0; i < ntparms; ++i)
17122     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17123       return NULL_TREE;
17124
17125   /* Verify that nondeduced template arguments agree with the type
17126      obtained from argument deduction.
17127
17128      For example:
17129
17130        struct A { typedef int X; };
17131        template <class T, class U> struct C {};
17132        template <class T> struct C<T, typename T::X> {};
17133
17134      Then with the instantiation `C<A, int>', we can deduce that
17135      `T' is `A' but unify () does not check whether `typename T::X'
17136      is `int'.  */
17137   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17138   if (spec_args == error_mark_node
17139       /* We only need to check the innermost arguments; the other
17140          arguments will always agree.  */
17141       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17142                               INNERMOST_TEMPLATE_ARGS (args)))
17143     return NULL_TREE;
17144
17145   /* Now that we have bindings for all of the template arguments,
17146      ensure that the arguments deduced for the template template
17147      parameters have compatible template parameter lists.  See the use
17148      of template_template_parm_bindings_ok_p in fn_type_unification
17149      for more information.  */
17150   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17151     return NULL_TREE;
17152
17153   return deduced_args;
17154 }
17155
17156 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17157    Return the TREE_LIST node with the most specialized template, if
17158    any.  If there is no most specialized template, the error_mark_node
17159    is returned.
17160
17161    Note that this function does not look at, or modify, the
17162    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17163    returned is one of the elements of INSTANTIATIONS, callers may
17164    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17165    and retrieve it from the value returned.  */
17166
17167 tree
17168 most_specialized_instantiation (tree templates)
17169 {
17170   tree fn, champ;
17171
17172   ++processing_template_decl;
17173
17174   champ = templates;
17175   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17176     {
17177       int fate = 0;
17178
17179       if (get_bindings (TREE_VALUE (champ),
17180                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17181                         NULL_TREE, /*check_ret=*/true))
17182         fate--;
17183
17184       if (get_bindings (TREE_VALUE (fn),
17185                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17186                         NULL_TREE, /*check_ret=*/true))
17187         fate++;
17188
17189       if (fate == -1)
17190         champ = fn;
17191       else if (!fate)
17192         {
17193           /* Equally specialized, move to next function.  If there
17194              is no next function, nothing's most specialized.  */
17195           fn = TREE_CHAIN (fn);
17196           champ = fn;
17197           if (!fn)
17198             break;
17199         }
17200     }
17201
17202   if (champ)
17203     /* Now verify that champ is better than everything earlier in the
17204        instantiation list.  */
17205     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17206       if (get_bindings (TREE_VALUE (champ),
17207                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17208                         NULL_TREE, /*check_ret=*/true)
17209           || !get_bindings (TREE_VALUE (fn),
17210                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17211                             NULL_TREE, /*check_ret=*/true))
17212         {
17213           champ = NULL_TREE;
17214           break;
17215         }
17216
17217   processing_template_decl--;
17218
17219   if (!champ)
17220     return error_mark_node;
17221
17222   return champ;
17223 }
17224
17225 /* If DECL is a specialization of some template, return the most
17226    general such template.  Otherwise, returns NULL_TREE.
17227
17228    For example, given:
17229
17230      template <class T> struct S { template <class U> void f(U); };
17231
17232    if TMPL is `template <class U> void S<int>::f(U)' this will return
17233    the full template.  This function will not trace past partial
17234    specializations, however.  For example, given in addition:
17235
17236      template <class T> struct S<T*> { template <class U> void f(U); };
17237
17238    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17239    `template <class T> template <class U> S<T*>::f(U)'.  */
17240
17241 tree
17242 most_general_template (tree decl)
17243 {
17244   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17245      an immediate specialization.  */
17246   if (TREE_CODE (decl) == FUNCTION_DECL)
17247     {
17248       if (DECL_TEMPLATE_INFO (decl)) {
17249         decl = DECL_TI_TEMPLATE (decl);
17250
17251         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17252            template friend.  */
17253         if (TREE_CODE (decl) != TEMPLATE_DECL)
17254           return NULL_TREE;
17255       } else
17256         return NULL_TREE;
17257     }
17258
17259   /* Look for more and more general templates.  */
17260   while (DECL_TEMPLATE_INFO (decl))
17261     {
17262       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17263          (See cp-tree.h for details.)  */
17264       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17265         break;
17266
17267       if (CLASS_TYPE_P (TREE_TYPE (decl))
17268           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17269         break;
17270
17271       /* Stop if we run into an explicitly specialized class template.  */
17272       if (!DECL_NAMESPACE_SCOPE_P (decl)
17273           && DECL_CONTEXT (decl)
17274           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17275         break;
17276
17277       decl = DECL_TI_TEMPLATE (decl);
17278     }
17279
17280   return decl;
17281 }
17282
17283 /* Return the most specialized of the class template partial
17284    specializations of TMPL which can produce TYPE, a specialization of
17285    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17286    a _TYPE node corresponding to the partial specialization, while the
17287    TREE_PURPOSE is the set of template arguments that must be
17288    substituted into the TREE_TYPE in order to generate TYPE.
17289
17290    If the choice of partial specialization is ambiguous, a diagnostic
17291    is issued, and the error_mark_node is returned.  If there are no
17292    partial specializations of TMPL matching TYPE, then NULL_TREE is
17293    returned.  */
17294
17295 static tree
17296 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17297 {
17298   tree list = NULL_TREE;
17299   tree t;
17300   tree champ;
17301   int fate;
17302   bool ambiguous_p;
17303   tree args;
17304   tree outer_args = NULL_TREE;
17305
17306   tmpl = most_general_template (tmpl);
17307   args = CLASSTYPE_TI_ARGS (type);
17308
17309   /* For determining which partial specialization to use, only the
17310      innermost args are interesting.  */
17311   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17312     {
17313       outer_args = strip_innermost_template_args (args, 1);
17314       args = INNERMOST_TEMPLATE_ARGS (args);
17315     }
17316
17317   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17318     {
17319       tree partial_spec_args;
17320       tree spec_args;
17321       tree parms = TREE_VALUE (t);
17322
17323       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17324
17325       ++processing_template_decl;
17326
17327       if (outer_args)
17328         {
17329           int i;
17330
17331           /* Discard the outer levels of args, and then substitute in the
17332              template args from the enclosing class.  */
17333           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17334           partial_spec_args = tsubst_template_args
17335             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17336
17337           /* PARMS already refers to just the innermost parms, but the
17338              template parms in partial_spec_args had their levels lowered
17339              by tsubst, so we need to do the same for the parm list.  We
17340              can't just tsubst the TREE_VEC itself, as tsubst wants to
17341              treat a TREE_VEC as an argument vector.  */
17342           parms = copy_node (parms);
17343           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17344             TREE_VEC_ELT (parms, i) =
17345               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17346
17347         }
17348
17349       partial_spec_args =
17350           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17351                                  add_to_template_args (outer_args,
17352                                                        partial_spec_args),
17353                                  tmpl, tf_none,
17354                                  /*require_all_args=*/true,
17355                                  /*use_default_args=*/true);
17356
17357       --processing_template_decl;
17358
17359       if (partial_spec_args == error_mark_node)
17360         return error_mark_node;
17361
17362       spec_args = get_class_bindings (parms,
17363                                       partial_spec_args,
17364                                       args);
17365       if (spec_args)
17366         {
17367           if (outer_args)
17368             spec_args = add_to_template_args (outer_args, spec_args);
17369           list = tree_cons (spec_args, TREE_VALUE (t), list);
17370           TREE_TYPE (list) = TREE_TYPE (t);
17371         }
17372     }
17373
17374   if (! list)
17375     return NULL_TREE;
17376
17377   ambiguous_p = false;
17378   t = list;
17379   champ = t;
17380   t = TREE_CHAIN (t);
17381   for (; t; t = TREE_CHAIN (t))
17382     {
17383       fate = more_specialized_class (champ, t);
17384       if (fate == 1)
17385         ;
17386       else
17387         {
17388           if (fate == 0)
17389             {
17390               t = TREE_CHAIN (t);
17391               if (! t)
17392                 {
17393                   ambiguous_p = true;
17394                   break;
17395                 }
17396             }
17397           champ = t;
17398         }
17399     }
17400
17401   if (!ambiguous_p)
17402     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17403       {
17404         fate = more_specialized_class (champ, t);
17405         if (fate != 1)
17406           {
17407             ambiguous_p = true;
17408             break;
17409           }
17410       }
17411
17412   if (ambiguous_p)
17413     {
17414       const char *str;
17415       char *spaces = NULL;
17416       if (!(complain & tf_error))
17417         return error_mark_node;
17418       error ("ambiguous class template instantiation for %q#T", type);
17419       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17420       for (t = list; t; t = TREE_CHAIN (t))
17421         {
17422           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17423           spaces = spaces ? spaces : get_spaces (str);
17424         }
17425       free (spaces);
17426       return error_mark_node;
17427     }
17428
17429   return champ;
17430 }
17431
17432 /* Explicitly instantiate DECL.  */
17433
17434 void
17435 do_decl_instantiation (tree decl, tree storage)
17436 {
17437   tree result = NULL_TREE;
17438   int extern_p = 0;
17439
17440   if (!decl || decl == error_mark_node)
17441     /* An error occurred, for which grokdeclarator has already issued
17442        an appropriate message.  */
17443     return;
17444   else if (! DECL_LANG_SPECIFIC (decl))
17445     {
17446       error ("explicit instantiation of non-template %q#D", decl);
17447       return;
17448     }
17449   else if (TREE_CODE (decl) == VAR_DECL)
17450     {
17451       /* There is an asymmetry here in the way VAR_DECLs and
17452          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17453          the latter, the DECL we get back will be marked as a
17454          template instantiation, and the appropriate
17455          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17456          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17457          should handle VAR_DECLs as it currently handles
17458          FUNCTION_DECLs.  */
17459       if (!DECL_CLASS_SCOPE_P (decl))
17460         {
17461           error ("%qD is not a static data member of a class template", decl);
17462           return;
17463         }
17464       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17465       if (!result || TREE_CODE (result) != VAR_DECL)
17466         {
17467           error ("no matching template for %qD found", decl);
17468           return;
17469         }
17470       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17471         {
17472           error ("type %qT for explicit instantiation %qD does not match "
17473                  "declared type %qT", TREE_TYPE (result), decl,
17474                  TREE_TYPE (decl));
17475           return;
17476         }
17477     }
17478   else if (TREE_CODE (decl) != FUNCTION_DECL)
17479     {
17480       error ("explicit instantiation of %q#D", decl);
17481       return;
17482     }
17483   else
17484     result = decl;
17485
17486   /* Check for various error cases.  Note that if the explicit
17487      instantiation is valid the RESULT will currently be marked as an
17488      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17489      until we get here.  */
17490
17491   if (DECL_TEMPLATE_SPECIALIZATION (result))
17492     {
17493       /* DR 259 [temp.spec].
17494
17495          Both an explicit instantiation and a declaration of an explicit
17496          specialization shall not appear in a program unless the explicit
17497          instantiation follows a declaration of the explicit specialization.
17498
17499          For a given set of template parameters, if an explicit
17500          instantiation of a template appears after a declaration of an
17501          explicit specialization for that template, the explicit
17502          instantiation has no effect.  */
17503       return;
17504     }
17505   else if (DECL_EXPLICIT_INSTANTIATION (result))
17506     {
17507       /* [temp.spec]
17508
17509          No program shall explicitly instantiate any template more
17510          than once.
17511
17512          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17513          the first instantiation was `extern' and the second is not,
17514          and EXTERN_P for the opposite case.  */
17515       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17516         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17517       /* If an "extern" explicit instantiation follows an ordinary
17518          explicit instantiation, the template is instantiated.  */
17519       if (extern_p)
17520         return;
17521     }
17522   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17523     {
17524       error ("no matching template for %qD found", result);
17525       return;
17526     }
17527   else if (!DECL_TEMPLATE_INFO (result))
17528     {
17529       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17530       return;
17531     }
17532
17533   if (storage == NULL_TREE)
17534     ;
17535   else if (storage == ridpointers[(int) RID_EXTERN])
17536     {
17537       if (!in_system_header && (cxx_dialect == cxx98))
17538         pedwarn (input_location, OPT_pedantic, 
17539                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17540                  "instantiations");
17541       extern_p = 1;
17542     }
17543   else
17544     error ("storage class %qD applied to template instantiation", storage);
17545
17546   check_explicit_instantiation_namespace (result);
17547   mark_decl_instantiated (result, extern_p);
17548   if (! extern_p)
17549     instantiate_decl (result, /*defer_ok=*/1,
17550                       /*expl_inst_class_mem_p=*/false);
17551 }
17552
17553 static void
17554 mark_class_instantiated (tree t, int extern_p)
17555 {
17556   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17557   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17558   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17559   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17560   if (! extern_p)
17561     {
17562       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17563       rest_of_type_compilation (t, 1);
17564     }
17565 }
17566
17567 /* Called from do_type_instantiation through binding_table_foreach to
17568    do recursive instantiation for the type bound in ENTRY.  */
17569 static void
17570 bt_instantiate_type_proc (binding_entry entry, void *data)
17571 {
17572   tree storage = *(tree *) data;
17573
17574   if (MAYBE_CLASS_TYPE_P (entry->type)
17575       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17576     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17577 }
17578
17579 /* Called from do_type_instantiation to instantiate a member
17580    (a member function or a static member variable) of an
17581    explicitly instantiated class template.  */
17582 static void
17583 instantiate_class_member (tree decl, int extern_p)
17584 {
17585   mark_decl_instantiated (decl, extern_p);
17586   if (! extern_p)
17587     instantiate_decl (decl, /*defer_ok=*/1,
17588                       /*expl_inst_class_mem_p=*/true);
17589 }
17590
17591 /* Perform an explicit instantiation of template class T.  STORAGE, if
17592    non-null, is the RID for extern, inline or static.  COMPLAIN is
17593    nonzero if this is called from the parser, zero if called recursively,
17594    since the standard is unclear (as detailed below).  */
17595
17596 void
17597 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17598 {
17599   int extern_p = 0;
17600   int nomem_p = 0;
17601   int static_p = 0;
17602   int previous_instantiation_extern_p = 0;
17603
17604   if (TREE_CODE (t) == TYPE_DECL)
17605     t = TREE_TYPE (t);
17606
17607   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17608     {
17609       error ("explicit instantiation of non-template type %qT", t);
17610       return;
17611     }
17612
17613   complete_type (t);
17614
17615   if (!COMPLETE_TYPE_P (t))
17616     {
17617       if (complain & tf_error)
17618         error ("explicit instantiation of %q#T before definition of template",
17619                t);
17620       return;
17621     }
17622
17623   if (storage != NULL_TREE)
17624     {
17625       if (!in_system_header)
17626         {
17627           if (storage == ridpointers[(int) RID_EXTERN])
17628             {
17629               if (cxx_dialect == cxx98)
17630                 pedwarn (input_location, OPT_pedantic, 
17631                          "ISO C++ 1998 forbids the use of %<extern%> on "
17632                          "explicit instantiations");
17633             }
17634           else
17635             pedwarn (input_location, OPT_pedantic, 
17636                      "ISO C++ forbids the use of %qE"
17637                      " on explicit instantiations", storage);
17638         }
17639
17640       if (storage == ridpointers[(int) RID_INLINE])
17641         nomem_p = 1;
17642       else if (storage == ridpointers[(int) RID_EXTERN])
17643         extern_p = 1;
17644       else if (storage == ridpointers[(int) RID_STATIC])
17645         static_p = 1;
17646       else
17647         {
17648           error ("storage class %qD applied to template instantiation",
17649                  storage);
17650           extern_p = 0;
17651         }
17652     }
17653
17654   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17655     {
17656       /* DR 259 [temp.spec].
17657
17658          Both an explicit instantiation and a declaration of an explicit
17659          specialization shall not appear in a program unless the explicit
17660          instantiation follows a declaration of the explicit specialization.
17661
17662          For a given set of template parameters, if an explicit
17663          instantiation of a template appears after a declaration of an
17664          explicit specialization for that template, the explicit
17665          instantiation has no effect.  */
17666       return;
17667     }
17668   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17669     {
17670       /* [temp.spec]
17671
17672          No program shall explicitly instantiate any template more
17673          than once.
17674
17675          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17676          instantiation was `extern'.  If EXTERN_P then the second is.
17677          These cases are OK.  */
17678       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17679
17680       if (!previous_instantiation_extern_p && !extern_p
17681           && (complain & tf_error))
17682         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17683
17684       /* If we've already instantiated the template, just return now.  */
17685       if (!CLASSTYPE_INTERFACE_ONLY (t))
17686         return;
17687     }
17688
17689   check_explicit_instantiation_namespace (TYPE_NAME (t));
17690   mark_class_instantiated (t, extern_p);
17691
17692   if (nomem_p)
17693     return;
17694
17695   {
17696     tree tmp;
17697
17698     /* In contrast to implicit instantiation, where only the
17699        declarations, and not the definitions, of members are
17700        instantiated, we have here:
17701
17702          [temp.explicit]
17703
17704          The explicit instantiation of a class template specialization
17705          implies the instantiation of all of its members not
17706          previously explicitly specialized in the translation unit
17707          containing the explicit instantiation.
17708
17709        Of course, we can't instantiate member template classes, since
17710        we don't have any arguments for them.  Note that the standard
17711        is unclear on whether the instantiation of the members are
17712        *explicit* instantiations or not.  However, the most natural
17713        interpretation is that it should be an explicit instantiation.  */
17714
17715     if (! static_p)
17716       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17717         if (TREE_CODE (tmp) == FUNCTION_DECL
17718             && DECL_TEMPLATE_INSTANTIATION (tmp))
17719           instantiate_class_member (tmp, extern_p);
17720
17721     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17722       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17723         instantiate_class_member (tmp, extern_p);
17724
17725     if (CLASSTYPE_NESTED_UTDS (t))
17726       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17727                              bt_instantiate_type_proc, &storage);
17728   }
17729 }
17730
17731 /* Given a function DECL, which is a specialization of TMPL, modify
17732    DECL to be a re-instantiation of TMPL with the same template
17733    arguments.  TMPL should be the template into which tsubst'ing
17734    should occur for DECL, not the most general template.
17735
17736    One reason for doing this is a scenario like this:
17737
17738      template <class T>
17739      void f(const T&, int i);
17740
17741      void g() { f(3, 7); }
17742
17743      template <class T>
17744      void f(const T& t, const int i) { }
17745
17746    Note that when the template is first instantiated, with
17747    instantiate_template, the resulting DECL will have no name for the
17748    first parameter, and the wrong type for the second.  So, when we go
17749    to instantiate the DECL, we regenerate it.  */
17750
17751 static void
17752 regenerate_decl_from_template (tree decl, tree tmpl)
17753 {
17754   /* The arguments used to instantiate DECL, from the most general
17755      template.  */
17756   tree args;
17757   tree code_pattern;
17758
17759   args = DECL_TI_ARGS (decl);
17760   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17761
17762   /* Make sure that we can see identifiers, and compute access
17763      correctly.  */
17764   push_access_scope (decl);
17765
17766   if (TREE_CODE (decl) == FUNCTION_DECL)
17767     {
17768       tree decl_parm;
17769       tree pattern_parm;
17770       tree specs;
17771       int args_depth;
17772       int parms_depth;
17773
17774       args_depth = TMPL_ARGS_DEPTH (args);
17775       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17776       if (args_depth > parms_depth)
17777         args = get_innermost_template_args (args, parms_depth);
17778
17779       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17780                                               args, tf_error, NULL_TREE,
17781                                               /*defer_ok*/false);
17782       if (specs && specs != error_mark_node)
17783         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17784                                                     specs);
17785
17786       /* Merge parameter declarations.  */
17787       decl_parm = skip_artificial_parms_for (decl,
17788                                              DECL_ARGUMENTS (decl));
17789       pattern_parm
17790         = skip_artificial_parms_for (code_pattern,
17791                                      DECL_ARGUMENTS (code_pattern));
17792       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17793         {
17794           tree parm_type;
17795           tree attributes;
17796           
17797           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17798             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17799           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17800                               NULL_TREE);
17801           parm_type = type_decays_to (parm_type);
17802           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17803             TREE_TYPE (decl_parm) = parm_type;
17804           attributes = DECL_ATTRIBUTES (pattern_parm);
17805           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17806             {
17807               DECL_ATTRIBUTES (decl_parm) = attributes;
17808               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17809             }
17810           decl_parm = DECL_CHAIN (decl_parm);
17811           pattern_parm = DECL_CHAIN (pattern_parm);
17812         }
17813       /* Merge any parameters that match with the function parameter
17814          pack.  */
17815       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17816         {
17817           int i, len;
17818           tree expanded_types;
17819           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17820              the parameters in this function parameter pack.  */
17821           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17822                                                  args, tf_error, NULL_TREE);
17823           len = TREE_VEC_LENGTH (expanded_types);
17824           for (i = 0; i < len; i++)
17825             {
17826               tree parm_type;
17827               tree attributes;
17828           
17829               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17830                 /* Rename the parameter to include the index.  */
17831                 DECL_NAME (decl_parm) = 
17832                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17833               parm_type = TREE_VEC_ELT (expanded_types, i);
17834               parm_type = type_decays_to (parm_type);
17835               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17836                 TREE_TYPE (decl_parm) = parm_type;
17837               attributes = DECL_ATTRIBUTES (pattern_parm);
17838               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17839                 {
17840                   DECL_ATTRIBUTES (decl_parm) = attributes;
17841                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17842                 }
17843               decl_parm = DECL_CHAIN (decl_parm);
17844             }
17845         }
17846       /* Merge additional specifiers from the CODE_PATTERN.  */
17847       if (DECL_DECLARED_INLINE_P (code_pattern)
17848           && !DECL_DECLARED_INLINE_P (decl))
17849         DECL_DECLARED_INLINE_P (decl) = 1;
17850     }
17851   else if (TREE_CODE (decl) == VAR_DECL)
17852     {
17853       DECL_INITIAL (decl) =
17854         tsubst_expr (DECL_INITIAL (code_pattern), args,
17855                      tf_error, DECL_TI_TEMPLATE (decl),
17856                      /*integral_constant_expression_p=*/false);
17857       if (VAR_HAD_UNKNOWN_BOUND (decl))
17858         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17859                                    tf_error, DECL_TI_TEMPLATE (decl));
17860     }
17861   else
17862     gcc_unreachable ();
17863
17864   pop_access_scope (decl);
17865 }
17866
17867 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17868    substituted to get DECL.  */
17869
17870 tree
17871 template_for_substitution (tree decl)
17872 {
17873   tree tmpl = DECL_TI_TEMPLATE (decl);
17874
17875   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17876      for the instantiation.  This is not always the most general
17877      template.  Consider, for example:
17878
17879         template <class T>
17880         struct S { template <class U> void f();
17881                    template <> void f<int>(); };
17882
17883      and an instantiation of S<double>::f<int>.  We want TD to be the
17884      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17885   while (/* An instantiation cannot have a definition, so we need a
17886             more general template.  */
17887          DECL_TEMPLATE_INSTANTIATION (tmpl)
17888            /* We must also deal with friend templates.  Given:
17889
17890                 template <class T> struct S {
17891                   template <class U> friend void f() {};
17892                 };
17893
17894               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17895               so far as the language is concerned, but that's still
17896               where we get the pattern for the instantiation from.  On
17897               other hand, if the definition comes outside the class, say:
17898
17899                 template <class T> struct S {
17900                   template <class U> friend void f();
17901                 };
17902                 template <class U> friend void f() {}
17903
17904               we don't need to look any further.  That's what the check for
17905               DECL_INITIAL is for.  */
17906           || (TREE_CODE (decl) == FUNCTION_DECL
17907               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17908               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17909     {
17910       /* The present template, TD, should not be a definition.  If it
17911          were a definition, we should be using it!  Note that we
17912          cannot restructure the loop to just keep going until we find
17913          a template with a definition, since that might go too far if
17914          a specialization was declared, but not defined.  */
17915       gcc_assert (TREE_CODE (decl) != VAR_DECL
17916                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17917
17918       /* Fetch the more general template.  */
17919       tmpl = DECL_TI_TEMPLATE (tmpl);
17920     }
17921
17922   return tmpl;
17923 }
17924
17925 /* Returns true if we need to instantiate this template instance even if we
17926    know we aren't going to emit it..  */
17927
17928 bool
17929 always_instantiate_p (tree decl)
17930 {
17931   /* We always instantiate inline functions so that we can inline them.  An
17932      explicit instantiation declaration prohibits implicit instantiation of
17933      non-inline functions.  With high levels of optimization, we would
17934      normally inline non-inline functions -- but we're not allowed to do
17935      that for "extern template" functions.  Therefore, we check
17936      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17937   return ((TREE_CODE (decl) == FUNCTION_DECL
17938            && DECL_DECLARED_INLINE_P (decl))
17939           /* And we need to instantiate static data members so that
17940              their initializers are available in integral constant
17941              expressions.  */
17942           || (TREE_CODE (decl) == VAR_DECL
17943               && decl_maybe_constant_var_p (decl)));
17944 }
17945
17946 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17947    instantiate it now, modifying TREE_TYPE (fn).  */
17948
17949 void
17950 maybe_instantiate_noexcept (tree fn)
17951 {
17952   tree fntype, spec, noex, clone;
17953
17954   if (DECL_CLONED_FUNCTION_P (fn))
17955     fn = DECL_CLONED_FUNCTION (fn);
17956   fntype = TREE_TYPE (fn);
17957   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17958
17959   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17960     return;
17961
17962   noex = TREE_PURPOSE (spec);
17963
17964   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17965     {
17966       push_tinst_level (fn);
17967       push_access_scope (fn);
17968       input_location = DECL_SOURCE_LOCATION (fn);
17969       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17970                                     DEFERRED_NOEXCEPT_ARGS (noex),
17971                                     tf_warning_or_error, fn, /*function_p=*/false,
17972                                     /*integral_constant_expression_p=*/true);
17973       pop_access_scope (fn);
17974       pop_tinst_level ();
17975       spec = build_noexcept_spec (noex, tf_warning_or_error);
17976       if (spec == error_mark_node)
17977         spec = noexcept_false_spec;
17978     }
17979   else
17980     {
17981       /* This is an implicitly declared function, so NOEX is a list of
17982          other functions to evaluate and merge.  */
17983       tree elt;
17984       spec = noexcept_true_spec;
17985       for (elt = noex; elt; elt = OVL_NEXT (elt))
17986         {
17987           tree fn = OVL_CURRENT (elt);
17988           tree subspec;
17989           maybe_instantiate_noexcept (fn);
17990           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17991           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17992         }
17993     }
17994
17995   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17996
17997   FOR_EACH_CLONE (clone, fn)
17998     {
17999       if (TREE_TYPE (clone) == fntype)
18000         TREE_TYPE (clone) = TREE_TYPE (fn);
18001       else
18002         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
18003     }
18004 }
18005
18006 /* Produce the definition of D, a _DECL generated from a template.  If
18007    DEFER_OK is nonzero, then we don't have to actually do the
18008    instantiation now; we just have to do it sometime.  Normally it is
18009    an error if this is an explicit instantiation but D is undefined.
18010    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
18011    explicitly instantiated class template.  */
18012
18013 tree
18014 instantiate_decl (tree d, int defer_ok,
18015                   bool expl_inst_class_mem_p)
18016 {
18017   tree tmpl = DECL_TI_TEMPLATE (d);
18018   tree gen_args;
18019   tree args;
18020   tree td;
18021   tree code_pattern;
18022   tree spec;
18023   tree gen_tmpl;
18024   bool pattern_defined;
18025   int need_push;
18026   location_t saved_loc = input_location;
18027   bool external_p;
18028
18029   /* This function should only be used to instantiate templates for
18030      functions and static member variables.  */
18031   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18032               || TREE_CODE (d) == VAR_DECL);
18033
18034   /* Variables are never deferred; if instantiation is required, they
18035      are instantiated right away.  That allows for better code in the
18036      case that an expression refers to the value of the variable --
18037      if the variable has a constant value the referring expression can
18038      take advantage of that fact.  */
18039   if (TREE_CODE (d) == VAR_DECL
18040       || DECL_DECLARED_CONSTEXPR_P (d))
18041     defer_ok = 0;
18042
18043   /* Don't instantiate cloned functions.  Instead, instantiate the
18044      functions they cloned.  */
18045   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18046     d = DECL_CLONED_FUNCTION (d);
18047
18048   if (DECL_TEMPLATE_INSTANTIATED (d)
18049       || (TREE_CODE (d) == FUNCTION_DECL
18050           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
18051       || DECL_TEMPLATE_SPECIALIZATION (d))
18052     /* D has already been instantiated or explicitly specialized, so
18053        there's nothing for us to do here.
18054
18055        It might seem reasonable to check whether or not D is an explicit
18056        instantiation, and, if so, stop here.  But when an explicit
18057        instantiation is deferred until the end of the compilation,
18058        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18059        the instantiation.  */
18060     return d;
18061
18062   /* Check to see whether we know that this template will be
18063      instantiated in some other file, as with "extern template"
18064      extension.  */
18065   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18066
18067   /* In general, we do not instantiate such templates.  */
18068   if (external_p && !always_instantiate_p (d))
18069     return d;
18070
18071   gen_tmpl = most_general_template (tmpl);
18072   gen_args = DECL_TI_ARGS (d);
18073
18074   if (tmpl != gen_tmpl)
18075     /* We should already have the extra args.  */
18076     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18077                 == TMPL_ARGS_DEPTH (gen_args));
18078   /* And what's in the hash table should match D.  */
18079   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18080               || spec == NULL_TREE);
18081
18082   /* This needs to happen before any tsubsting.  */
18083   if (! push_tinst_level (d))
18084     return d;
18085
18086   timevar_push (TV_TEMPLATE_INST);
18087
18088   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18089      for the instantiation.  */
18090   td = template_for_substitution (d);
18091   code_pattern = DECL_TEMPLATE_RESULT (td);
18092
18093   /* We should never be trying to instantiate a member of a class
18094      template or partial specialization.  */
18095   gcc_assert (d != code_pattern);
18096
18097   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18098       || DECL_TEMPLATE_SPECIALIZATION (td))
18099     /* In the case of a friend template whose definition is provided
18100        outside the class, we may have too many arguments.  Drop the
18101        ones we don't need.  The same is true for specializations.  */
18102     args = get_innermost_template_args
18103       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18104   else
18105     args = gen_args;
18106
18107   if (TREE_CODE (d) == FUNCTION_DECL)
18108     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18109                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18110   else
18111     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18112
18113   /* We may be in the middle of deferred access check.  Disable it now.  */
18114   push_deferring_access_checks (dk_no_deferred);
18115
18116   /* Unless an explicit instantiation directive has already determined
18117      the linkage of D, remember that a definition is available for
18118      this entity.  */
18119   if (pattern_defined
18120       && !DECL_INTERFACE_KNOWN (d)
18121       && !DECL_NOT_REALLY_EXTERN (d))
18122     mark_definable (d);
18123
18124   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18125   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18126   input_location = DECL_SOURCE_LOCATION (d);
18127
18128   /* If D is a member of an explicitly instantiated class template,
18129      and no definition is available, treat it like an implicit
18130      instantiation.  */
18131   if (!pattern_defined && expl_inst_class_mem_p
18132       && DECL_EXPLICIT_INSTANTIATION (d))
18133     {
18134       /* Leave linkage flags alone on instantiations with anonymous
18135          visibility.  */
18136       if (TREE_PUBLIC (d))
18137         {
18138           DECL_NOT_REALLY_EXTERN (d) = 0;
18139           DECL_INTERFACE_KNOWN (d) = 0;
18140         }
18141       SET_DECL_IMPLICIT_INSTANTIATION (d);
18142     }
18143
18144   if (TREE_CODE (d) == FUNCTION_DECL)
18145     maybe_instantiate_noexcept (d);
18146
18147   /* Recheck the substitutions to obtain any warning messages
18148      about ignoring cv qualifiers.  Don't do this for artificial decls,
18149      as it breaks the context-sensitive substitution for lambda op(). */
18150   if (!defer_ok && !DECL_ARTIFICIAL (d))
18151     {
18152       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18153       tree type = TREE_TYPE (gen);
18154
18155       /* Make sure that we can see identifiers, and compute access
18156          correctly.  D is already the target FUNCTION_DECL with the
18157          right context.  */
18158       push_access_scope (d);
18159
18160       if (TREE_CODE (gen) == FUNCTION_DECL)
18161         {
18162           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18163           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18164                                           d, /*defer_ok*/true);
18165           /* Don't simply tsubst the function type, as that will give
18166              duplicate warnings about poor parameter qualifications.
18167              The function arguments are the same as the decl_arguments
18168              without the top level cv qualifiers.  */
18169           type = TREE_TYPE (type);
18170         }
18171       tsubst (type, gen_args, tf_warning_or_error, d);
18172
18173       pop_access_scope (d);
18174     }
18175
18176   /* Defer all other templates, unless we have been explicitly
18177      forbidden from doing so.  */
18178   if (/* If there is no definition, we cannot instantiate the
18179          template.  */
18180       ! pattern_defined
18181       /* If it's OK to postpone instantiation, do so.  */
18182       || defer_ok
18183       /* If this is a static data member that will be defined
18184          elsewhere, we don't want to instantiate the entire data
18185          member, but we do want to instantiate the initializer so that
18186          we can substitute that elsewhere.  */
18187       || (external_p && TREE_CODE (d) == VAR_DECL))
18188     {
18189       /* The definition of the static data member is now required so
18190          we must substitute the initializer.  */
18191       if (TREE_CODE (d) == VAR_DECL
18192           && !DECL_INITIAL (d)
18193           && DECL_INITIAL (code_pattern))
18194         {
18195           tree ns;
18196           tree init;
18197           bool const_init = false;
18198
18199           ns = decl_namespace_context (d);
18200           push_nested_namespace (ns);
18201           push_nested_class (DECL_CONTEXT (d));
18202           init = tsubst_expr (DECL_INITIAL (code_pattern),
18203                               args,
18204                               tf_warning_or_error, NULL_TREE,
18205                               /*integral_constant_expression_p=*/false);
18206           /* Make sure the initializer is still constant, in case of
18207              circular dependency (template/instantiate6.C). */
18208           const_init
18209             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18210           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18211                           /*asmspec_tree=*/NULL_TREE,
18212                           LOOKUP_ONLYCONVERTING);
18213           pop_nested_class ();
18214           pop_nested_namespace (ns);
18215         }
18216
18217       /* We restore the source position here because it's used by
18218          add_pending_template.  */
18219       input_location = saved_loc;
18220
18221       if (at_eof && !pattern_defined
18222           && DECL_EXPLICIT_INSTANTIATION (d)
18223           && DECL_NOT_REALLY_EXTERN (d))
18224         /* [temp.explicit]
18225
18226            The definition of a non-exported function template, a
18227            non-exported member function template, or a non-exported
18228            member function or static data member of a class template
18229            shall be present in every translation unit in which it is
18230            explicitly instantiated.  */
18231         permerror (input_location,  "explicit instantiation of %qD "
18232                    "but no definition available", d);
18233
18234       /* If we're in unevaluated context, we just wanted to get the
18235          constant value; this isn't an odr use, so don't queue
18236          a full instantiation.  */
18237       if (cp_unevaluated_operand != 0)
18238         goto out;
18239       /* ??? Historically, we have instantiated inline functions, even
18240          when marked as "extern template".  */
18241       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18242         add_pending_template (d);
18243       goto out;
18244     }
18245   /* Tell the repository that D is available in this translation unit
18246      -- and see if it is supposed to be instantiated here.  */
18247   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18248     {
18249       /* In a PCH file, despite the fact that the repository hasn't
18250          requested instantiation in the PCH it is still possible that
18251          an instantiation will be required in a file that includes the
18252          PCH.  */
18253       if (pch_file)
18254         add_pending_template (d);
18255       /* Instantiate inline functions so that the inliner can do its
18256          job, even though we'll not be emitting a copy of this
18257          function.  */
18258       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18259         goto out;
18260     }
18261
18262   need_push = !cfun || !global_bindings_p ();
18263   if (need_push)
18264     push_to_top_level ();
18265
18266   /* Mark D as instantiated so that recursive calls to
18267      instantiate_decl do not try to instantiate it again.  */
18268   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18269
18270   /* Regenerate the declaration in case the template has been modified
18271      by a subsequent redeclaration.  */
18272   regenerate_decl_from_template (d, td);
18273
18274   /* We already set the file and line above.  Reset them now in case
18275      they changed as a result of calling regenerate_decl_from_template.  */
18276   input_location = DECL_SOURCE_LOCATION (d);
18277
18278   if (TREE_CODE (d) == VAR_DECL)
18279     {
18280       tree init;
18281       bool const_init = false;
18282
18283       /* Clear out DECL_RTL; whatever was there before may not be right
18284          since we've reset the type of the declaration.  */
18285       SET_DECL_RTL (d, NULL);
18286       DECL_IN_AGGR_P (d) = 0;
18287
18288       /* The initializer is placed in DECL_INITIAL by
18289          regenerate_decl_from_template so we don't need to
18290          push/pop_access_scope again here.  Pull it out so that
18291          cp_finish_decl can process it.  */
18292       init = DECL_INITIAL (d);
18293       DECL_INITIAL (d) = NULL_TREE;
18294       DECL_INITIALIZED_P (d) = 0;
18295
18296       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18297          initializer.  That function will defer actual emission until
18298          we have a chance to determine linkage.  */
18299       DECL_EXTERNAL (d) = 0;
18300
18301       /* Enter the scope of D so that access-checking works correctly.  */
18302       push_nested_class (DECL_CONTEXT (d));
18303       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18304       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18305       pop_nested_class ();
18306     }
18307   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18308     synthesize_method (d);
18309   else if (TREE_CODE (d) == FUNCTION_DECL)
18310     {
18311       htab_t saved_local_specializations;
18312       tree subst_decl;
18313       tree tmpl_parm;
18314       tree spec_parm;
18315
18316       /* Save away the current list, in case we are instantiating one
18317          template from within the body of another.  */
18318       saved_local_specializations = local_specializations;
18319
18320       /* Set up the list of local specializations.  */
18321       local_specializations = htab_create (37,
18322                                            hash_local_specialization,
18323                                            eq_local_specializations,
18324                                            NULL);
18325
18326       /* Set up context.  */
18327       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18328
18329       /* Create substitution entries for the parameters.  */
18330       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18331       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18332       spec_parm = DECL_ARGUMENTS (d);
18333       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18334         {
18335           register_local_specialization (spec_parm, tmpl_parm);
18336           spec_parm = skip_artificial_parms_for (d, spec_parm);
18337           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18338         }
18339       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18340         {
18341           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18342             {
18343               register_local_specialization (spec_parm, tmpl_parm);
18344               spec_parm = DECL_CHAIN (spec_parm);
18345             }
18346           else
18347             {
18348               /* Register the (value) argument pack as a specialization of
18349                  TMPL_PARM, then move on.  */
18350               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18351               register_local_specialization (argpack, tmpl_parm);
18352             }
18353         }
18354       gcc_assert (!spec_parm);
18355
18356       /* Substitute into the body of the function.  */
18357       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18358                    tf_warning_or_error, tmpl,
18359                    /*integral_constant_expression_p=*/false);
18360
18361       /* Set the current input_location to the end of the function
18362          so that finish_function knows where we are.  */
18363       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18364
18365       /* We don't need the local specializations any more.  */
18366       htab_delete (local_specializations);
18367       local_specializations = saved_local_specializations;
18368
18369       /* Finish the function.  */
18370       d = finish_function (0);
18371       expand_or_defer_fn (d);
18372     }
18373
18374   /* We're not deferring instantiation any more.  */
18375   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18376
18377   if (need_push)
18378     pop_from_top_level ();
18379
18380 out:
18381   input_location = saved_loc;
18382   pop_deferring_access_checks ();
18383   pop_tinst_level ();
18384
18385   timevar_pop (TV_TEMPLATE_INST);
18386
18387   return d;
18388 }
18389
18390 /* Run through the list of templates that we wish we could
18391    instantiate, and instantiate any we can.  RETRIES is the
18392    number of times we retry pending template instantiation.  */
18393
18394 void
18395 instantiate_pending_templates (int retries)
18396 {
18397   int reconsider;
18398   location_t saved_loc = input_location;
18399
18400   /* Instantiating templates may trigger vtable generation.  This in turn
18401      may require further template instantiations.  We place a limit here
18402      to avoid infinite loop.  */
18403   if (pending_templates && retries >= max_tinst_depth)
18404     {
18405       tree decl = pending_templates->tinst->decl;
18406
18407       error ("template instantiation depth exceeds maximum of %d"
18408              " instantiating %q+D, possibly from virtual table generation"
18409              " (use -ftemplate-depth= to increase the maximum)",
18410              max_tinst_depth, decl);
18411       if (TREE_CODE (decl) == FUNCTION_DECL)
18412         /* Pretend that we defined it.  */
18413         DECL_INITIAL (decl) = error_mark_node;
18414       return;
18415     }
18416
18417   do
18418     {
18419       struct pending_template **t = &pending_templates;
18420       struct pending_template *last = NULL;
18421       reconsider = 0;
18422       while (*t)
18423         {
18424           tree instantiation = reopen_tinst_level ((*t)->tinst);
18425           bool complete = false;
18426
18427           if (TYPE_P (instantiation))
18428             {
18429               tree fn;
18430
18431               if (!COMPLETE_TYPE_P (instantiation))
18432                 {
18433                   instantiate_class_template (instantiation);
18434                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18435                     for (fn = TYPE_METHODS (instantiation);
18436                          fn;
18437                          fn = TREE_CHAIN (fn))
18438                       if (! DECL_ARTIFICIAL (fn))
18439                         instantiate_decl (fn,
18440                                           /*defer_ok=*/0,
18441                                           /*expl_inst_class_mem_p=*/false);
18442                   if (COMPLETE_TYPE_P (instantiation))
18443                     reconsider = 1;
18444                 }
18445
18446               complete = COMPLETE_TYPE_P (instantiation);
18447             }
18448           else
18449             {
18450               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18451                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18452                 {
18453                   instantiation
18454                     = instantiate_decl (instantiation,
18455                                         /*defer_ok=*/0,
18456                                         /*expl_inst_class_mem_p=*/false);
18457                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18458                     reconsider = 1;
18459                 }
18460
18461               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18462                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18463             }
18464
18465           if (complete)
18466             /* If INSTANTIATION has been instantiated, then we don't
18467                need to consider it again in the future.  */
18468             *t = (*t)->next;
18469           else
18470             {
18471               last = *t;
18472               t = &(*t)->next;
18473             }
18474           tinst_depth = 0;
18475           current_tinst_level = NULL;
18476         }
18477       last_pending_template = last;
18478     }
18479   while (reconsider);
18480
18481   input_location = saved_loc;
18482 }
18483
18484 /* Substitute ARGVEC into T, which is a list of initializers for
18485    either base class or a non-static data member.  The TREE_PURPOSEs
18486    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18487    instantiate_decl.  */
18488
18489 static tree
18490 tsubst_initializer_list (tree t, tree argvec)
18491 {
18492   tree inits = NULL_TREE;
18493
18494   for (; t; t = TREE_CHAIN (t))
18495     {
18496       tree decl;
18497       tree init;
18498       tree expanded_bases = NULL_TREE;
18499       tree expanded_arguments = NULL_TREE;
18500       int i, len = 1;
18501
18502       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18503         {
18504           tree expr;
18505           tree arg;
18506
18507           /* Expand the base class expansion type into separate base
18508              classes.  */
18509           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18510                                                  tf_warning_or_error,
18511                                                  NULL_TREE);
18512           if (expanded_bases == error_mark_node)
18513             continue;
18514           
18515           /* We'll be building separate TREE_LISTs of arguments for
18516              each base.  */
18517           len = TREE_VEC_LENGTH (expanded_bases);
18518           expanded_arguments = make_tree_vec (len);
18519           for (i = 0; i < len; i++)
18520             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18521
18522           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18523              expand each argument in the TREE_VALUE of t.  */
18524           expr = make_node (EXPR_PACK_EXPANSION);
18525           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18526             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18527
18528           if (TREE_VALUE (t) == void_type_node)
18529             /* VOID_TYPE_NODE is used to indicate
18530                value-initialization.  */
18531             {
18532               for (i = 0; i < len; i++)
18533                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18534             }
18535           else
18536             {
18537               /* Substitute parameter packs into each argument in the
18538                  TREE_LIST.  */
18539               in_base_initializer = 1;
18540               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18541                 {
18542                   tree expanded_exprs;
18543
18544                   /* Expand the argument.  */
18545                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18546                   expanded_exprs 
18547                     = tsubst_pack_expansion (expr, argvec,
18548                                              tf_warning_or_error,
18549                                              NULL_TREE);
18550                   if (expanded_exprs == error_mark_node)
18551                     continue;
18552
18553                   /* Prepend each of the expanded expressions to the
18554                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18555                   for (i = 0; i < len; i++)
18556                     {
18557                       TREE_VEC_ELT (expanded_arguments, i) = 
18558                         tree_cons (NULL_TREE, 
18559                                    TREE_VEC_ELT (expanded_exprs, i),
18560                                    TREE_VEC_ELT (expanded_arguments, i));
18561                     }
18562                 }
18563               in_base_initializer = 0;
18564
18565               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18566                  since we built them backwards.  */
18567               for (i = 0; i < len; i++)
18568                 {
18569                   TREE_VEC_ELT (expanded_arguments, i) = 
18570                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18571                 }
18572             }
18573         }
18574
18575       for (i = 0; i < len; ++i)
18576         {
18577           if (expanded_bases)
18578             {
18579               decl = TREE_VEC_ELT (expanded_bases, i);
18580               decl = expand_member_init (decl);
18581               init = TREE_VEC_ELT (expanded_arguments, i);
18582             }
18583           else
18584             {
18585               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18586                                   tf_warning_or_error, NULL_TREE);
18587
18588               decl = expand_member_init (decl);
18589               if (decl && !DECL_P (decl))
18590                 in_base_initializer = 1;
18591
18592               init = TREE_VALUE (t);
18593               if (init != void_type_node)
18594                 init = tsubst_expr (init, argvec,
18595                                     tf_warning_or_error, NULL_TREE,
18596                                     /*integral_constant_expression_p=*/false);
18597               in_base_initializer = 0;
18598             }
18599
18600           if (decl)
18601             {
18602               init = build_tree_list (decl, init);
18603               TREE_CHAIN (init) = inits;
18604               inits = init;
18605             }
18606         }
18607     }
18608   return inits;
18609 }
18610
18611 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18612
18613 static void
18614 set_current_access_from_decl (tree decl)
18615 {
18616   if (TREE_PRIVATE (decl))
18617     current_access_specifier = access_private_node;
18618   else if (TREE_PROTECTED (decl))
18619     current_access_specifier = access_protected_node;
18620   else
18621     current_access_specifier = access_public_node;
18622 }
18623
18624 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18625    is the instantiation (which should have been created with
18626    start_enum) and ARGS are the template arguments to use.  */
18627
18628 static void
18629 tsubst_enum (tree tag, tree newtag, tree args)
18630 {
18631   tree e;
18632
18633   if (SCOPED_ENUM_P (newtag))
18634     begin_scope (sk_scoped_enum, newtag);
18635
18636   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18637     {
18638       tree value;
18639       tree decl;
18640
18641       decl = TREE_VALUE (e);
18642       /* Note that in a template enum, the TREE_VALUE is the
18643          CONST_DECL, not the corresponding INTEGER_CST.  */
18644       value = tsubst_expr (DECL_INITIAL (decl),
18645                            args, tf_warning_or_error, NULL_TREE,
18646                            /*integral_constant_expression_p=*/true);
18647
18648       /* Give this enumeration constant the correct access.  */
18649       set_current_access_from_decl (decl);
18650
18651       /* Actually build the enumerator itself.  */
18652       build_enumerator
18653         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18654     }
18655
18656   if (SCOPED_ENUM_P (newtag))
18657     finish_scope ();
18658
18659   finish_enum_value_list (newtag);
18660   finish_enum (newtag);
18661
18662   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18663     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18664 }
18665
18666 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18667    its type -- but without substituting the innermost set of template
18668    arguments.  So, innermost set of template parameters will appear in
18669    the type.  */
18670
18671 tree
18672 get_mostly_instantiated_function_type (tree decl)
18673 {
18674   tree fn_type;
18675   tree tmpl;
18676   tree targs;
18677   tree tparms;
18678   int parm_depth;
18679
18680   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18681   targs = DECL_TI_ARGS (decl);
18682   tparms = DECL_TEMPLATE_PARMS (tmpl);
18683   parm_depth = TMPL_PARMS_DEPTH (tparms);
18684
18685   /* There should be as many levels of arguments as there are levels
18686      of parameters.  */
18687   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18688
18689   fn_type = TREE_TYPE (tmpl);
18690
18691   if (parm_depth == 1)
18692     /* No substitution is necessary.  */
18693     ;
18694   else
18695     {
18696       int i;
18697       tree partial_args;
18698
18699       /* Replace the innermost level of the TARGS with NULL_TREEs to
18700          let tsubst know not to substitute for those parameters.  */
18701       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18702       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18703         SET_TMPL_ARGS_LEVEL (partial_args, i,
18704                              TMPL_ARGS_LEVEL (targs, i));
18705       SET_TMPL_ARGS_LEVEL (partial_args,
18706                            TMPL_ARGS_DEPTH (targs),
18707                            make_tree_vec (DECL_NTPARMS (tmpl)));
18708
18709       /* Make sure that we can see identifiers, and compute access
18710          correctly.  */
18711       push_access_scope (decl);
18712
18713       ++processing_template_decl;
18714       /* Now, do the (partial) substitution to figure out the
18715          appropriate function type.  */
18716       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18717       --processing_template_decl;
18718
18719       /* Substitute into the template parameters to obtain the real
18720          innermost set of parameters.  This step is important if the
18721          innermost set of template parameters contains value
18722          parameters whose types depend on outer template parameters.  */
18723       TREE_VEC_LENGTH (partial_args)--;
18724       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18725
18726       pop_access_scope (decl);
18727     }
18728
18729   return fn_type;
18730 }
18731
18732 /* Return truthvalue if we're processing a template different from
18733    the last one involved in diagnostics.  */
18734 int
18735 problematic_instantiation_changed (void)
18736 {
18737   return current_tinst_level != last_error_tinst_level;
18738 }
18739
18740 /* Remember current template involved in diagnostics.  */
18741 void
18742 record_last_problematic_instantiation (void)
18743 {
18744   last_error_tinst_level = current_tinst_level;
18745 }
18746
18747 struct tinst_level *
18748 current_instantiation (void)
18749 {
18750   return current_tinst_level;
18751 }
18752
18753 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18754    type. Return zero for ok, nonzero for disallowed. Issue error and
18755    warning messages under control of COMPLAIN.  */
18756
18757 static int
18758 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18759 {
18760   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18761     return 0;
18762   else if (POINTER_TYPE_P (type))
18763     return 0;
18764   else if (TYPE_PTR_TO_MEMBER_P (type))
18765     return 0;
18766   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18767     return 0;
18768   else if (TREE_CODE (type) == TYPENAME_TYPE)
18769     return 0;
18770   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18771     return 0;
18772   else if (TREE_CODE (type) == NULLPTR_TYPE)
18773     return 0;
18774
18775   if (complain & tf_error)
18776     error ("%q#T is not a valid type for a template constant parameter", type);
18777   return 1;
18778 }
18779
18780 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18781    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18782
18783 static bool
18784 dependent_type_p_r (tree type)
18785 {
18786   tree scope;
18787
18788   /* [temp.dep.type]
18789
18790      A type is dependent if it is:
18791
18792      -- a template parameter. Template template parameters are types
18793         for us (since TYPE_P holds true for them) so we handle
18794         them here.  */
18795   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18796       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18797     return true;
18798   /* -- a qualified-id with a nested-name-specifier which contains a
18799         class-name that names a dependent type or whose unqualified-id
18800         names a dependent type.  */
18801   if (TREE_CODE (type) == TYPENAME_TYPE)
18802     return true;
18803   /* -- a cv-qualified type where the cv-unqualified type is
18804         dependent.  */
18805   type = TYPE_MAIN_VARIANT (type);
18806   /* -- a compound type constructed from any dependent type.  */
18807   if (TYPE_PTR_TO_MEMBER_P (type))
18808     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18809             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18810                                            (type)));
18811   else if (TREE_CODE (type) == POINTER_TYPE
18812            || TREE_CODE (type) == REFERENCE_TYPE)
18813     return dependent_type_p (TREE_TYPE (type));
18814   else if (TREE_CODE (type) == FUNCTION_TYPE
18815            || TREE_CODE (type) == METHOD_TYPE)
18816     {
18817       tree arg_type;
18818
18819       if (dependent_type_p (TREE_TYPE (type)))
18820         return true;
18821       for (arg_type = TYPE_ARG_TYPES (type);
18822            arg_type;
18823            arg_type = TREE_CHAIN (arg_type))
18824         if (dependent_type_p (TREE_VALUE (arg_type)))
18825           return true;
18826       return false;
18827     }
18828   /* -- an array type constructed from any dependent type or whose
18829         size is specified by a constant expression that is
18830         value-dependent.
18831
18832         We checked for type- and value-dependence of the bounds in
18833         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18834   if (TREE_CODE (type) == ARRAY_TYPE)
18835     {
18836       if (TYPE_DOMAIN (type)
18837           && dependent_type_p (TYPE_DOMAIN (type)))
18838         return true;
18839       return dependent_type_p (TREE_TYPE (type));
18840     }
18841
18842   /* -- a template-id in which either the template name is a template
18843      parameter ...  */
18844   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18845     return true;
18846   /* ... or any of the template arguments is a dependent type or
18847         an expression that is type-dependent or value-dependent.  */
18848   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18849            && (any_dependent_template_arguments_p
18850                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18851     return true;
18852
18853   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18854      dependent; if the argument of the `typeof' expression is not
18855      type-dependent, then it should already been have resolved.  */
18856   if (TREE_CODE (type) == TYPEOF_TYPE
18857       || TREE_CODE (type) == DECLTYPE_TYPE
18858       || TREE_CODE (type) == UNDERLYING_TYPE)
18859     return true;
18860
18861   /* A template argument pack is dependent if any of its packed
18862      arguments are.  */
18863   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18864     {
18865       tree args = ARGUMENT_PACK_ARGS (type);
18866       int i, len = TREE_VEC_LENGTH (args);
18867       for (i = 0; i < len; ++i)
18868         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18869           return true;
18870     }
18871
18872   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18873      be template parameters.  */
18874   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18875     return true;
18876
18877   /* The standard does not specifically mention types that are local
18878      to template functions or local classes, but they should be
18879      considered dependent too.  For example:
18880
18881        template <int I> void f() {
18882          enum E { a = I };
18883          S<sizeof (E)> s;
18884        }
18885
18886      The size of `E' cannot be known until the value of `I' has been
18887      determined.  Therefore, `E' must be considered dependent.  */
18888   scope = TYPE_CONTEXT (type);
18889   if (scope && TYPE_P (scope))
18890     return dependent_type_p (scope);
18891   /* Don't use type_dependent_expression_p here, as it can lead
18892      to infinite recursion trying to determine whether a lambda
18893      nested in a lambda is dependent (c++/47687).  */
18894   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18895            && DECL_LANG_SPECIFIC (scope)
18896            && DECL_TEMPLATE_INFO (scope)
18897            && (any_dependent_template_arguments_p
18898                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18899     return true;
18900
18901   /* Other types are non-dependent.  */
18902   return false;
18903 }
18904
18905 /* Returns TRUE if TYPE is dependent, in the sense of
18906    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18907
18908 bool
18909 dependent_type_p (tree type)
18910 {
18911   /* If there are no template parameters in scope, then there can't be
18912      any dependent types.  */
18913   if (!processing_template_decl)
18914     {
18915       /* If we are not processing a template, then nobody should be
18916          providing us with a dependent type.  */
18917       gcc_assert (type);
18918       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18919       return false;
18920     }
18921
18922   /* If the type is NULL, we have not computed a type for the entity
18923      in question; in that case, the type is dependent.  */
18924   if (!type)
18925     return true;
18926
18927   /* Erroneous types can be considered non-dependent.  */
18928   if (type == error_mark_node)
18929     return false;
18930
18931   /* If we have not already computed the appropriate value for TYPE,
18932      do so now.  */
18933   if (!TYPE_DEPENDENT_P_VALID (type))
18934     {
18935       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18936       TYPE_DEPENDENT_P_VALID (type) = 1;
18937     }
18938
18939   return TYPE_DEPENDENT_P (type);
18940 }
18941
18942 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18943    lookup.  In other words, a dependent type that is not the current
18944    instantiation.  */
18945
18946 bool
18947 dependent_scope_p (tree scope)
18948 {
18949   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18950           && !currently_open_class (scope));
18951 }
18952
18953 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18954    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18955    expression.  */
18956
18957 /* Note that this predicate is not appropriate for general expressions;
18958    only constant expressions (that satisfy potential_constant_expression)
18959    can be tested for value dependence.
18960
18961    We should really also have a predicate for "instantiation-dependent".
18962
18963    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18964      (what about instantiation-dependent constant-expressions?)
18965    is_late_template_attribute: defer if instantiation-dependent.
18966    compute_array_index_type: proceed if constant and not t- or v-dependent
18967      if instantiation-dependent, need to remember full expression
18968    uses_template_parms: FIXME - need to audit callers
18969    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18970    dependent_type_p [array_type]: dependent if index type is dependent
18971      (or non-constant?)
18972    static_assert - instantiation-dependent */
18973
18974 bool
18975 value_dependent_expression_p (tree expression)
18976 {
18977   if (!processing_template_decl)
18978     return false;
18979
18980   /* A name declared with a dependent type.  */
18981   if (DECL_P (expression) && type_dependent_expression_p (expression))
18982     return true;
18983
18984   switch (TREE_CODE (expression))
18985     {
18986     case IDENTIFIER_NODE:
18987       /* A name that has not been looked up -- must be dependent.  */
18988       return true;
18989
18990     case TEMPLATE_PARM_INDEX:
18991       /* A non-type template parm.  */
18992       return true;
18993
18994     case CONST_DECL:
18995       /* A non-type template parm.  */
18996       if (DECL_TEMPLATE_PARM_P (expression))
18997         return true;
18998       return value_dependent_expression_p (DECL_INITIAL (expression));
18999
19000     case VAR_DECL:
19001        /* A constant with literal type and is initialized
19002           with an expression that is value-dependent.  */
19003       if (DECL_INITIAL (expression)
19004           && decl_constant_var_p (expression)
19005           && value_dependent_expression_p (DECL_INITIAL (expression)))
19006         return true;
19007       return false;
19008
19009     case DYNAMIC_CAST_EXPR:
19010     case STATIC_CAST_EXPR:
19011     case CONST_CAST_EXPR:
19012     case REINTERPRET_CAST_EXPR:
19013     case CAST_EXPR:
19014       /* These expressions are value-dependent if the type to which
19015          the cast occurs is dependent or the expression being casted
19016          is value-dependent.  */
19017       {
19018         tree type = TREE_TYPE (expression);
19019
19020         if (dependent_type_p (type))
19021           return true;
19022
19023         /* A functional cast has a list of operands.  */
19024         expression = TREE_OPERAND (expression, 0);
19025         if (!expression)
19026           {
19027             /* If there are no operands, it must be an expression such
19028                as "int()". This should not happen for aggregate types
19029                because it would form non-constant expressions.  */
19030             gcc_assert (cxx_dialect >= cxx0x
19031                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19032
19033             return false;
19034           }
19035
19036         if (TREE_CODE (expression) == TREE_LIST)
19037           return any_value_dependent_elements_p (expression);
19038
19039         return value_dependent_expression_p (expression);
19040       }
19041
19042     case SIZEOF_EXPR:
19043     case ALIGNOF_EXPR:
19044     case TYPEID_EXPR:
19045       /* A `sizeof' expression is value-dependent if the operand is
19046          type-dependent or is a pack expansion.  */
19047       expression = TREE_OPERAND (expression, 0);
19048       if (PACK_EXPANSION_P (expression))
19049         return true;
19050       else if (TYPE_P (expression))
19051         return dependent_type_p (expression);
19052       return type_dependent_expression_p (expression);
19053
19054     case AT_ENCODE_EXPR:
19055       /* An 'encode' expression is value-dependent if the operand is
19056          type-dependent.  */
19057       expression = TREE_OPERAND (expression, 0);
19058       return dependent_type_p (expression);
19059
19060     case NOEXCEPT_EXPR:
19061       expression = TREE_OPERAND (expression, 0);
19062       return type_dependent_expression_p (expression);
19063
19064     case SCOPE_REF:
19065       {
19066         tree name = TREE_OPERAND (expression, 1);
19067         return value_dependent_expression_p (name);
19068       }
19069
19070     case COMPONENT_REF:
19071       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19072               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19073
19074     case NONTYPE_ARGUMENT_PACK:
19075       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19076          is value-dependent.  */
19077       {
19078         tree values = ARGUMENT_PACK_ARGS (expression);
19079         int i, len = TREE_VEC_LENGTH (values);
19080         
19081         for (i = 0; i < len; ++i)
19082           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19083             return true;
19084         
19085         return false;
19086       }
19087
19088     case TRAIT_EXPR:
19089       {
19090         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19091         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19092                 || (type2 ? dependent_type_p (type2) : false));
19093       }
19094
19095     case MODOP_EXPR:
19096       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19097               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19098
19099     case ARRAY_REF:
19100       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19101               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19102
19103     case ADDR_EXPR:
19104       {
19105         tree op = TREE_OPERAND (expression, 0);
19106         return (value_dependent_expression_p (op)
19107                 || has_value_dependent_address (op));
19108       }
19109
19110     case CALL_EXPR:
19111       {
19112         tree fn = get_callee_fndecl (expression);
19113         int i, nargs;
19114         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19115           return true;
19116         nargs = call_expr_nargs (expression);
19117         for (i = 0; i < nargs; ++i)
19118           {
19119             tree op = CALL_EXPR_ARG (expression, i);
19120             /* In a call to a constexpr member function, look through the
19121                implicit ADDR_EXPR on the object argument so that it doesn't
19122                cause the call to be considered value-dependent.  We also
19123                look through it in potential_constant_expression.  */
19124             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19125                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19126                 && TREE_CODE (op) == ADDR_EXPR)
19127               op = TREE_OPERAND (op, 0);
19128             if (value_dependent_expression_p (op))
19129               return true;
19130           }
19131         return false;
19132       }
19133
19134     case TEMPLATE_ID_EXPR:
19135       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19136          type-dependent.  */
19137       return type_dependent_expression_p (expression);
19138
19139     case CONSTRUCTOR:
19140       {
19141         unsigned ix;
19142         tree val;
19143         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19144           if (value_dependent_expression_p (val))
19145             return true;
19146         return false;
19147       }
19148
19149     default:
19150       /* A constant expression is value-dependent if any subexpression is
19151          value-dependent.  */
19152       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19153         {
19154         case tcc_reference:
19155         case tcc_unary:
19156         case tcc_comparison:
19157         case tcc_binary:
19158         case tcc_expression:
19159         case tcc_vl_exp:
19160           {
19161             int i, len = cp_tree_operand_length (expression);
19162
19163             for (i = 0; i < len; i++)
19164               {
19165                 tree t = TREE_OPERAND (expression, i);
19166
19167                 /* In some cases, some of the operands may be missing.l
19168                    (For example, in the case of PREDECREMENT_EXPR, the
19169                    amount to increment by may be missing.)  That doesn't
19170                    make the expression dependent.  */
19171                 if (t && value_dependent_expression_p (t))
19172                   return true;
19173               }
19174           }
19175           break;
19176         default:
19177           break;
19178         }
19179       break;
19180     }
19181
19182   /* The expression is not value-dependent.  */
19183   return false;
19184 }
19185
19186 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19187    [temp.dep.expr].  Note that an expression with no type is
19188    considered dependent.  Other parts of the compiler arrange for an
19189    expression with type-dependent subexpressions to have no type, so
19190    this function doesn't have to be fully recursive.  */
19191
19192 bool
19193 type_dependent_expression_p (tree expression)
19194 {
19195   if (!processing_template_decl)
19196     return false;
19197
19198   if (expression == error_mark_node)
19199     return false;
19200
19201   /* An unresolved name is always dependent.  */
19202   if (TREE_CODE (expression) == IDENTIFIER_NODE
19203       || TREE_CODE (expression) == USING_DECL)
19204     return true;
19205
19206   /* Some expression forms are never type-dependent.  */
19207   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19208       || TREE_CODE (expression) == SIZEOF_EXPR
19209       || TREE_CODE (expression) == ALIGNOF_EXPR
19210       || TREE_CODE (expression) == AT_ENCODE_EXPR
19211       || TREE_CODE (expression) == NOEXCEPT_EXPR
19212       || TREE_CODE (expression) == TRAIT_EXPR
19213       || TREE_CODE (expression) == TYPEID_EXPR
19214       || TREE_CODE (expression) == DELETE_EXPR
19215       || TREE_CODE (expression) == VEC_DELETE_EXPR
19216       || TREE_CODE (expression) == THROW_EXPR)
19217     return false;
19218
19219   /* The types of these expressions depends only on the type to which
19220      the cast occurs.  */
19221   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19222       || TREE_CODE (expression) == STATIC_CAST_EXPR
19223       || TREE_CODE (expression) == CONST_CAST_EXPR
19224       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19225       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19226       || TREE_CODE (expression) == CAST_EXPR)
19227     return dependent_type_p (TREE_TYPE (expression));
19228
19229   /* The types of these expressions depends only on the type created
19230      by the expression.  */
19231   if (TREE_CODE (expression) == NEW_EXPR
19232       || TREE_CODE (expression) == VEC_NEW_EXPR)
19233     {
19234       /* For NEW_EXPR tree nodes created inside a template, either
19235          the object type itself or a TREE_LIST may appear as the
19236          operand 1.  */
19237       tree type = TREE_OPERAND (expression, 1);
19238       if (TREE_CODE (type) == TREE_LIST)
19239         /* This is an array type.  We need to check array dimensions
19240            as well.  */
19241         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19242                || value_dependent_expression_p
19243                     (TREE_OPERAND (TREE_VALUE (type), 1));
19244       else
19245         return dependent_type_p (type);
19246     }
19247
19248   if (TREE_CODE (expression) == SCOPE_REF)
19249     {
19250       tree scope = TREE_OPERAND (expression, 0);
19251       tree name = TREE_OPERAND (expression, 1);
19252
19253       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19254          contains an identifier associated by name lookup with one or more
19255          declarations declared with a dependent type, or...a
19256          nested-name-specifier or qualified-id that names a member of an
19257          unknown specialization.  */
19258       return (type_dependent_expression_p (name)
19259               || dependent_scope_p (scope));
19260     }
19261
19262   if (TREE_CODE (expression) == FUNCTION_DECL
19263       && DECL_LANG_SPECIFIC (expression)
19264       && DECL_TEMPLATE_INFO (expression)
19265       && (any_dependent_template_arguments_p
19266           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19267     return true;
19268
19269   if (TREE_CODE (expression) == TEMPLATE_DECL
19270       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19271     return false;
19272
19273   if (TREE_CODE (expression) == STMT_EXPR)
19274     expression = stmt_expr_value_expr (expression);
19275
19276   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19277     {
19278       tree elt;
19279       unsigned i;
19280
19281       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19282         {
19283           if (type_dependent_expression_p (elt))
19284             return true;
19285         }
19286       return false;
19287     }
19288
19289   /* A static data member of the current instantiation with incomplete
19290      array type is type-dependent, as the definition and specializations
19291      can have different bounds.  */
19292   if (TREE_CODE (expression) == VAR_DECL
19293       && DECL_CLASS_SCOPE_P (expression)
19294       && dependent_type_p (DECL_CONTEXT (expression))
19295       && VAR_HAD_UNKNOWN_BOUND (expression))
19296     return true;
19297
19298   if (TREE_TYPE (expression) == unknown_type_node)
19299     {
19300       if (TREE_CODE (expression) == ADDR_EXPR)
19301         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19302       if (TREE_CODE (expression) == COMPONENT_REF
19303           || TREE_CODE (expression) == OFFSET_REF)
19304         {
19305           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19306             return true;
19307           expression = TREE_OPERAND (expression, 1);
19308           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19309             return false;
19310         }
19311       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19312       if (TREE_CODE (expression) == SCOPE_REF)
19313         return false;
19314
19315       if (BASELINK_P (expression))
19316         expression = BASELINK_FUNCTIONS (expression);
19317
19318       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19319         {
19320           if (any_dependent_template_arguments_p
19321               (TREE_OPERAND (expression, 1)))
19322             return true;
19323           expression = TREE_OPERAND (expression, 0);
19324         }
19325       gcc_assert (TREE_CODE (expression) == OVERLOAD
19326                   || TREE_CODE (expression) == FUNCTION_DECL);
19327
19328       while (expression)
19329         {
19330           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19331             return true;
19332           expression = OVL_NEXT (expression);
19333         }
19334       return false;
19335     }
19336
19337   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19338
19339   return (dependent_type_p (TREE_TYPE (expression)));
19340 }
19341
19342 /* Like type_dependent_expression_p, but it also works while not processing
19343    a template definition, i.e. during substitution or mangling.  */
19344
19345 bool
19346 type_dependent_expression_p_push (tree expr)
19347 {
19348   bool b;
19349   ++processing_template_decl;
19350   b = type_dependent_expression_p (expr);
19351   --processing_template_decl;
19352   return b;
19353 }
19354
19355 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19356
19357 bool
19358 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19359 {
19360   unsigned int i;
19361   tree arg;
19362
19363   FOR_EACH_VEC_ELT (tree, args, i, arg)
19364     {
19365       if (type_dependent_expression_p (arg))
19366         return true;
19367     }
19368   return false;
19369 }
19370
19371 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19372    expressions) contains any type-dependent expressions.  */
19373
19374 bool
19375 any_type_dependent_elements_p (const_tree list)
19376 {
19377   for (; list; list = TREE_CHAIN (list))
19378     if (value_dependent_expression_p (TREE_VALUE (list)))
19379       return true;
19380
19381   return false;
19382 }
19383
19384 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19385    expressions) contains any value-dependent expressions.  */
19386
19387 bool
19388 any_value_dependent_elements_p (const_tree list)
19389 {
19390   for (; list; list = TREE_CHAIN (list))
19391     if (value_dependent_expression_p (TREE_VALUE (list)))
19392       return true;
19393
19394   return false;
19395 }
19396
19397 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19398
19399 bool
19400 dependent_template_arg_p (tree arg)
19401 {
19402   if (!processing_template_decl)
19403     return false;
19404
19405   /* Assume a template argument that was wrongly written by the user
19406      is dependent. This is consistent with what
19407      any_dependent_template_arguments_p [that calls this function]
19408      does.  */
19409   if (!arg || arg == error_mark_node)
19410     return true;
19411
19412   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19413     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19414
19415   if (TREE_CODE (arg) == TEMPLATE_DECL
19416       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19417     return dependent_template_p (arg);
19418   else if (ARGUMENT_PACK_P (arg))
19419     {
19420       tree args = ARGUMENT_PACK_ARGS (arg);
19421       int i, len = TREE_VEC_LENGTH (args);
19422       for (i = 0; i < len; ++i)
19423         {
19424           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19425             return true;
19426         }
19427
19428       return false;
19429     }
19430   else if (TYPE_P (arg))
19431     return dependent_type_p (arg);
19432   else
19433     return (type_dependent_expression_p (arg)
19434             || value_dependent_expression_p (arg));
19435 }
19436
19437 /* Returns true if ARGS (a collection of template arguments) contains
19438    any types that require structural equality testing.  */
19439
19440 bool
19441 any_template_arguments_need_structural_equality_p (tree args)
19442 {
19443   int i;
19444   int j;
19445
19446   if (!args)
19447     return false;
19448   if (args == error_mark_node)
19449     return true;
19450
19451   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19452     {
19453       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19454       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19455         {
19456           tree arg = TREE_VEC_ELT (level, j);
19457           tree packed_args = NULL_TREE;
19458           int k, len = 1;
19459
19460           if (ARGUMENT_PACK_P (arg))
19461             {
19462               /* Look inside the argument pack.  */
19463               packed_args = ARGUMENT_PACK_ARGS (arg);
19464               len = TREE_VEC_LENGTH (packed_args);
19465             }
19466
19467           for (k = 0; k < len; ++k)
19468             {
19469               if (packed_args)
19470                 arg = TREE_VEC_ELT (packed_args, k);
19471
19472               if (error_operand_p (arg))
19473                 return true;
19474               else if (TREE_CODE (arg) == TEMPLATE_DECL
19475                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19476                 continue;
19477               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19478                 return true;
19479               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19480                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19481                 return true;
19482             }
19483         }
19484     }
19485
19486   return false;
19487 }
19488
19489 /* Returns true if ARGS (a collection of template arguments) contains
19490    any dependent arguments.  */
19491
19492 bool
19493 any_dependent_template_arguments_p (const_tree args)
19494 {
19495   int i;
19496   int j;
19497
19498   if (!args)
19499     return false;
19500   if (args == error_mark_node)
19501     return true;
19502
19503   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19504     {
19505       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19506       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19507         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19508           return true;
19509     }
19510
19511   return false;
19512 }
19513
19514 /* Returns TRUE if the template TMPL is dependent.  */
19515
19516 bool
19517 dependent_template_p (tree tmpl)
19518 {
19519   if (TREE_CODE (tmpl) == OVERLOAD)
19520     {
19521       while (tmpl)
19522         {
19523           if (dependent_template_p (OVL_CURRENT (tmpl)))
19524             return true;
19525           tmpl = OVL_NEXT (tmpl);
19526         }
19527       return false;
19528     }
19529
19530   /* Template template parameters are dependent.  */
19531   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19532       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19533     return true;
19534   /* So are names that have not been looked up.  */
19535   if (TREE_CODE (tmpl) == SCOPE_REF
19536       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19537     return true;
19538   /* So are member templates of dependent classes.  */
19539   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19540     return dependent_type_p (DECL_CONTEXT (tmpl));
19541   return false;
19542 }
19543
19544 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19545
19546 bool
19547 dependent_template_id_p (tree tmpl, tree args)
19548 {
19549   return (dependent_template_p (tmpl)
19550           || any_dependent_template_arguments_p (args));
19551 }
19552
19553 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19554    is dependent.  */
19555
19556 bool
19557 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19558 {
19559   int i;
19560
19561   if (!processing_template_decl)
19562     return false;
19563
19564   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19565     {
19566       tree decl = TREE_VEC_ELT (declv, i);
19567       tree init = TREE_VEC_ELT (initv, i);
19568       tree cond = TREE_VEC_ELT (condv, i);
19569       tree incr = TREE_VEC_ELT (incrv, i);
19570
19571       if (type_dependent_expression_p (decl))
19572         return true;
19573
19574       if (init && type_dependent_expression_p (init))
19575         return true;
19576
19577       if (type_dependent_expression_p (cond))
19578         return true;
19579
19580       if (COMPARISON_CLASS_P (cond)
19581           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19582               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19583         return true;
19584
19585       if (TREE_CODE (incr) == MODOP_EXPR)
19586         {
19587           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19588               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19589             return true;
19590         }
19591       else if (type_dependent_expression_p (incr))
19592         return true;
19593       else if (TREE_CODE (incr) == MODIFY_EXPR)
19594         {
19595           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19596             return true;
19597           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19598             {
19599               tree t = TREE_OPERAND (incr, 1);
19600               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19601                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19602                 return true;
19603             }
19604         }
19605     }
19606
19607   return false;
19608 }
19609
19610 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19611    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19612    no such TYPE can be found.  Note that this function peers inside
19613    uninstantiated templates and therefore should be used only in
19614    extremely limited situations.  ONLY_CURRENT_P restricts this
19615    peering to the currently open classes hierarchy (which is required
19616    when comparing types).  */
19617
19618 tree
19619 resolve_typename_type (tree type, bool only_current_p)
19620 {
19621   tree scope;
19622   tree name;
19623   tree decl;
19624   int quals;
19625   tree pushed_scope;
19626   tree result;
19627
19628   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19629
19630   scope = TYPE_CONTEXT (type);
19631   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19632      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19633      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19634      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19635      identifier  of the TYPENAME_TYPE anymore.
19636      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19637      TYPENAME_TYPE instead, we avoid messing up with a possible
19638      typedef variant case.  */
19639   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19640
19641   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19642      it first before we can figure out what NAME refers to.  */
19643   if (TREE_CODE (scope) == TYPENAME_TYPE)
19644     scope = resolve_typename_type (scope, only_current_p);
19645   /* If we don't know what SCOPE refers to, then we cannot resolve the
19646      TYPENAME_TYPE.  */
19647   if (TREE_CODE (scope) == TYPENAME_TYPE)
19648     return type;
19649   /* If the SCOPE is a template type parameter, we have no way of
19650      resolving the name.  */
19651   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19652     return type;
19653   /* If the SCOPE is not the current instantiation, there's no reason
19654      to look inside it.  */
19655   if (only_current_p && !currently_open_class (scope))
19656     return type;
19657   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19658   if (typedef_variant_p (type))
19659     return type;
19660   /* If SCOPE isn't the template itself, it will not have a valid
19661      TYPE_FIELDS list.  */
19662   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19663     /* scope is either the template itself or a compatible instantiation
19664        like X<T>, so look up the name in the original template.  */
19665     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19666   else
19667     /* scope is a partial instantiation, so we can't do the lookup or we
19668        will lose the template arguments.  */
19669     return type;
19670   /* Enter the SCOPE so that name lookup will be resolved as if we
19671      were in the class definition.  In particular, SCOPE will no
19672      longer be considered a dependent type.  */
19673   pushed_scope = push_scope (scope);
19674   /* Look up the declaration.  */
19675   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19676
19677   result = NULL_TREE;
19678   
19679   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19680      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19681   if (!decl)
19682     /*nop*/;
19683   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19684            && TREE_CODE (decl) == TYPE_DECL)
19685     {
19686       result = TREE_TYPE (decl);
19687       if (result == error_mark_node)
19688         result = NULL_TREE;
19689     }
19690   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19691            && DECL_CLASS_TEMPLATE_P (decl))
19692     {
19693       tree tmpl;
19694       tree args;
19695       /* Obtain the template and the arguments.  */
19696       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19697       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19698       /* Instantiate the template.  */
19699       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19700                                       /*entering_scope=*/0,
19701                                       tf_error | tf_user);
19702       if (result == error_mark_node)
19703         result = NULL_TREE;
19704     }
19705   
19706   /* Leave the SCOPE.  */
19707   if (pushed_scope)
19708     pop_scope (pushed_scope);
19709
19710   /* If we failed to resolve it, return the original typename.  */
19711   if (!result)
19712     return type;
19713   
19714   /* If lookup found a typename type, resolve that too.  */
19715   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19716     {
19717       /* Ill-formed programs can cause infinite recursion here, so we
19718          must catch that.  */
19719       TYPENAME_IS_RESOLVING_P (type) = 1;
19720       result = resolve_typename_type (result, only_current_p);
19721       TYPENAME_IS_RESOLVING_P (type) = 0;
19722     }
19723   
19724   /* Qualify the resulting type.  */
19725   quals = cp_type_quals (type);
19726   if (quals)
19727     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19728
19729   return result;
19730 }
19731
19732 /* EXPR is an expression which is not type-dependent.  Return a proxy
19733    for EXPR that can be used to compute the types of larger
19734    expressions containing EXPR.  */
19735
19736 tree
19737 build_non_dependent_expr (tree expr)
19738 {
19739   tree inner_expr;
19740
19741 #ifdef ENABLE_CHECKING
19742   /* Try to get a constant value for all non-type-dependent expressions in
19743       order to expose bugs in *_dependent_expression_p and constexpr.  */
19744   if (cxx_dialect >= cxx0x)
19745     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19746 #endif
19747
19748   /* Preserve OVERLOADs; the functions must be available to resolve
19749      types.  */
19750   inner_expr = expr;
19751   if (TREE_CODE (inner_expr) == STMT_EXPR)
19752     inner_expr = stmt_expr_value_expr (inner_expr);
19753   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19754     inner_expr = TREE_OPERAND (inner_expr, 0);
19755   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19756     inner_expr = TREE_OPERAND (inner_expr, 1);
19757   if (is_overloaded_fn (inner_expr)
19758       || TREE_CODE (inner_expr) == OFFSET_REF)
19759     return expr;
19760   /* There is no need to return a proxy for a variable.  */
19761   if (TREE_CODE (expr) == VAR_DECL)
19762     return expr;
19763   /* Preserve string constants; conversions from string constants to
19764      "char *" are allowed, even though normally a "const char *"
19765      cannot be used to initialize a "char *".  */
19766   if (TREE_CODE (expr) == STRING_CST)
19767     return expr;
19768   /* Preserve arithmetic constants, as an optimization -- there is no
19769      reason to create a new node.  */
19770   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19771     return expr;
19772   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19773      There is at least one place where we want to know that a
19774      particular expression is a throw-expression: when checking a ?:
19775      expression, there are special rules if the second or third
19776      argument is a throw-expression.  */
19777   if (TREE_CODE (expr) == THROW_EXPR)
19778     return expr;
19779
19780   /* Don't wrap an initializer list, we need to be able to look inside.  */
19781   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19782     return expr;
19783
19784   if (TREE_CODE (expr) == COND_EXPR)
19785     return build3 (COND_EXPR,
19786                    TREE_TYPE (expr),
19787                    TREE_OPERAND (expr, 0),
19788                    (TREE_OPERAND (expr, 1)
19789                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19790                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19791                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19792   if (TREE_CODE (expr) == COMPOUND_EXPR
19793       && !COMPOUND_EXPR_OVERLOADED (expr))
19794     return build2 (COMPOUND_EXPR,
19795                    TREE_TYPE (expr),
19796                    TREE_OPERAND (expr, 0),
19797                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19798
19799   /* If the type is unknown, it can't really be non-dependent */
19800   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19801
19802   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19803   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19804 }
19805
19806 /* ARGS is a vector of expressions as arguments to a function call.
19807    Replace the arguments with equivalent non-dependent expressions.
19808    This modifies ARGS in place.  */
19809
19810 void
19811 make_args_non_dependent (VEC(tree,gc) *args)
19812 {
19813   unsigned int ix;
19814   tree arg;
19815
19816   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19817     {
19818       tree newarg = build_non_dependent_expr (arg);
19819       if (newarg != arg)
19820         VEC_replace (tree, args, ix, newarg);
19821     }
19822 }
19823
19824 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19825    with a level one deeper than the actual template parms.  */
19826
19827 tree
19828 make_auto (void)
19829 {
19830   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19831   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19832                                TYPE_DECL, get_identifier ("auto"), au);
19833   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19834   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19835     (0, processing_template_decl + 1, processing_template_decl + 1,
19836      0, TYPE_NAME (au), NULL_TREE);
19837   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19838   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19839   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19840
19841   return au;
19842 }
19843
19844 /* Given type ARG, return std::initializer_list<ARG>.  */
19845
19846 static tree
19847 listify (tree arg)
19848 {
19849   tree std_init_list = namespace_binding
19850     (get_identifier ("initializer_list"), std_node);
19851   tree argvec;
19852   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19853     {    
19854       error ("deducing from brace-enclosed initializer list requires "
19855              "#include <initializer_list>");
19856       return error_mark_node;
19857     }
19858   argvec = make_tree_vec (1);
19859   TREE_VEC_ELT (argvec, 0) = arg;
19860   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19861                                 NULL_TREE, 0, tf_warning_or_error);
19862 }
19863
19864 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19865
19866 static tree
19867 listify_autos (tree type, tree auto_node)
19868 {
19869   tree init_auto = listify (auto_node);
19870   tree argvec = make_tree_vec (1);
19871   TREE_VEC_ELT (argvec, 0) = init_auto;
19872   if (processing_template_decl)
19873     argvec = add_to_template_args (current_template_args (), argvec);
19874   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19875 }
19876
19877 /* walk_tree helper for do_auto_deduction.  */
19878
19879 static tree
19880 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19881                  void *type)
19882 {
19883   /* Is this a variable with the type we're looking for?  */
19884   if (DECL_P (*tp)
19885       && TREE_TYPE (*tp) == type)
19886     return *tp;
19887   else
19888     return NULL_TREE;
19889 }
19890
19891 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19892    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19893
19894 tree
19895 do_auto_deduction (tree type, tree init, tree auto_node)
19896 {
19897   tree parms, tparms, targs;
19898   tree args[1];
19899   tree decl;
19900   int val;
19901
19902   if (processing_template_decl
19903       && (TREE_TYPE (init) == NULL_TREE
19904           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19905     /* Not enough information to try this yet.  */
19906     return type;
19907
19908   /* The name of the object being declared shall not appear in the
19909      initializer expression.  */
19910   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19911   if (decl)
19912     {
19913       error ("variable %q#D with %<auto%> type used in its own "
19914              "initializer", decl);
19915       return error_mark_node;
19916     }
19917
19918   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19919      with either a new invented type template parameter U or, if the
19920      initializer is a braced-init-list (8.5.4), with
19921      std::initializer_list<U>.  */
19922   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19923     type = listify_autos (type, auto_node);
19924
19925   init = resolve_nondeduced_context (init);
19926
19927   parms = build_tree_list (NULL_TREE, type);
19928   args[0] = init;
19929   tparms = make_tree_vec (1);
19930   targs = make_tree_vec (1);
19931   TREE_VEC_ELT (tparms, 0)
19932     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19933   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19934                                DEDUCE_CALL, LOOKUP_NORMAL,
19935                                /*explain_p=*/false);
19936   if (val > 0)
19937     {
19938       if (processing_template_decl)
19939         /* Try again at instantiation time.  */
19940         return type;
19941       if (type && type != error_mark_node)
19942         /* If type is error_mark_node a diagnostic must have been
19943            emitted by now.  Also, having a mention to '<type error>'
19944            in the diagnostic is not really useful to the user.  */
19945         error ("unable to deduce %qT from %qE", type, init);
19946       return error_mark_node;
19947     }
19948
19949   /* If the list of declarators contains more than one declarator, the type
19950      of each declared variable is determined as described above. If the
19951      type deduced for the template parameter U is not the same in each
19952      deduction, the program is ill-formed.  */
19953   if (TREE_TYPE (auto_node)
19954       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19955     {
19956       error ("inconsistent deduction for %qT: %qT and then %qT",
19957              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19958       return error_mark_node;
19959     }
19960   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19961
19962   if (processing_template_decl)
19963     targs = add_to_template_args (current_template_args (), targs);
19964   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19965 }
19966
19967 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19968    result.  */
19969
19970 tree
19971 splice_late_return_type (tree type, tree late_return_type)
19972 {
19973   tree argvec;
19974
19975   if (late_return_type == NULL_TREE)
19976     return type;
19977   argvec = make_tree_vec (1);
19978   TREE_VEC_ELT (argvec, 0) = late_return_type;
19979   if (processing_template_parmlist)
19980     /* For a late-specified return type in a template type-parameter, we
19981        need to add a dummy argument level for its parmlist.  */
19982     argvec = add_to_template_args
19983       (make_tree_vec (processing_template_parmlist), argvec);
19984   if (current_template_parms)
19985     argvec = add_to_template_args (current_template_args (), argvec);
19986   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19987 }
19988
19989 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19990
19991 bool
19992 is_auto (const_tree type)
19993 {
19994   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19995       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19996     return true;
19997   else
19998     return false;
19999 }
20000
20001 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
20002    appear as a type-specifier for the declaration in question, we don't
20003    have to look through the whole type.  */
20004
20005 tree
20006 type_uses_auto (tree type)
20007 {
20008   enum tree_code code;
20009   if (is_auto (type))
20010     return type;
20011
20012   code = TREE_CODE (type);
20013
20014   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20015       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20016       || code == METHOD_TYPE || code == ARRAY_TYPE)
20017     return type_uses_auto (TREE_TYPE (type));
20018
20019   if (TYPE_PTRMEMFUNC_P (type))
20020     return type_uses_auto (TREE_TYPE (TREE_TYPE
20021                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20022
20023   return NULL_TREE;
20024 }
20025
20026 /* For a given template T, return the vector of typedefs referenced
20027    in T for which access check is needed at T instantiation time.
20028    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20029    Those typedefs were added to T by the function
20030    append_type_to_template_for_access_check.  */
20031
20032 VEC(qualified_typedef_usage_t,gc)*
20033 get_types_needing_access_check (tree t)
20034 {
20035   tree ti;
20036   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20037
20038   if (!t || t == error_mark_node)
20039     return NULL;
20040
20041   if (!(ti = get_template_info (t)))
20042     return NULL;
20043
20044   if (CLASS_TYPE_P (t)
20045       || TREE_CODE (t) == FUNCTION_DECL)
20046     {
20047       if (!TI_TEMPLATE (ti))
20048         return NULL;
20049
20050       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20051     }
20052
20053   return result;
20054 }
20055
20056 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20057    tied to T. That list of typedefs will be access checked at
20058    T instantiation time.
20059    T is either a FUNCTION_DECL or a RECORD_TYPE.
20060    TYPE_DECL is a TYPE_DECL node representing a typedef.
20061    SCOPE is the scope through which TYPE_DECL is accessed.
20062    LOCATION is the location of the usage point of TYPE_DECL.
20063
20064    This function is a subroutine of
20065    append_type_to_template_for_access_check.  */
20066
20067 static void
20068 append_type_to_template_for_access_check_1 (tree t,
20069                                             tree type_decl,
20070                                             tree scope,
20071                                             location_t location)
20072 {
20073   qualified_typedef_usage_t typedef_usage;
20074   tree ti;
20075
20076   if (!t || t == error_mark_node)
20077     return;
20078
20079   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20080                || CLASS_TYPE_P (t))
20081               && type_decl
20082               && TREE_CODE (type_decl) == TYPE_DECL
20083               && scope);
20084
20085   if (!(ti = get_template_info (t)))
20086     return;
20087
20088   gcc_assert (TI_TEMPLATE (ti));
20089
20090   typedef_usage.typedef_decl = type_decl;
20091   typedef_usage.context = scope;
20092   typedef_usage.locus = location;
20093
20094   VEC_safe_push (qualified_typedef_usage_t, gc,
20095                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20096                  &typedef_usage);
20097 }
20098
20099 /* Append TYPE_DECL to the template TEMPL.
20100    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20101    At TEMPL instanciation time, TYPE_DECL will be checked to see
20102    if it can be accessed through SCOPE.
20103    LOCATION is the location of the usage point of TYPE_DECL.
20104
20105    e.g. consider the following code snippet:
20106
20107      class C
20108      {
20109        typedef int myint;
20110      };
20111
20112      template<class U> struct S
20113      {
20114        C::myint mi; // <-- usage point of the typedef C::myint
20115      };
20116
20117      S<char> s;
20118
20119    At S<char> instantiation time, we need to check the access of C::myint
20120    In other words, we need to check the access of the myint typedef through
20121    the C scope. For that purpose, this function will add the myint typedef
20122    and the scope C through which its being accessed to a list of typedefs
20123    tied to the template S. That list will be walked at template instantiation
20124    time and access check performed on each typedefs it contains.
20125    Note that this particular code snippet should yield an error because
20126    myint is private to C.  */
20127
20128 void
20129 append_type_to_template_for_access_check (tree templ,
20130                                           tree type_decl,
20131                                           tree scope,
20132                                           location_t location)
20133 {
20134   qualified_typedef_usage_t *iter;
20135   int i;
20136
20137   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20138
20139   /* Make sure we don't append the type to the template twice.  */
20140   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20141                     get_types_needing_access_check (templ),
20142                     i, iter)
20143     if (iter->typedef_decl == type_decl && scope == iter->context)
20144       return;
20145
20146   append_type_to_template_for_access_check_1 (templ, type_decl,
20147                                               scope, location);
20148 }
20149
20150 /* Set up the hash tables for template instantiations.  */
20151
20152 void
20153 init_template_processing (void)
20154 {
20155   decl_specializations = htab_create_ggc (37,
20156                                           hash_specialization,
20157                                           eq_specializations,
20158                                           ggc_free);
20159   type_specializations = htab_create_ggc (37,
20160                                           hash_specialization,
20161                                           eq_specializations,
20162                                           ggc_free);
20163 }
20164
20165 /* Print stats about the template hash tables for -fstats.  */
20166
20167 void
20168 print_template_statistics (void)
20169 {
20170   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20171            "%f collisions\n", (long) htab_size (decl_specializations),
20172            (long) htab_elements (decl_specializations),
20173            htab_collisions (decl_specializations));
20174   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20175            "%f collisions\n", (long) htab_size (type_specializations),
20176            (long) htab_elements (type_specializations),
20177            htab_collisions (type_specializations));
20178 }
20179
20180 #include "gt-cp-pt.h"