OSDN Git Service

PR c++/35688
[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++11 or -std=gnu++11");
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       /* Adjust visibility for template arguments.  */
8604       determine_visibility (TYPE_MAIN_DECL (type));
8605     }
8606   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8607
8608   pbinfo = TYPE_BINFO (pattern);
8609
8610   /* We should never instantiate a nested class before its enclosing
8611      class; we need to look up the nested class by name before we can
8612      instantiate it, and that lookup should instantiate the enclosing
8613      class.  */
8614   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8615               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8616
8617   base_list = NULL_TREE;
8618   if (BINFO_N_BASE_BINFOS (pbinfo))
8619     {
8620       tree pbase_binfo;
8621       tree pushed_scope;
8622       int i;
8623
8624       /* We must enter the scope containing the type, as that is where
8625          the accessibility of types named in dependent bases are
8626          looked up from.  */
8627       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8628
8629       /* Substitute into each of the bases to determine the actual
8630          basetypes.  */
8631       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8632         {
8633           tree base;
8634           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8635           tree expanded_bases = NULL_TREE;
8636           int idx, len = 1;
8637
8638           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8639             {
8640               expanded_bases = 
8641                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8642                                        args, tf_error, NULL_TREE);
8643               if (expanded_bases == error_mark_node)
8644                 continue;
8645
8646               len = TREE_VEC_LENGTH (expanded_bases);
8647             }
8648
8649           for (idx = 0; idx < len; idx++)
8650             {
8651               if (expanded_bases)
8652                 /* Extract the already-expanded base class.  */
8653                 base = TREE_VEC_ELT (expanded_bases, idx);
8654               else
8655                 /* Substitute to figure out the base class.  */
8656                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8657                                NULL_TREE);
8658
8659               if (base == error_mark_node)
8660                 continue;
8661
8662               base_list = tree_cons (access, base, base_list);
8663               if (BINFO_VIRTUAL_P (pbase_binfo))
8664                 TREE_TYPE (base_list) = integer_type_node;
8665             }
8666         }
8667
8668       /* The list is now in reverse order; correct that.  */
8669       base_list = nreverse (base_list);
8670
8671       if (pushed_scope)
8672         pop_scope (pushed_scope);
8673     }
8674   /* Now call xref_basetypes to set up all the base-class
8675      information.  */
8676   xref_basetypes (type, base_list);
8677
8678   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8679                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8680                                   args, tf_error, NULL_TREE);
8681   fixup_attribute_variants (type);
8682
8683   /* Now that our base classes are set up, enter the scope of the
8684      class, so that name lookups into base classes, etc. will work
8685      correctly.  This is precisely analogous to what we do in
8686      begin_class_definition when defining an ordinary non-template
8687      class, except we also need to push the enclosing classes.  */
8688   push_nested_class (type);
8689
8690   /* Now members are processed in the order of declaration.  */
8691   for (member = CLASSTYPE_DECL_LIST (pattern);
8692        member; member = TREE_CHAIN (member))
8693     {
8694       tree t = TREE_VALUE (member);
8695
8696       if (TREE_PURPOSE (member))
8697         {
8698           if (TYPE_P (t))
8699             {
8700               /* Build new CLASSTYPE_NESTED_UTDS.  */
8701
8702               tree newtag;
8703               bool class_template_p;
8704
8705               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8706                                   && TYPE_LANG_SPECIFIC (t)
8707                                   && CLASSTYPE_IS_TEMPLATE (t));
8708               /* If the member is a class template, then -- even after
8709                  substitution -- there may be dependent types in the
8710                  template argument list for the class.  We increment
8711                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8712                  that function will assume that no types are dependent
8713                  when outside of a template.  */
8714               if (class_template_p)
8715                 ++processing_template_decl;
8716               newtag = tsubst (t, args, tf_error, NULL_TREE);
8717               if (class_template_p)
8718                 --processing_template_decl;
8719               if (newtag == error_mark_node)
8720                 continue;
8721
8722               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8723                 {
8724                   tree name = TYPE_IDENTIFIER (t);
8725
8726                   if (class_template_p)
8727                     /* Unfortunately, lookup_template_class sets
8728                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8729                        instantiation (i.e., for the type of a member
8730                        template class nested within a template class.)
8731                        This behavior is required for
8732                        maybe_process_partial_specialization to work
8733                        correctly, but is not accurate in this case;
8734                        the TAG is not an instantiation of anything.
8735                        (The corresponding TEMPLATE_DECL is an
8736                        instantiation, but the TYPE is not.) */
8737                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8738
8739                   /* Now, we call pushtag to put this NEWTAG into the scope of
8740                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8741                      pushtag calling push_template_decl.  We don't have to do
8742                      this for enums because it will already have been done in
8743                      tsubst_enum.  */
8744                   if (name)
8745                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8746                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8747                 }
8748             }
8749           else if (TREE_CODE (t) == FUNCTION_DECL
8750                    || DECL_FUNCTION_TEMPLATE_P (t))
8751             {
8752               /* Build new TYPE_METHODS.  */
8753               tree r;
8754
8755               if (TREE_CODE (t) == TEMPLATE_DECL)
8756                 ++processing_template_decl;
8757               r = tsubst (t, args, tf_error, NULL_TREE);
8758               if (TREE_CODE (t) == TEMPLATE_DECL)
8759                 --processing_template_decl;
8760               set_current_access_from_decl (r);
8761               finish_member_declaration (r);
8762               /* Instantiate members marked with attribute used.  */
8763               if (r != error_mark_node && DECL_PRESERVE_P (r))
8764                 mark_used (r);
8765             }
8766           else
8767             {
8768               /* Build new TYPE_FIELDS.  */
8769               if (TREE_CODE (t) == STATIC_ASSERT)
8770                 {
8771                   tree condition = 
8772                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8773                                  tf_warning_or_error, NULL_TREE,
8774                                  /*integral_constant_expression_p=*/true);
8775                   finish_static_assert (condition,
8776                                         STATIC_ASSERT_MESSAGE (t), 
8777                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8778                                         /*member_p=*/true);
8779                 }
8780               else if (TREE_CODE (t) != CONST_DECL)
8781                 {
8782                   tree r;
8783
8784                   /* The file and line for this declaration, to
8785                      assist in error message reporting.  Since we
8786                      called push_tinst_level above, we don't need to
8787                      restore these.  */
8788                   input_location = DECL_SOURCE_LOCATION (t);
8789
8790                   if (TREE_CODE (t) == TEMPLATE_DECL)
8791                     ++processing_template_decl;
8792                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8793                   if (TREE_CODE (t) == TEMPLATE_DECL)
8794                     --processing_template_decl;
8795                   if (TREE_CODE (r) == VAR_DECL)
8796                     {
8797                       /* In [temp.inst]:
8798
8799                            [t]he initialization (and any associated
8800                            side-effects) of a static data member does
8801                            not occur unless the static data member is
8802                            itself used in a way that requires the
8803                            definition of the static data member to
8804                            exist.
8805
8806                          Therefore, we do not substitute into the
8807                          initialized for the static data member here.  */
8808                       finish_static_data_member_decl
8809                         (r,
8810                          /*init=*/NULL_TREE,
8811                          /*init_const_expr_p=*/false,
8812                          /*asmspec_tree=*/NULL_TREE,
8813                          /*flags=*/0);
8814                       /* Instantiate members marked with attribute used.  */
8815                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8816                         mark_used (r);
8817                     }
8818                   else if (TREE_CODE (r) == FIELD_DECL)
8819                     {
8820                       /* Determine whether R has a valid type and can be
8821                          completed later.  If R is invalid, then it is
8822                          replaced by error_mark_node so that it will not be
8823                          added to TYPE_FIELDS.  */
8824                       tree rtype = TREE_TYPE (r);
8825                       if (can_complete_type_without_circularity (rtype))
8826                         complete_type (rtype);
8827
8828                       if (!COMPLETE_TYPE_P (rtype))
8829                         {
8830                           cxx_incomplete_type_error (r, rtype);
8831                           r = error_mark_node;
8832                         }
8833                     }
8834
8835                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8836                      such a thing will already have been added to the field
8837                      list by tsubst_enum in finish_member_declaration in the
8838                      CLASSTYPE_NESTED_UTDS case above.  */
8839                   if (!(TREE_CODE (r) == TYPE_DECL
8840                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8841                         && DECL_ARTIFICIAL (r)))
8842                     {
8843                       set_current_access_from_decl (r);
8844                       finish_member_declaration (r);
8845                     }
8846                 }
8847             }
8848         }
8849       else
8850         {
8851           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8852             {
8853               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8854
8855               tree friend_type = t;
8856               bool adjust_processing_template_decl = false;
8857
8858               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8859                 {
8860                   /* template <class T> friend class C;  */
8861                   friend_type = tsubst_friend_class (friend_type, args);
8862                   adjust_processing_template_decl = true;
8863                 }
8864               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8865                 {
8866                   /* template <class T> friend class C::D;  */
8867                   friend_type = tsubst (friend_type, args,
8868                                         tf_warning_or_error, NULL_TREE);
8869                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8870                     friend_type = TREE_TYPE (friend_type);
8871                   adjust_processing_template_decl = true;
8872                 }
8873               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8874                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8875                 {
8876                   /* This could be either
8877
8878                        friend class T::C;
8879
8880                      when dependent_type_p is false or
8881
8882                        template <class U> friend class T::C;
8883
8884                      otherwise.  */
8885                   friend_type = tsubst (friend_type, args,
8886                                         tf_warning_or_error, NULL_TREE);
8887                   /* Bump processing_template_decl for correct
8888                      dependent_type_p calculation.  */
8889                   ++processing_template_decl;
8890                   if (dependent_type_p (friend_type))
8891                     adjust_processing_template_decl = true;
8892                   --processing_template_decl;
8893                 }
8894               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8895                        && hidden_name_p (TYPE_NAME (friend_type)))
8896                 {
8897                   /* friend class C;
8898
8899                      where C hasn't been declared yet.  Let's lookup name
8900                      from namespace scope directly, bypassing any name that
8901                      come from dependent base class.  */
8902                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8903
8904                   /* The call to xref_tag_from_type does injection for friend
8905                      classes.  */
8906                   push_nested_namespace (ns);
8907                   friend_type =
8908                     xref_tag_from_type (friend_type, NULL_TREE,
8909                                         /*tag_scope=*/ts_current);
8910                   pop_nested_namespace (ns);
8911                 }
8912               else if (uses_template_parms (friend_type))
8913                 /* friend class C<T>;  */
8914                 friend_type = tsubst (friend_type, args,
8915                                       tf_warning_or_error, NULL_TREE);
8916               /* Otherwise it's
8917
8918                    friend class C;
8919
8920                  where C is already declared or
8921
8922                    friend class C<int>;
8923
8924                  We don't have to do anything in these cases.  */
8925
8926               if (adjust_processing_template_decl)
8927                 /* Trick make_friend_class into realizing that the friend
8928                    we're adding is a template, not an ordinary class.  It's
8929                    important that we use make_friend_class since it will
8930                    perform some error-checking and output cross-reference
8931                    information.  */
8932                 ++processing_template_decl;
8933
8934               if (friend_type != error_mark_node)
8935                 make_friend_class (type, friend_type, /*complain=*/false);
8936
8937               if (adjust_processing_template_decl)
8938                 --processing_template_decl;
8939             }
8940           else
8941             {
8942               /* Build new DECL_FRIENDLIST.  */
8943               tree r;
8944
8945               /* The file and line for this declaration, to
8946                  assist in error message reporting.  Since we
8947                  called push_tinst_level above, we don't need to
8948                  restore these.  */
8949               input_location = DECL_SOURCE_LOCATION (t);
8950
8951               if (TREE_CODE (t) == TEMPLATE_DECL)
8952                 {
8953                   ++processing_template_decl;
8954                   push_deferring_access_checks (dk_no_check);
8955                 }
8956
8957               r = tsubst_friend_function (t, args);
8958               add_friend (type, r, /*complain=*/false);
8959               if (TREE_CODE (t) == TEMPLATE_DECL)
8960                 {
8961                   pop_deferring_access_checks ();
8962                   --processing_template_decl;
8963                 }
8964             }
8965         }
8966     }
8967
8968   if (CLASSTYPE_LAMBDA_EXPR (type))
8969     {
8970       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8971       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8972         {
8973           apply_lambda_return_type (lambda, void_type_node);
8974           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8975         }
8976       instantiate_decl (lambda_function (type), false, false);
8977       maybe_add_lambda_conv_op (type);
8978     }
8979
8980   /* Set the file and line number information to whatever is given for
8981      the class itself.  This puts error messages involving generated
8982      implicit functions at a predictable point, and the same point
8983      that would be used for non-template classes.  */
8984   input_location = DECL_SOURCE_LOCATION (typedecl);
8985
8986   unreverse_member_declarations (type);
8987   finish_struct_1 (type);
8988   TYPE_BEING_DEFINED (type) = 0;
8989
8990   /* We don't instantiate default arguments for member functions.  14.7.1:
8991
8992      The implicit instantiation of a class template specialization causes
8993      the implicit instantiation of the declarations, but not of the
8994      definitions or default arguments, of the class member functions,
8995      member classes, static data members and member templates....  */
8996
8997   /* Some typedefs referenced from within the template code need to be access
8998      checked at template instantiation time, i.e now. These types were
8999      added to the template at parsing time. Let's get those and perform
9000      the access checks then.  */
9001   perform_typedefs_access_check (pattern, args);
9002   perform_deferred_access_checks ();
9003   pop_nested_class ();
9004   maximum_field_alignment = saved_maximum_field_alignment;
9005   pop_from_top_level ();
9006   pop_deferring_access_checks ();
9007   pop_tinst_level ();
9008
9009   /* The vtable for a template class can be emitted in any translation
9010      unit in which the class is instantiated.  When there is no key
9011      method, however, finish_struct_1 will already have added TYPE to
9012      the keyed_classes list.  */
9013   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9014     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9015
9016   return type;
9017 }
9018
9019 /* Wrapper for instantiate_class_template_1.  */
9020
9021 tree
9022 instantiate_class_template (tree type)
9023 {
9024   tree ret;
9025   timevar_push (TV_TEMPLATE_INST);
9026   ret = instantiate_class_template_1 (type);
9027   timevar_pop (TV_TEMPLATE_INST);
9028   return ret;
9029 }
9030
9031 static tree
9032 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9033 {
9034   tree r;
9035
9036   if (!t)
9037     r = t;
9038   else if (TYPE_P (t))
9039     r = tsubst (t, args, complain, in_decl);
9040   else
9041     {
9042       if (!(complain & tf_warning))
9043         ++c_inhibit_evaluation_warnings;
9044       r = tsubst_expr (t, args, complain, in_decl,
9045                        /*integral_constant_expression_p=*/true);
9046       if (!(complain & tf_warning))
9047         --c_inhibit_evaluation_warnings;
9048       /* Preserve the raw-reference nature of T.  */
9049       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9050           && REFERENCE_REF_P (r))
9051         r = TREE_OPERAND (r, 0);
9052     }
9053   return r;
9054 }
9055
9056 /* Given a function parameter pack TMPL_PARM and some function parameters
9057    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9058    and set *SPEC_P to point at the next point in the list.  */
9059
9060 static tree
9061 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9062 {
9063   /* Collect all of the extra "packed" parameters into an
9064      argument pack.  */
9065   tree parmvec;
9066   tree parmtypevec;
9067   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9068   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9069   tree spec_parm = *spec_p;
9070   int i, len;
9071
9072   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9073     if (tmpl_parm
9074         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9075       break;
9076
9077   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9078   parmvec = make_tree_vec (len);
9079   parmtypevec = make_tree_vec (len);
9080   spec_parm = *spec_p;
9081   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9082     {
9083       TREE_VEC_ELT (parmvec, i) = spec_parm;
9084       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9085     }
9086
9087   /* Build the argument packs.  */
9088   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9089   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9090   TREE_TYPE (argpack) = argtypepack;
9091   *spec_p = spec_parm;
9092
9093   return argpack;
9094 }
9095
9096 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9097    NONTYPE_ARGUMENT_PACK.  */
9098
9099 static tree
9100 make_fnparm_pack (tree spec_parm)
9101 {
9102   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9103 }
9104
9105 /* Substitute ARGS into T, which is an pack expansion
9106    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9107    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9108    (if only a partial substitution could be performed) or
9109    ERROR_MARK_NODE if there was an error.  */
9110 tree
9111 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9112                        tree in_decl)
9113 {
9114   tree pattern;
9115   tree pack, packs = NULL_TREE;
9116   bool unsubstituted_packs = false;
9117   int i, len = -1;
9118   tree result;
9119   htab_t saved_local_specializations = NULL;
9120
9121   gcc_assert (PACK_EXPANSION_P (t));
9122   pattern = PACK_EXPANSION_PATTERN (t);
9123
9124   /* Determine the argument packs that will instantiate the parameter
9125      packs used in the expansion expression. While we're at it,
9126      compute the number of arguments to be expanded and make sure it
9127      is consistent.  */
9128   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9129        pack = TREE_CHAIN (pack))
9130     {
9131       tree parm_pack = TREE_VALUE (pack);
9132       tree arg_pack = NULL_TREE;
9133       tree orig_arg = NULL_TREE;
9134
9135       if (TREE_CODE (parm_pack) == BASES)
9136        {
9137          if (BASES_DIRECT (parm_pack))
9138            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9139                                                         args, complain, in_decl, false));
9140          else
9141            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9142                                                  args, complain, in_decl, false));
9143        }
9144       if (TREE_CODE (parm_pack) == PARM_DECL)
9145         {
9146           if (!cp_unevaluated_operand)
9147             arg_pack = retrieve_local_specialization (parm_pack);
9148           else
9149             {
9150               /* We can't rely on local_specializations for a parameter
9151                  name used later in a function declaration (such as in a
9152                  late-specified return type).  Even if it exists, it might
9153                  have the wrong value for a recursive call.  Just make a
9154                  dummy decl, since it's only used for its type.  */
9155               arg_pack = tsubst_decl (parm_pack, args, complain);
9156               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9157                 /* Partial instantiation of the parm_pack, we can't build
9158                    up an argument pack yet.  */
9159                 arg_pack = NULL_TREE;
9160               else
9161                 arg_pack = make_fnparm_pack (arg_pack);
9162             }
9163         }
9164       else
9165         {
9166           int level, idx, levels;
9167           template_parm_level_and_index (parm_pack, &level, &idx);
9168
9169           levels = TMPL_ARGS_DEPTH (args);
9170           if (level <= levels)
9171             arg_pack = TMPL_ARG (args, level, idx);
9172         }
9173
9174       orig_arg = arg_pack;
9175       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9176         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9177       
9178       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9179         /* This can only happen if we forget to expand an argument
9180            pack somewhere else. Just return an error, silently.  */
9181         {
9182           result = make_tree_vec (1);
9183           TREE_VEC_ELT (result, 0) = error_mark_node;
9184           return result;
9185         }
9186
9187       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9188         /* The argument pack that the parameter maps to is just an
9189            expansion of the parameter itself, such as one would find
9190            in the implicit typedef of a class inside the class itself.
9191            Consider this parameter "unsubstituted", so that we will
9192            maintain the outer pack expansion.  */
9193         arg_pack = NULL_TREE;
9194           
9195       if (arg_pack)
9196         {
9197           int my_len = 
9198             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9199
9200           /* Don't bother trying to do a partial substitution with
9201              incomplete packs; we'll try again after deduction.  */
9202           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9203             return t;
9204
9205           if (len < 0)
9206             len = my_len;
9207           else if (len != my_len)
9208             {
9209               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9210                 error ("mismatched argument pack lengths while expanding "
9211                        "%<%T%>",
9212                        pattern);
9213               else
9214                 error ("mismatched argument pack lengths while expanding "
9215                        "%<%E%>",
9216                        pattern);
9217               return error_mark_node;
9218             }
9219
9220           /* Keep track of the parameter packs and their corresponding
9221              argument packs.  */
9222           packs = tree_cons (parm_pack, arg_pack, packs);
9223           TREE_TYPE (packs) = orig_arg;
9224         }
9225       else
9226         {
9227           /* We can't substitute for this parameter pack.  */
9228           unsubstituted_packs = true;
9229           break;
9230         }
9231     }
9232
9233   /* We cannot expand this expansion expression, because we don't have
9234      all of the argument packs we need. Substitute into the pattern
9235      and return a PACK_EXPANSION_*. The caller will need to deal with
9236      that.  */
9237   if (unsubstituted_packs)
9238     {
9239       tree new_pat;
9240       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9241         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9242                                /*integral_constant_expression_p=*/false);
9243       else
9244         new_pat = tsubst (pattern, args, complain, in_decl);
9245       return make_pack_expansion (new_pat);
9246     }
9247
9248   /* We could not find any argument packs that work.  */
9249   if (len < 0)
9250     return error_mark_node;
9251
9252   if (cp_unevaluated_operand)
9253     {
9254       /* We're in a late-specified return type, so create our own local
9255          specializations table; the current table is either NULL or (in the
9256          case of recursive unification) might have bindings that we don't
9257          want to use or alter.  */
9258       saved_local_specializations = local_specializations;
9259       local_specializations = htab_create (37,
9260                                            hash_local_specialization,
9261                                            eq_local_specializations,
9262                                            NULL);
9263     }
9264
9265   /* For each argument in each argument pack, substitute into the
9266      pattern.  */
9267   result = make_tree_vec (len);
9268   for (i = 0; i < len; ++i)
9269     {
9270       /* For parameter pack, change the substitution of the parameter
9271          pack to the ith argument in its argument pack, then expand
9272          the pattern.  */
9273       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9274         {
9275           tree parm = TREE_PURPOSE (pack);
9276           tree arg;
9277
9278           /* Select the Ith argument from the pack.  */
9279           if (TREE_CODE (parm) == PARM_DECL)
9280             {
9281               if (i == 0)
9282                 {
9283                   arg = make_node (ARGUMENT_PACK_SELECT);
9284                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9285                   mark_used (parm);
9286                   register_local_specialization (arg, parm);
9287                 }
9288               else
9289                 arg = retrieve_local_specialization (parm);
9290             }
9291           else
9292             {
9293               int idx, level;
9294               template_parm_level_and_index (parm, &level, &idx);
9295
9296               if (i == 0)
9297                 {
9298                   arg = make_node (ARGUMENT_PACK_SELECT);
9299                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9300                   /* Update the corresponding argument.  */
9301                   TMPL_ARG (args, level, idx) = arg;
9302                 }
9303               else
9304                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9305                 arg = TMPL_ARG (args, level, idx);
9306             }
9307           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9308         }
9309
9310       /* Substitute into the PATTERN with the altered arguments.  */
9311       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9312         TREE_VEC_ELT (result, i) = 
9313           tsubst_expr (pattern, args, complain, in_decl,
9314                        /*integral_constant_expression_p=*/false);
9315       else
9316         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9317
9318       if (TREE_VEC_ELT (result, i) == error_mark_node)
9319         {
9320           result = error_mark_node;
9321           break;
9322         }
9323     }
9324
9325   /* Update ARGS to restore the substitution from parameter packs to
9326      their argument packs.  */
9327   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9328     {
9329       tree parm = TREE_PURPOSE (pack);
9330
9331       if (TREE_CODE (parm) == PARM_DECL)
9332         register_local_specialization (TREE_TYPE (pack), parm);
9333       else
9334         {
9335           int idx, level;
9336           template_parm_level_and_index (parm, &level, &idx);
9337           
9338           /* Update the corresponding argument.  */
9339           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9340             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9341               TREE_TYPE (pack);
9342           else
9343             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9344         }
9345     }
9346
9347   if (saved_local_specializations)
9348     {
9349       htab_delete (local_specializations);
9350       local_specializations = saved_local_specializations;
9351     }
9352   
9353   return result;
9354 }
9355
9356 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9357    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9358    parameter packs; all parms generated from a function parameter pack will
9359    have the same DECL_PARM_INDEX.  */
9360
9361 tree
9362 get_pattern_parm (tree parm, tree tmpl)
9363 {
9364   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9365   tree patparm;
9366
9367   if (DECL_ARTIFICIAL (parm))
9368     {
9369       for (patparm = DECL_ARGUMENTS (pattern);
9370            patparm; patparm = DECL_CHAIN (patparm))
9371         if (DECL_ARTIFICIAL (patparm)
9372             && DECL_NAME (parm) == DECL_NAME (patparm))
9373           break;
9374     }
9375   else
9376     {
9377       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9378       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9379       gcc_assert (DECL_PARM_INDEX (patparm)
9380                   == DECL_PARM_INDEX (parm));
9381     }
9382
9383   return patparm;
9384 }
9385
9386 /* Substitute ARGS into the vector or list of template arguments T.  */
9387
9388 static tree
9389 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9390 {
9391   tree orig_t = t;
9392   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9393   tree *elts;
9394
9395   if (t == error_mark_node)
9396     return error_mark_node;
9397
9398   len = TREE_VEC_LENGTH (t);
9399   elts = XALLOCAVEC (tree, len);
9400
9401   for (i = 0; i < len; i++)
9402     {
9403       tree orig_arg = TREE_VEC_ELT (t, i);
9404       tree new_arg;
9405
9406       if (TREE_CODE (orig_arg) == TREE_VEC)
9407         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9408       else if (PACK_EXPANSION_P (orig_arg))
9409         {
9410           /* Substitute into an expansion expression.  */
9411           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9412
9413           if (TREE_CODE (new_arg) == TREE_VEC)
9414             /* Add to the expanded length adjustment the number of
9415                expanded arguments. We subtract one from this
9416                measurement, because the argument pack expression
9417                itself is already counted as 1 in
9418                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9419                the argument pack is empty.  */
9420             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9421         }
9422       else if (ARGUMENT_PACK_P (orig_arg))
9423         {
9424           /* Substitute into each of the arguments.  */
9425           new_arg = TYPE_P (orig_arg)
9426             ? cxx_make_type (TREE_CODE (orig_arg))
9427             : make_node (TREE_CODE (orig_arg));
9428           
9429           SET_ARGUMENT_PACK_ARGS (
9430             new_arg,
9431             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9432                                   args, complain, in_decl));
9433
9434           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9435             new_arg = error_mark_node;
9436
9437           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9438             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9439                                           complain, in_decl);
9440             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9441
9442             if (TREE_TYPE (new_arg) == error_mark_node)
9443               new_arg = error_mark_node;
9444           }
9445         }
9446       else
9447         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9448
9449       if (new_arg == error_mark_node)
9450         return error_mark_node;
9451
9452       elts[i] = new_arg;
9453       if (new_arg != orig_arg)
9454         need_new = 1;
9455     }
9456
9457   if (!need_new)
9458     return t;
9459
9460   /* Make space for the expanded arguments coming from template
9461      argument packs.  */
9462   t = make_tree_vec (len + expanded_len_adjust);
9463   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9464      arguments for a member template.
9465      In that case each TREE_VEC in ORIG_T represents a level of template
9466      arguments, and ORIG_T won't carry any non defaulted argument count.
9467      It will rather be the nested TREE_VECs that will carry one.
9468      In other words, ORIG_T carries a non defaulted argument count only
9469      if it doesn't contain any nested TREE_VEC.  */
9470   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9471     {
9472       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9473       count += expanded_len_adjust;
9474       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9475     }
9476   for (i = 0, out = 0; i < len; i++)
9477     {
9478       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9479            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9480           && TREE_CODE (elts[i]) == TREE_VEC)
9481         {
9482           int idx;
9483
9484           /* Now expand the template argument pack "in place".  */
9485           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9486             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9487         }
9488       else
9489         {
9490           TREE_VEC_ELT (t, out) = elts[i];
9491           out++;
9492         }
9493     }
9494
9495   return t;
9496 }
9497
9498 /* Return the result of substituting ARGS into the template parameters
9499    given by PARMS.  If there are m levels of ARGS and m + n levels of
9500    PARMS, then the result will contain n levels of PARMS.  For
9501    example, if PARMS is `template <class T> template <class U>
9502    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9503    result will be `template <int*, double, class V>'.  */
9504
9505 static tree
9506 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9507 {
9508   tree r = NULL_TREE;
9509   tree* new_parms;
9510
9511   /* When substituting into a template, we must set
9512      PROCESSING_TEMPLATE_DECL as the template parameters may be
9513      dependent if they are based on one-another, and the dependency
9514      predicates are short-circuit outside of templates.  */
9515   ++processing_template_decl;
9516
9517   for (new_parms = &r;
9518        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9519        new_parms = &(TREE_CHAIN (*new_parms)),
9520          parms = TREE_CHAIN (parms))
9521     {
9522       tree new_vec =
9523         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9524       int i;
9525
9526       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9527         {
9528           tree tuple;
9529
9530           if (parms == error_mark_node)
9531             continue;
9532
9533           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9534
9535           if (tuple == error_mark_node)
9536             continue;
9537
9538           TREE_VEC_ELT (new_vec, i) =
9539             tsubst_template_parm (tuple, args, complain);
9540         }
9541
9542       *new_parms =
9543         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9544                              - TMPL_ARGS_DEPTH (args)),
9545                    new_vec, NULL_TREE);
9546     }
9547
9548   --processing_template_decl;
9549
9550   return r;
9551 }
9552
9553 /* Return the result of substituting ARGS into one template parameter
9554    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9555    parameter and which TREE_PURPOSE is the default argument of the
9556    template parameter.  */
9557
9558 static tree
9559 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9560 {
9561   tree default_value, parm_decl;
9562
9563   if (args == NULL_TREE
9564       || t == NULL_TREE
9565       || t == error_mark_node)
9566     return t;
9567
9568   gcc_assert (TREE_CODE (t) == TREE_LIST);
9569
9570   default_value = TREE_PURPOSE (t);
9571   parm_decl = TREE_VALUE (t);
9572
9573   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9574   if (TREE_CODE (parm_decl) == PARM_DECL
9575       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9576     parm_decl = error_mark_node;
9577   default_value = tsubst_template_arg (default_value, args,
9578                                        complain, NULL_TREE);
9579
9580   return build_tree_list (default_value, parm_decl);
9581 }
9582
9583 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9584    type T.  If T is not an aggregate or enumeration type, it is
9585    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9586    ENTERING_SCOPE is nonzero, T is the context for a template which
9587    we are presently tsubst'ing.  Return the substituted value.  */
9588
9589 static tree
9590 tsubst_aggr_type (tree t,
9591                   tree args,
9592                   tsubst_flags_t complain,
9593                   tree in_decl,
9594                   int entering_scope)
9595 {
9596   if (t == NULL_TREE)
9597     return NULL_TREE;
9598
9599   switch (TREE_CODE (t))
9600     {
9601     case RECORD_TYPE:
9602       if (TYPE_PTRMEMFUNC_P (t))
9603         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9604
9605       /* Else fall through.  */
9606     case ENUMERAL_TYPE:
9607     case UNION_TYPE:
9608       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9609         {
9610           tree argvec;
9611           tree context;
9612           tree r;
9613           int saved_unevaluated_operand;
9614           int saved_inhibit_evaluation_warnings;
9615
9616           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9617           saved_unevaluated_operand = cp_unevaluated_operand;
9618           cp_unevaluated_operand = 0;
9619           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9620           c_inhibit_evaluation_warnings = 0;
9621
9622           /* First, determine the context for the type we are looking
9623              up.  */
9624           context = TYPE_CONTEXT (t);
9625           if (context && TYPE_P (context))
9626             {
9627               context = tsubst_aggr_type (context, args, complain,
9628                                           in_decl, /*entering_scope=*/1);
9629               /* If context is a nested class inside a class template,
9630                  it may still need to be instantiated (c++/33959).  */
9631               context = complete_type (context);
9632             }
9633
9634           /* Then, figure out what arguments are appropriate for the
9635              type we are trying to find.  For example, given:
9636
9637                template <class T> struct S;
9638                template <class T, class U> void f(T, U) { S<U> su; }
9639
9640              and supposing that we are instantiating f<int, double>,
9641              then our ARGS will be {int, double}, but, when looking up
9642              S we only want {double}.  */
9643           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9644                                          complain, in_decl);
9645           if (argvec == error_mark_node)
9646             r = error_mark_node;
9647           else
9648             {
9649               r = lookup_template_class (t, argvec, in_decl, context,
9650                                          entering_scope, complain);
9651               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9652             }
9653
9654           cp_unevaluated_operand = saved_unevaluated_operand;
9655           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9656
9657           return r;
9658         }
9659       else
9660         /* This is not a template type, so there's nothing to do.  */
9661         return t;
9662
9663     default:
9664       return tsubst (t, args, complain, in_decl);
9665     }
9666 }
9667
9668 /* Substitute into the default argument ARG (a default argument for
9669    FN), which has the indicated TYPE.  */
9670
9671 tree
9672 tsubst_default_argument (tree fn, tree type, tree arg)
9673 {
9674   tree saved_class_ptr = NULL_TREE;
9675   tree saved_class_ref = NULL_TREE;
9676
9677   /* This can happen in invalid code.  */
9678   if (TREE_CODE (arg) == DEFAULT_ARG)
9679     return arg;
9680
9681   /* This default argument came from a template.  Instantiate the
9682      default argument here, not in tsubst.  In the case of
9683      something like:
9684
9685        template <class T>
9686        struct S {
9687          static T t();
9688          void f(T = t());
9689        };
9690
9691      we must be careful to do name lookup in the scope of S<T>,
9692      rather than in the current class.  */
9693   push_access_scope (fn);
9694   /* The "this" pointer is not valid in a default argument.  */
9695   if (cfun)
9696     {
9697       saved_class_ptr = current_class_ptr;
9698       cp_function_chain->x_current_class_ptr = NULL_TREE;
9699       saved_class_ref = current_class_ref;
9700       cp_function_chain->x_current_class_ref = NULL_TREE;
9701     }
9702
9703   push_deferring_access_checks(dk_no_deferred);
9704   /* The default argument expression may cause implicitly defined
9705      member functions to be synthesized, which will result in garbage
9706      collection.  We must treat this situation as if we were within
9707      the body of function so as to avoid collecting live data on the
9708      stack.  */
9709   ++function_depth;
9710   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9711                      tf_warning_or_error, NULL_TREE,
9712                      /*integral_constant_expression_p=*/false);
9713   --function_depth;
9714   pop_deferring_access_checks();
9715
9716   /* Restore the "this" pointer.  */
9717   if (cfun)
9718     {
9719       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9720       cp_function_chain->x_current_class_ref = saved_class_ref;
9721     }
9722
9723   /* Make sure the default argument is reasonable.  */
9724   arg = check_default_argument (type, arg);
9725
9726   pop_access_scope (fn);
9727
9728   return arg;
9729 }
9730
9731 /* Substitute into all the default arguments for FN.  */
9732
9733 static void
9734 tsubst_default_arguments (tree fn)
9735 {
9736   tree arg;
9737   tree tmpl_args;
9738
9739   tmpl_args = DECL_TI_ARGS (fn);
9740
9741   /* If this function is not yet instantiated, we certainly don't need
9742      its default arguments.  */
9743   if (uses_template_parms (tmpl_args))
9744     return;
9745   /* Don't do this again for clones.  */
9746   if (DECL_CLONED_FUNCTION_P (fn))
9747     return;
9748
9749   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9750        arg;
9751        arg = TREE_CHAIN (arg))
9752     if (TREE_PURPOSE (arg))
9753       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9754                                                     TREE_VALUE (arg),
9755                                                     TREE_PURPOSE (arg));
9756 }
9757
9758 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9759    result of the substitution.  Issue error and warning messages under
9760    control of COMPLAIN.  */
9761
9762 static tree
9763 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9764 {
9765 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9766   location_t saved_loc;
9767   tree r = NULL_TREE;
9768   tree in_decl = t;
9769   hashval_t hash = 0;
9770
9771   /* Set the filename and linenumber to improve error-reporting.  */
9772   saved_loc = input_location;
9773   input_location = DECL_SOURCE_LOCATION (t);
9774
9775   switch (TREE_CODE (t))
9776     {
9777     case TEMPLATE_DECL:
9778       {
9779         /* We can get here when processing a member function template,
9780            member class template, or template template parameter.  */
9781         tree decl = DECL_TEMPLATE_RESULT (t);
9782         tree spec;
9783         tree tmpl_args;
9784         tree full_args;
9785
9786         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9787           {
9788             /* Template template parameter is treated here.  */
9789             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9790             if (new_type == error_mark_node)
9791               RETURN (error_mark_node);
9792
9793             r = copy_decl (t);
9794             DECL_CHAIN (r) = NULL_TREE;
9795             TREE_TYPE (r) = new_type;
9796             DECL_TEMPLATE_RESULT (r)
9797               = build_decl (DECL_SOURCE_LOCATION (decl),
9798                             TYPE_DECL, DECL_NAME (decl), new_type);
9799             DECL_TEMPLATE_PARMS (r)
9800               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9801                                        complain);
9802             TYPE_NAME (new_type) = r;
9803             break;
9804           }
9805
9806         /* We might already have an instance of this template.
9807            The ARGS are for the surrounding class type, so the
9808            full args contain the tsubst'd args for the context,
9809            plus the innermost args from the template decl.  */
9810         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9811           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9812           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9813         /* Because this is a template, the arguments will still be
9814            dependent, even after substitution.  If
9815            PROCESSING_TEMPLATE_DECL is not set, the dependency
9816            predicates will short-circuit.  */
9817         ++processing_template_decl;
9818         full_args = tsubst_template_args (tmpl_args, args,
9819                                           complain, in_decl);
9820         --processing_template_decl;
9821         if (full_args == error_mark_node)
9822           RETURN (error_mark_node);
9823
9824         /* If this is a default template template argument,
9825            tsubst might not have changed anything.  */
9826         if (full_args == tmpl_args)
9827           RETURN (t);
9828
9829         hash = hash_tmpl_and_args (t, full_args);
9830         spec = retrieve_specialization (t, full_args, hash);
9831         if (spec != NULL_TREE)
9832           {
9833             r = spec;
9834             break;
9835           }
9836
9837         /* Make a new template decl.  It will be similar to the
9838            original, but will record the current template arguments.
9839            We also create a new function declaration, which is just
9840            like the old one, but points to this new template, rather
9841            than the old one.  */
9842         r = copy_decl (t);
9843         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9844         DECL_CHAIN (r) = NULL_TREE;
9845
9846         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9847
9848         if (TREE_CODE (decl) == TYPE_DECL)
9849           {
9850             tree new_type;
9851             ++processing_template_decl;
9852             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9853             --processing_template_decl;
9854             if (new_type == error_mark_node)
9855               RETURN (error_mark_node);
9856
9857             TREE_TYPE (r) = new_type;
9858             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9859             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9860             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9861             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9862           }
9863         else
9864           {
9865             tree new_decl;
9866             ++processing_template_decl;
9867             new_decl = tsubst (decl, args, complain, in_decl);
9868             --processing_template_decl;
9869             if (new_decl == error_mark_node)
9870               RETURN (error_mark_node);
9871
9872             DECL_TEMPLATE_RESULT (r) = new_decl;
9873             DECL_TI_TEMPLATE (new_decl) = r;
9874             TREE_TYPE (r) = TREE_TYPE (new_decl);
9875             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9876             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9877           }
9878
9879         SET_DECL_IMPLICIT_INSTANTIATION (r);
9880         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9881         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9882
9883         /* The template parameters for this new template are all the
9884            template parameters for the old template, except the
9885            outermost level of parameters.  */
9886         DECL_TEMPLATE_PARMS (r)
9887           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9888                                    complain);
9889
9890         if (PRIMARY_TEMPLATE_P (t))
9891           DECL_PRIMARY_TEMPLATE (r) = r;
9892
9893         if (TREE_CODE (decl) != TYPE_DECL)
9894           /* Record this non-type partial instantiation.  */
9895           register_specialization (r, t,
9896                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9897                                    false, hash);
9898       }
9899       break;
9900
9901     case FUNCTION_DECL:
9902       {
9903         tree ctx;
9904         tree argvec = NULL_TREE;
9905         tree *friends;
9906         tree gen_tmpl;
9907         tree type;
9908         int member;
9909         int args_depth;
9910         int parms_depth;
9911
9912         /* Nobody should be tsubst'ing into non-template functions.  */
9913         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9914
9915         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9916           {
9917             tree spec;
9918             bool dependent_p;
9919
9920             /* If T is not dependent, just return it.  We have to
9921                increment PROCESSING_TEMPLATE_DECL because
9922                value_dependent_expression_p assumes that nothing is
9923                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9924             ++processing_template_decl;
9925             dependent_p = value_dependent_expression_p (t);
9926             --processing_template_decl;
9927             if (!dependent_p)
9928               RETURN (t);
9929
9930             /* Calculate the most general template of which R is a
9931                specialization, and the complete set of arguments used to
9932                specialize R.  */
9933             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9934             argvec = tsubst_template_args (DECL_TI_ARGS
9935                                           (DECL_TEMPLATE_RESULT
9936                                                  (DECL_TI_TEMPLATE (t))),
9937                                            args, complain, in_decl);
9938             if (argvec == error_mark_node)
9939               RETURN (error_mark_node);
9940
9941             /* Check to see if we already have this specialization.  */
9942             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9943             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9944
9945             if (spec)
9946               {
9947                 r = spec;
9948                 break;
9949               }
9950
9951             /* We can see more levels of arguments than parameters if
9952                there was a specialization of a member template, like
9953                this:
9954
9955                  template <class T> struct S { template <class U> void f(); }
9956                  template <> template <class U> void S<int>::f(U);
9957
9958                Here, we'll be substituting into the specialization,
9959                because that's where we can find the code we actually
9960                want to generate, but we'll have enough arguments for
9961                the most general template.
9962
9963                We also deal with the peculiar case:
9964
9965                  template <class T> struct S {
9966                    template <class U> friend void f();
9967                  };
9968                  template <class U> void f() {}
9969                  template S<int>;
9970                  template void f<double>();
9971
9972                Here, the ARGS for the instantiation of will be {int,
9973                double}.  But, we only need as many ARGS as there are
9974                levels of template parameters in CODE_PATTERN.  We are
9975                careful not to get fooled into reducing the ARGS in
9976                situations like:
9977
9978                  template <class T> struct S { template <class U> void f(U); }
9979                  template <class T> template <> void S<T>::f(int) {}
9980
9981                which we can spot because the pattern will be a
9982                specialization in this case.  */
9983             args_depth = TMPL_ARGS_DEPTH (args);
9984             parms_depth =
9985               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9986             if (args_depth > parms_depth
9987                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9988               args = get_innermost_template_args (args, parms_depth);
9989           }
9990         else
9991           {
9992             /* This special case arises when we have something like this:
9993
9994                  template <class T> struct S {
9995                    friend void f<int>(int, double);
9996                  };
9997
9998                Here, the DECL_TI_TEMPLATE for the friend declaration
9999                will be an IDENTIFIER_NODE.  We are being called from
10000                tsubst_friend_function, and we want only to create a
10001                new decl (R) with appropriate types so that we can call
10002                determine_specialization.  */
10003             gen_tmpl = NULL_TREE;
10004           }
10005
10006         if (DECL_CLASS_SCOPE_P (t))
10007           {
10008             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10009               member = 2;
10010             else
10011               member = 1;
10012             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10013                                     complain, t, /*entering_scope=*/1);
10014           }
10015         else
10016           {
10017             member = 0;
10018             ctx = DECL_CONTEXT (t);
10019           }
10020         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10021         if (type == error_mark_node)
10022           RETURN (error_mark_node);
10023
10024         /* We do NOT check for matching decls pushed separately at this
10025            point, as they may not represent instantiations of this
10026            template, and in any case are considered separate under the
10027            discrete model.  */
10028         r = copy_decl (t);
10029         DECL_USE_TEMPLATE (r) = 0;
10030         TREE_TYPE (r) = type;
10031         /* Clear out the mangled name and RTL for the instantiation.  */
10032         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10033         SET_DECL_RTL (r, NULL);
10034         /* Leave DECL_INITIAL set on deleted instantiations.  */
10035         if (!DECL_DELETED_FN (r))
10036           DECL_INITIAL (r) = NULL_TREE;
10037         DECL_CONTEXT (r) = ctx;
10038
10039         if (member && DECL_CONV_FN_P (r))
10040           /* Type-conversion operator.  Reconstruct the name, in
10041              case it's the name of one of the template's parameters.  */
10042           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10043
10044         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10045                                      complain, t);
10046         DECL_RESULT (r) = NULL_TREE;
10047
10048         TREE_STATIC (r) = 0;
10049         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10050         DECL_EXTERNAL (r) = 1;
10051         /* If this is an instantiation of a function with internal
10052            linkage, we already know what object file linkage will be
10053            assigned to the instantiation.  */
10054         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10055         DECL_DEFER_OUTPUT (r) = 0;
10056         DECL_CHAIN (r) = NULL_TREE;
10057         DECL_PENDING_INLINE_INFO (r) = 0;
10058         DECL_PENDING_INLINE_P (r) = 0;
10059         DECL_SAVED_TREE (r) = NULL_TREE;
10060         DECL_STRUCT_FUNCTION (r) = NULL;
10061         TREE_USED (r) = 0;
10062         /* We'll re-clone as appropriate in instantiate_template.  */
10063         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10064
10065         /* If we aren't complaining now, return on error before we register
10066            the specialization so that we'll complain eventually.  */
10067         if ((complain & tf_error) == 0
10068             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10069             && !grok_op_properties (r, /*complain=*/false))
10070           RETURN (error_mark_node);
10071
10072         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10073            this in the special friend case mentioned above where
10074            GEN_TMPL is NULL.  */
10075         if (gen_tmpl)
10076           {
10077             DECL_TEMPLATE_INFO (r)
10078               = build_template_info (gen_tmpl, argvec);
10079             SET_DECL_IMPLICIT_INSTANTIATION (r);
10080             register_specialization (r, gen_tmpl, argvec, false, hash);
10081
10082             /* We're not supposed to instantiate default arguments
10083                until they are called, for a template.  But, for a
10084                declaration like:
10085
10086                  template <class T> void f ()
10087                  { extern void g(int i = T()); }
10088
10089                we should do the substitution when the template is
10090                instantiated.  We handle the member function case in
10091                instantiate_class_template since the default arguments
10092                might refer to other members of the class.  */
10093             if (!member
10094                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10095                 && !uses_template_parms (argvec))
10096               tsubst_default_arguments (r);
10097           }
10098         else
10099           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10100
10101         /* Copy the list of befriending classes.  */
10102         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10103              *friends;
10104              friends = &TREE_CHAIN (*friends))
10105           {
10106             *friends = copy_node (*friends);
10107             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10108                                             args, complain,
10109                                             in_decl);
10110           }
10111
10112         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10113           {
10114             maybe_retrofit_in_chrg (r);
10115             if (DECL_CONSTRUCTOR_P (r))
10116               grok_ctor_properties (ctx, r);
10117             /* If this is an instantiation of a member template, clone it.
10118                If it isn't, that'll be handled by
10119                clone_constructors_and_destructors.  */
10120             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10121               clone_function_decl (r, /*update_method_vec_p=*/0);
10122           }
10123         else if ((complain & tf_error) != 0
10124                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10125                  && !grok_op_properties (r, /*complain=*/true))
10126           RETURN (error_mark_node);
10127
10128         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10129           SET_DECL_FRIEND_CONTEXT (r,
10130                                    tsubst (DECL_FRIEND_CONTEXT (t),
10131                                             args, complain, in_decl));
10132
10133         /* Possibly limit visibility based on template args.  */
10134         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10135         if (DECL_VISIBILITY_SPECIFIED (t))
10136           {
10137             DECL_VISIBILITY_SPECIFIED (r) = 0;
10138             DECL_ATTRIBUTES (r)
10139               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10140           }
10141         determine_visibility (r);
10142         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10143             && !processing_template_decl)
10144           defaulted_late_check (r);
10145
10146         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10147                                         args, complain, in_decl);
10148       }
10149       break;
10150
10151     case PARM_DECL:
10152       {
10153         tree type = NULL_TREE;
10154         int i, len = 1;
10155         tree expanded_types = NULL_TREE;
10156         tree prev_r = NULL_TREE;
10157         tree first_r = NULL_TREE;
10158
10159         if (FUNCTION_PARAMETER_PACK_P (t))
10160           {
10161             /* If there is a local specialization that isn't a
10162                parameter pack, it means that we're doing a "simple"
10163                substitution from inside tsubst_pack_expansion. Just
10164                return the local specialization (which will be a single
10165                parm).  */
10166             tree spec = retrieve_local_specialization (t);
10167             if (spec 
10168                 && TREE_CODE (spec) == PARM_DECL
10169                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10170               RETURN (spec);
10171
10172             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10173                the parameters in this function parameter pack.  */
10174             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10175                                                     complain, in_decl);
10176             if (TREE_CODE (expanded_types) == TREE_VEC)
10177               {
10178                 len = TREE_VEC_LENGTH (expanded_types);
10179
10180                 /* Zero-length parameter packs are boring. Just substitute
10181                    into the chain.  */
10182                 if (len == 0)
10183                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10184                                   TREE_CHAIN (t)));
10185               }
10186             else
10187               {
10188                 /* All we did was update the type. Make a note of that.  */
10189                 type = expanded_types;
10190                 expanded_types = NULL_TREE;
10191               }
10192           }
10193
10194         /* Loop through all of the parameter's we'll build. When T is
10195            a function parameter pack, LEN is the number of expanded
10196            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10197         r = NULL_TREE;
10198         for (i = 0; i < len; ++i)
10199           {
10200             prev_r = r;
10201             r = copy_node (t);
10202             if (DECL_TEMPLATE_PARM_P (t))
10203               SET_DECL_TEMPLATE_PARM_P (r);
10204
10205             if (expanded_types)
10206               /* We're on the Ith parameter of the function parameter
10207                  pack.  */
10208               {
10209                 /* An argument of a function parameter pack is not a parameter
10210                    pack.  */
10211                 FUNCTION_PARAMETER_PACK_P (r) = false;
10212
10213                 /* Get the Ith type.  */
10214                 type = TREE_VEC_ELT (expanded_types, i);
10215
10216                 if (DECL_NAME (r))
10217                   /* Rename the parameter to include the index.  */
10218                   DECL_NAME (r) =
10219                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10220               }
10221             else if (!type)
10222               /* We're dealing with a normal parameter.  */
10223               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10224
10225             type = type_decays_to (type);
10226             TREE_TYPE (r) = type;
10227             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10228
10229             if (DECL_INITIAL (r))
10230               {
10231                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10232                   DECL_INITIAL (r) = TREE_TYPE (r);
10233                 else
10234                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10235                                              complain, in_decl);
10236               }
10237
10238             DECL_CONTEXT (r) = NULL_TREE;
10239
10240             if (!DECL_TEMPLATE_PARM_P (r))
10241               DECL_ARG_TYPE (r) = type_passed_as (type);
10242
10243             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10244                                             args, complain, in_decl);
10245
10246             /* Keep track of the first new parameter we
10247                generate. That's what will be returned to the
10248                caller.  */
10249             if (!first_r)
10250               first_r = r;
10251
10252             /* Build a proper chain of parameters when substituting
10253                into a function parameter pack.  */
10254             if (prev_r)
10255               DECL_CHAIN (prev_r) = r;
10256           }
10257
10258         if (DECL_CHAIN (t))
10259           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10260                                    complain, DECL_CHAIN (t));
10261
10262         /* FIRST_R contains the start of the chain we've built.  */
10263         r = first_r;
10264       }
10265       break;
10266
10267     case FIELD_DECL:
10268       {
10269         tree type;
10270
10271         r = copy_decl (t);
10272         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10273         if (type == error_mark_node)
10274           RETURN (error_mark_node);
10275         TREE_TYPE (r) = type;
10276         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10277
10278         if (DECL_C_BIT_FIELD (r))
10279           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10280              non-bit-fields DECL_INITIAL is a non-static data member
10281              initializer, which gets deferred instantiation.  */
10282           DECL_INITIAL (r)
10283             = tsubst_expr (DECL_INITIAL (t), args,
10284                            complain, in_decl,
10285                            /*integral_constant_expression_p=*/true);
10286         else if (DECL_INITIAL (t))
10287           {
10288             /* Set up DECL_TEMPLATE_INFO so that we can get at the
10289                NSDMI in perform_member_init.  Still set DECL_INITIAL
10290                so that we know there is one.  */
10291             DECL_INITIAL (r) = void_zero_node;
10292             gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10293             retrofit_lang_decl (r);
10294             DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10295           }
10296         /* We don't have to set DECL_CONTEXT here; it is set by
10297            finish_member_declaration.  */
10298         DECL_CHAIN (r) = NULL_TREE;
10299         if (VOID_TYPE_P (type))
10300           error ("instantiation of %q+D as type %qT", r, type);
10301
10302         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10303                                         args, complain, in_decl);
10304       }
10305       break;
10306
10307     case USING_DECL:
10308       /* We reach here only for member using decls.  */
10309       if (DECL_DEPENDENT_P (t))
10310         {
10311           r = do_class_using_decl
10312             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10313              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10314           if (!r)
10315             r = error_mark_node;
10316           else
10317             {
10318               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10319               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10320             }
10321         }
10322       else
10323         {
10324           r = copy_node (t);
10325           DECL_CHAIN (r) = NULL_TREE;
10326         }
10327       break;
10328
10329     case TYPE_DECL:
10330     case VAR_DECL:
10331       {
10332         tree argvec = NULL_TREE;
10333         tree gen_tmpl = NULL_TREE;
10334         tree spec;
10335         tree tmpl = NULL_TREE;
10336         tree ctx;
10337         tree type = NULL_TREE;
10338         bool local_p;
10339
10340         if (TREE_CODE (t) == TYPE_DECL
10341             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10342           {
10343             /* If this is the canonical decl, we don't have to
10344                mess with instantiations, and often we can't (for
10345                typename, template type parms and such).  Note that
10346                TYPE_NAME is not correct for the above test if
10347                we've copied the type for a typedef.  */
10348             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10349             if (type == error_mark_node)
10350               RETURN (error_mark_node);
10351             r = TYPE_NAME (type);
10352             break;
10353           }
10354
10355         /* Check to see if we already have the specialization we
10356            need.  */
10357         spec = NULL_TREE;
10358         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10359           {
10360             /* T is a static data member or namespace-scope entity.
10361                We have to substitute into namespace-scope variables
10362                (even though such entities are never templates) because
10363                of cases like:
10364                
10365                  template <class T> void f() { extern T t; }
10366
10367                where the entity referenced is not known until
10368                instantiation time.  */
10369             local_p = false;
10370             ctx = DECL_CONTEXT (t);
10371             if (DECL_CLASS_SCOPE_P (t))
10372               {
10373                 ctx = tsubst_aggr_type (ctx, args,
10374                                         complain,
10375                                         in_decl, /*entering_scope=*/1);
10376                 /* If CTX is unchanged, then T is in fact the
10377                    specialization we want.  That situation occurs when
10378                    referencing a static data member within in its own
10379                    class.  We can use pointer equality, rather than
10380                    same_type_p, because DECL_CONTEXT is always
10381                    canonical.  */
10382                 if (ctx == DECL_CONTEXT (t))
10383                   spec = t;
10384               }
10385
10386             if (!spec)
10387               {
10388                 tmpl = DECL_TI_TEMPLATE (t);
10389                 gen_tmpl = most_general_template (tmpl);
10390                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10391                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10392                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10393               }
10394           }
10395         else
10396           {
10397             /* A local variable.  */
10398             local_p = true;
10399             /* Subsequent calls to pushdecl will fill this in.  */
10400             ctx = NULL_TREE;
10401             spec = retrieve_local_specialization (t);
10402           }
10403         /* If we already have the specialization we need, there is
10404            nothing more to do.  */ 
10405         if (spec)
10406           {
10407             r = spec;
10408             break;
10409           }
10410
10411         /* Create a new node for the specialization we need.  */
10412         r = copy_decl (t);
10413         if (type == NULL_TREE)
10414           {
10415             if (is_typedef_decl (t))
10416               type = DECL_ORIGINAL_TYPE (t);
10417             else
10418               type = TREE_TYPE (t);
10419             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10420               type = strip_array_domain (type);
10421             type = tsubst (type, args, complain, in_decl);
10422           }
10423         if (TREE_CODE (r) == VAR_DECL)
10424           {
10425             /* Even if the original location is out of scope, the
10426                newly substituted one is not.  */
10427             DECL_DEAD_FOR_LOCAL (r) = 0;
10428             DECL_INITIALIZED_P (r) = 0;
10429             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10430             if (type == error_mark_node)
10431               RETURN (error_mark_node);
10432             if (TREE_CODE (type) == FUNCTION_TYPE)
10433               {
10434                 /* It may seem that this case cannot occur, since:
10435
10436                      typedef void f();
10437                      void g() { f x; }
10438
10439                    declares a function, not a variable.  However:
10440       
10441                      typedef void f();
10442                      template <typename T> void g() { T t; }
10443                      template void g<f>();
10444
10445                    is an attempt to declare a variable with function
10446                    type.  */
10447                 error ("variable %qD has function type",
10448                        /* R is not yet sufficiently initialized, so we
10449                           just use its name.  */
10450                        DECL_NAME (r));
10451                 RETURN (error_mark_node);
10452               }
10453             type = complete_type (type);
10454             /* Wait until cp_finish_decl to set this again, to handle
10455                circular dependency (template/instantiate6.C). */
10456             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10457             type = check_var_type (DECL_NAME (r), type);
10458
10459             if (DECL_HAS_VALUE_EXPR_P (t))
10460               {
10461                 tree ve = DECL_VALUE_EXPR (t);
10462                 ve = tsubst_expr (ve, args, complain, in_decl,
10463                                   /*constant_expression_p=*/false);
10464                 if (REFERENCE_REF_P (ve))
10465                   {
10466                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10467                     ve = TREE_OPERAND (ve, 0);
10468                   }
10469                 SET_DECL_VALUE_EXPR (r, ve);
10470               }
10471           }
10472         else if (DECL_SELF_REFERENCE_P (t))
10473           SET_DECL_SELF_REFERENCE_P (r);
10474         TREE_TYPE (r) = type;
10475         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10476         DECL_CONTEXT (r) = ctx;
10477         /* Clear out the mangled name and RTL for the instantiation.  */
10478         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10479         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10480           SET_DECL_RTL (r, NULL);
10481         /* The initializer must not be expanded until it is required;
10482            see [temp.inst].  */
10483         DECL_INITIAL (r) = NULL_TREE;
10484         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10485           SET_DECL_RTL (r, NULL);
10486         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10487         if (TREE_CODE (r) == VAR_DECL)
10488           {
10489             /* Possibly limit visibility based on template args.  */
10490             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10491             if (DECL_VISIBILITY_SPECIFIED (t))
10492               {
10493                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10494                 DECL_ATTRIBUTES (r)
10495                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10496               }
10497             determine_visibility (r);
10498           }
10499
10500         if (!local_p)
10501           {
10502             /* A static data member declaration is always marked
10503                external when it is declared in-class, even if an
10504                initializer is present.  We mimic the non-template
10505                processing here.  */
10506             DECL_EXTERNAL (r) = 1;
10507
10508             register_specialization (r, gen_tmpl, argvec, false, hash);
10509             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10510             SET_DECL_IMPLICIT_INSTANTIATION (r);
10511           }
10512         else if (cp_unevaluated_operand)
10513           {
10514             /* We're substituting this var in a decltype outside of its
10515                scope, such as for a lambda return type.  Don't add it to
10516                local_specializations, do perform auto deduction.  */
10517             tree auto_node = type_uses_auto (type);
10518             if (auto_node)
10519               {
10520                 tree init
10521                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10522                                  /*constant_expression_p=*/false);
10523                 init = resolve_nondeduced_context (init);
10524                 TREE_TYPE (r) = type
10525                   = do_auto_deduction (type, init, auto_node);
10526               }
10527           }
10528         else
10529           register_local_specialization (r, t);
10530
10531         DECL_CHAIN (r) = NULL_TREE;
10532
10533         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10534                                         /*flags=*/0,
10535                                         args, complain, in_decl);
10536
10537         /* Preserve a typedef that names a type.  */
10538         if (is_typedef_decl (r))
10539           {
10540             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10541             set_underlying_type (r);
10542           }
10543
10544         layout_decl (r, 0);
10545       }
10546       break;
10547
10548     default:
10549       gcc_unreachable ();
10550     }
10551 #undef RETURN
10552
10553  out:
10554   /* Restore the file and line information.  */
10555   input_location = saved_loc;
10556
10557   return r;
10558 }
10559
10560 /* Substitute into the ARG_TYPES of a function type.  */
10561
10562 static tree
10563 tsubst_arg_types (tree arg_types,
10564                   tree args,
10565                   tsubst_flags_t complain,
10566                   tree in_decl)
10567 {
10568   tree remaining_arg_types;
10569   tree type = NULL_TREE;
10570   int i = 1;
10571   tree expanded_args = NULL_TREE;
10572   tree default_arg;
10573
10574   if (!arg_types || arg_types == void_list_node)
10575     return arg_types;
10576
10577   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10578                                           args, complain, in_decl);
10579   if (remaining_arg_types == error_mark_node)
10580     return error_mark_node;
10581
10582   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10583     {
10584       /* For a pack expansion, perform substitution on the
10585          entire expression. Later on, we'll handle the arguments
10586          one-by-one.  */
10587       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10588                                             args, complain, in_decl);
10589
10590       if (TREE_CODE (expanded_args) == TREE_VEC)
10591         /* So that we'll spin through the parameters, one by one.  */
10592         i = TREE_VEC_LENGTH (expanded_args);
10593       else
10594         {
10595           /* We only partially substituted into the parameter
10596              pack. Our type is TYPE_PACK_EXPANSION.  */
10597           type = expanded_args;
10598           expanded_args = NULL_TREE;
10599         }
10600     }
10601
10602   while (i > 0) {
10603     --i;
10604     
10605     if (expanded_args)
10606       type = TREE_VEC_ELT (expanded_args, i);
10607     else if (!type)
10608       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10609
10610     if (type == error_mark_node)
10611       return error_mark_node;
10612     if (VOID_TYPE_P (type))
10613       {
10614         if (complain & tf_error)
10615           {
10616             error ("invalid parameter type %qT", type);
10617             if (in_decl)
10618               error ("in declaration %q+D", in_decl);
10619           }
10620         return error_mark_node;
10621     }
10622     
10623     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10624        top-level qualifiers as required.  */
10625     type = cv_unqualified (type_decays_to (type));
10626
10627     /* We do not substitute into default arguments here.  The standard
10628        mandates that they be instantiated only when needed, which is
10629        done in build_over_call.  */
10630     default_arg = TREE_PURPOSE (arg_types);
10631
10632     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10633       {
10634         /* We've instantiated a template before its default arguments
10635            have been parsed.  This can happen for a nested template
10636            class, and is not an error unless we require the default
10637            argument in a call of this function.  */
10638         remaining_arg_types = 
10639           tree_cons (default_arg, type, remaining_arg_types);
10640         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10641                        remaining_arg_types);
10642       }
10643     else
10644       remaining_arg_types = 
10645         hash_tree_cons (default_arg, type, remaining_arg_types);
10646   }
10647         
10648   return remaining_arg_types;
10649 }
10650
10651 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10652    *not* handle the exception-specification for FNTYPE, because the
10653    initial substitution of explicitly provided template parameters
10654    during argument deduction forbids substitution into the
10655    exception-specification:
10656
10657      [temp.deduct]
10658
10659      All references in the function type of the function template to  the
10660      corresponding template parameters are replaced by the specified tem-
10661      plate argument values.  If a substitution in a template parameter or
10662      in  the function type of the function template results in an invalid
10663      type, type deduction fails.  [Note: The equivalent  substitution  in
10664      exception specifications is done only when the function is instanti-
10665      ated, at which point a program is  ill-formed  if  the  substitution
10666      results in an invalid type.]  */
10667
10668 static tree
10669 tsubst_function_type (tree t,
10670                       tree args,
10671                       tsubst_flags_t complain,
10672                       tree in_decl)
10673 {
10674   tree return_type;
10675   tree arg_types;
10676   tree fntype;
10677
10678   /* The TYPE_CONTEXT is not used for function/method types.  */
10679   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10680
10681   /* Substitute the return type.  */
10682   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10683   if (return_type == error_mark_node)
10684     return error_mark_node;
10685   /* The standard does not presently indicate that creation of a
10686      function type with an invalid return type is a deduction failure.
10687      However, that is clearly analogous to creating an array of "void"
10688      or a reference to a reference.  This is core issue #486.  */
10689   if (TREE_CODE (return_type) == ARRAY_TYPE
10690       || TREE_CODE (return_type) == FUNCTION_TYPE)
10691     {
10692       if (complain & tf_error)
10693         {
10694           if (TREE_CODE (return_type) == ARRAY_TYPE)
10695             error ("function returning an array");
10696           else
10697             error ("function returning a function");
10698         }
10699       return error_mark_node;
10700     }
10701
10702   /* Substitute the argument types.  */
10703   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10704                                 complain, in_decl);
10705   if (arg_types == error_mark_node)
10706     return error_mark_node;
10707
10708   /* Construct a new type node and return it.  */
10709   if (TREE_CODE (t) == FUNCTION_TYPE)
10710     {
10711       fntype = build_function_type (return_type, arg_types);
10712       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10713     }
10714   else
10715     {
10716       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10717       if (! MAYBE_CLASS_TYPE_P (r))
10718         {
10719           /* [temp.deduct]
10720
10721              Type deduction may fail for any of the following
10722              reasons:
10723
10724              -- Attempting to create "pointer to member of T" when T
10725              is not a class type.  */
10726           if (complain & tf_error)
10727             error ("creating pointer to member function of non-class type %qT",
10728                       r);
10729           return error_mark_node;
10730         }
10731
10732       fntype = build_method_type_directly (r, return_type,
10733                                            TREE_CHAIN (arg_types));
10734     }
10735   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10736
10737   return fntype;
10738 }
10739
10740 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10741    ARGS into that specification, and return the substituted
10742    specification.  If there is no specification, return NULL_TREE.  */
10743
10744 static tree
10745 tsubst_exception_specification (tree fntype,
10746                                 tree args,
10747                                 tsubst_flags_t complain,
10748                                 tree in_decl,
10749                                 bool defer_ok)
10750 {
10751   tree specs;
10752   tree new_specs;
10753
10754   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10755   new_specs = NULL_TREE;
10756   if (specs && TREE_PURPOSE (specs))
10757     {
10758       /* A noexcept-specifier.  */
10759       tree expr = TREE_PURPOSE (specs);
10760       if (expr == boolean_true_node || expr == boolean_false_node)
10761         new_specs = expr;
10762       else if (defer_ok)
10763         {
10764           /* Defer instantiation of noexcept-specifiers to avoid
10765              excessive instantiations (c++/49107).  */
10766           new_specs = make_node (DEFERRED_NOEXCEPT);
10767           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10768             {
10769               /* We already partially instantiated this member template,
10770                  so combine the new args with the old.  */
10771               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10772                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10773               DEFERRED_NOEXCEPT_ARGS (new_specs)
10774                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10775             }
10776           else
10777             {
10778               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10779               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10780             }
10781         }
10782       else
10783         new_specs = tsubst_copy_and_build
10784           (expr, args, complain, in_decl, /*function_p=*/false,
10785            /*integral_constant_expression_p=*/true);
10786       new_specs = build_noexcept_spec (new_specs, complain);
10787     }
10788   else if (specs)
10789     {
10790       if (! TREE_VALUE (specs))
10791         new_specs = specs;
10792       else
10793         while (specs)
10794           {
10795             tree spec;
10796             int i, len = 1;
10797             tree expanded_specs = NULL_TREE;
10798
10799             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10800               {
10801                 /* Expand the pack expansion type.  */
10802                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10803                                                        args, complain,
10804                                                        in_decl);
10805
10806                 if (expanded_specs == error_mark_node)
10807                   return error_mark_node;
10808                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10809                   len = TREE_VEC_LENGTH (expanded_specs);
10810                 else
10811                   {
10812                     /* We're substituting into a member template, so
10813                        we got a TYPE_PACK_EXPANSION back.  Add that
10814                        expansion and move on.  */
10815                     gcc_assert (TREE_CODE (expanded_specs) 
10816                                 == TYPE_PACK_EXPANSION);
10817                     new_specs = add_exception_specifier (new_specs,
10818                                                          expanded_specs,
10819                                                          complain);
10820                     specs = TREE_CHAIN (specs);
10821                     continue;
10822                   }
10823               }
10824
10825             for (i = 0; i < len; ++i)
10826               {
10827                 if (expanded_specs)
10828                   spec = TREE_VEC_ELT (expanded_specs, i);
10829                 else
10830                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10831                 if (spec == error_mark_node)
10832                   return spec;
10833                 new_specs = add_exception_specifier (new_specs, spec, 
10834                                                      complain);
10835               }
10836
10837             specs = TREE_CHAIN (specs);
10838           }
10839     }
10840   return new_specs;
10841 }
10842
10843 /* Take the tree structure T and replace template parameters used
10844    therein with the argument vector ARGS.  IN_DECL is an associated
10845    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10846    Issue error and warning messages under control of COMPLAIN.  Note
10847    that we must be relatively non-tolerant of extensions here, in
10848    order to preserve conformance; if we allow substitutions that
10849    should not be allowed, we may allow argument deductions that should
10850    not succeed, and therefore report ambiguous overload situations
10851    where there are none.  In theory, we could allow the substitution,
10852    but indicate that it should have failed, and allow our caller to
10853    make sure that the right thing happens, but we don't try to do this
10854    yet.
10855
10856    This function is used for dealing with types, decls and the like;
10857    for expressions, use tsubst_expr or tsubst_copy.  */
10858
10859 tree
10860 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10861 {
10862   enum tree_code code;
10863   tree type, r;
10864
10865   if (t == NULL_TREE || t == error_mark_node
10866       || t == integer_type_node
10867       || t == void_type_node
10868       || t == char_type_node
10869       || t == unknown_type_node
10870       || TREE_CODE (t) == NAMESPACE_DECL
10871       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10872     return t;
10873
10874   if (DECL_P (t))
10875     return tsubst_decl (t, args, complain);
10876
10877   if (args == NULL_TREE)
10878     return t;
10879
10880   code = TREE_CODE (t);
10881
10882   if (code == IDENTIFIER_NODE)
10883     type = IDENTIFIER_TYPE_VALUE (t);
10884   else
10885     type = TREE_TYPE (t);
10886
10887   gcc_assert (type != unknown_type_node);
10888
10889   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10890      such as attribute aligned.  */
10891   if (TYPE_P (t)
10892       && typedef_variant_p (t))
10893     {
10894       tree decl = TYPE_NAME (t);
10895       
10896       if (DECL_CLASS_SCOPE_P (decl)
10897           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10898           && uses_template_parms (DECL_CONTEXT (decl)))
10899         {
10900           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10901           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10902           r = retrieve_specialization (tmpl, gen_args, 0);
10903         }
10904       else if (DECL_FUNCTION_SCOPE_P (decl)
10905                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10906                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10907         r = retrieve_local_specialization (decl);
10908       else
10909         /* The typedef is from a non-template context.  */
10910         return t;
10911
10912       if (r)
10913         {
10914           r = TREE_TYPE (r);
10915           r = cp_build_qualified_type_real
10916             (r, cp_type_quals (t) | cp_type_quals (r),
10917              complain | tf_ignore_bad_quals);
10918           return r;
10919         }
10920       /* Else we must be instantiating the typedef, so fall through.  */
10921     }
10922
10923   if (type
10924       && code != TYPENAME_TYPE
10925       && code != TEMPLATE_TYPE_PARM
10926       && code != IDENTIFIER_NODE
10927       && code != FUNCTION_TYPE
10928       && code != METHOD_TYPE)
10929     type = tsubst (type, args, complain, in_decl);
10930   if (type == error_mark_node)
10931     return error_mark_node;
10932
10933   switch (code)
10934     {
10935     case RECORD_TYPE:
10936     case UNION_TYPE:
10937     case ENUMERAL_TYPE:
10938       return tsubst_aggr_type (t, args, complain, in_decl,
10939                                /*entering_scope=*/0);
10940
10941     case ERROR_MARK:
10942     case IDENTIFIER_NODE:
10943     case VOID_TYPE:
10944     case REAL_TYPE:
10945     case COMPLEX_TYPE:
10946     case VECTOR_TYPE:
10947     case BOOLEAN_TYPE:
10948     case NULLPTR_TYPE:
10949     case LANG_TYPE:
10950       return t;
10951
10952     case INTEGER_TYPE:
10953       if (t == integer_type_node)
10954         return t;
10955
10956       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10957           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10958         return t;
10959
10960       {
10961         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10962
10963         max = tsubst_expr (omax, args, complain, in_decl,
10964                            /*integral_constant_expression_p=*/false);
10965
10966         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10967            needed.  */
10968         if (TREE_CODE (max) == NOP_EXPR
10969             && TREE_SIDE_EFFECTS (omax)
10970             && !TREE_TYPE (max))
10971           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10972
10973         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10974            with TREE_SIDE_EFFECTS that indicates this is not an integral
10975            constant expression.  */
10976         if (processing_template_decl
10977             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10978           {
10979             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10980             TREE_SIDE_EFFECTS (max) = 1;
10981           }
10982
10983         return compute_array_index_type (NULL_TREE, max, complain);
10984       }
10985
10986     case TEMPLATE_TYPE_PARM:
10987     case TEMPLATE_TEMPLATE_PARM:
10988     case BOUND_TEMPLATE_TEMPLATE_PARM:
10989     case TEMPLATE_PARM_INDEX:
10990       {
10991         int idx;
10992         int level;
10993         int levels;
10994         tree arg = NULL_TREE;
10995
10996         r = NULL_TREE;
10997
10998         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10999         template_parm_level_and_index (t, &level, &idx); 
11000
11001         levels = TMPL_ARGS_DEPTH (args);
11002         if (level <= levels)
11003           {
11004             arg = TMPL_ARG (args, level, idx);
11005
11006             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11007               /* See through ARGUMENT_PACK_SELECT arguments. */
11008               arg = ARGUMENT_PACK_SELECT_ARG (arg);
11009           }
11010
11011         if (arg == error_mark_node)
11012           return error_mark_node;
11013         else if (arg != NULL_TREE)
11014           {
11015             if (ARGUMENT_PACK_P (arg))
11016               /* If ARG is an argument pack, we don't actually want to
11017                  perform a substitution here, because substitutions
11018                  for argument packs are only done
11019                  element-by-element. We can get to this point when
11020                  substituting the type of a non-type template
11021                  parameter pack, when that type actually contains
11022                  template parameter packs from an outer template, e.g.,
11023
11024                  template<typename... Types> struct A {
11025                    template<Types... Values> struct B { };
11026                  };  */
11027               return t;
11028
11029             if (code == TEMPLATE_TYPE_PARM)
11030               {
11031                 int quals;
11032                 gcc_assert (TYPE_P (arg));
11033
11034                 quals = cp_type_quals (arg) | cp_type_quals (t);
11035                   
11036                 return cp_build_qualified_type_real
11037                   (arg, quals, complain | tf_ignore_bad_quals);
11038               }
11039             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11040               {
11041                 /* We are processing a type constructed from a
11042                    template template parameter.  */
11043                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11044                                       args, complain, in_decl);
11045                 if (argvec == error_mark_node)
11046                   return error_mark_node;
11047
11048                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11049                    are resolving nested-types in the signature of a
11050                    member function templates.  Otherwise ARG is a
11051                    TEMPLATE_DECL and is the real template to be
11052                    instantiated.  */
11053                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11054                   arg = TYPE_NAME (arg);
11055
11056                 r = lookup_template_class (arg,
11057                                            argvec, in_decl,
11058                                            DECL_CONTEXT (arg),
11059                                             /*entering_scope=*/0,
11060                                            complain);
11061                 return cp_build_qualified_type_real
11062                   (r, cp_type_quals (t), complain);
11063               }
11064             else
11065               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11066               return convert_from_reference (unshare_expr (arg));
11067           }
11068
11069         if (level == 1)
11070           /* This can happen during the attempted tsubst'ing in
11071              unify.  This means that we don't yet have any information
11072              about the template parameter in question.  */
11073           return t;
11074
11075         /* If we get here, we must have been looking at a parm for a
11076            more deeply nested template.  Make a new version of this
11077            template parameter, but with a lower level.  */
11078         switch (code)
11079           {
11080           case TEMPLATE_TYPE_PARM:
11081           case TEMPLATE_TEMPLATE_PARM:
11082           case BOUND_TEMPLATE_TEMPLATE_PARM:
11083             if (cp_type_quals (t))
11084               {
11085                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11086                 r = cp_build_qualified_type_real
11087                   (r, cp_type_quals (t),
11088                    complain | (code == TEMPLATE_TYPE_PARM
11089                                ? tf_ignore_bad_quals : 0));
11090               }
11091             else
11092               {
11093                 r = copy_type (t);
11094                 TEMPLATE_TYPE_PARM_INDEX (r)
11095                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11096                                                 r, levels, args, complain);
11097                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11098                 TYPE_MAIN_VARIANT (r) = r;
11099                 TYPE_POINTER_TO (r) = NULL_TREE;
11100                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11101
11102                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11103                   /* We have reduced the level of the template
11104                      template parameter, but not the levels of its
11105                      template parameters, so canonical_type_parameter
11106                      will not be able to find the canonical template
11107                      template parameter for this level. Thus, we
11108                      require structural equality checking to compare
11109                      TEMPLATE_TEMPLATE_PARMs. */
11110                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11111                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11112                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11113                 else
11114                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11115
11116                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11117                   {
11118                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11119                                           complain, in_decl);
11120                     if (argvec == error_mark_node)
11121                       return error_mark_node;
11122
11123                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11124                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11125                   }
11126               }
11127             break;
11128
11129           case TEMPLATE_PARM_INDEX:
11130             r = reduce_template_parm_level (t, type, levels, args, complain);
11131             break;
11132
11133           default:
11134             gcc_unreachable ();
11135           }
11136
11137         return r;
11138       }
11139
11140     case TREE_LIST:
11141       {
11142         tree purpose, value, chain;
11143
11144         if (t == void_list_node)
11145           return t;
11146
11147         purpose = TREE_PURPOSE (t);
11148         if (purpose)
11149           {
11150             purpose = tsubst (purpose, args, complain, in_decl);
11151             if (purpose == error_mark_node)
11152               return error_mark_node;
11153           }
11154         value = TREE_VALUE (t);
11155         if (value)
11156           {
11157             value = tsubst (value, args, complain, in_decl);
11158             if (value == error_mark_node)
11159               return error_mark_node;
11160           }
11161         chain = TREE_CHAIN (t);
11162         if (chain && chain != void_type_node)
11163           {
11164             chain = tsubst (chain, args, complain, in_decl);
11165             if (chain == error_mark_node)
11166               return error_mark_node;
11167           }
11168         if (purpose == TREE_PURPOSE (t)
11169             && value == TREE_VALUE (t)
11170             && chain == TREE_CHAIN (t))
11171           return t;
11172         return hash_tree_cons (purpose, value, chain);
11173       }
11174
11175     case TREE_BINFO:
11176       /* We should never be tsubsting a binfo.  */
11177       gcc_unreachable ();
11178
11179     case TREE_VEC:
11180       /* A vector of template arguments.  */
11181       gcc_assert (!type);
11182       return tsubst_template_args (t, args, complain, in_decl);
11183
11184     case POINTER_TYPE:
11185     case REFERENCE_TYPE:
11186       {
11187         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11188           return t;
11189
11190         /* [temp.deduct]
11191
11192            Type deduction may fail for any of the following
11193            reasons:
11194
11195            -- Attempting to create a pointer to reference type.
11196            -- Attempting to create a reference to a reference type or
11197               a reference to void.
11198
11199           Core issue 106 says that creating a reference to a reference
11200           during instantiation is no longer a cause for failure. We
11201           only enforce this check in strict C++98 mode.  */
11202         if ((TREE_CODE (type) == REFERENCE_TYPE
11203              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11204             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11205           {
11206             static location_t last_loc;
11207
11208             /* We keep track of the last time we issued this error
11209                message to avoid spewing a ton of messages during a
11210                single bad template instantiation.  */
11211             if (complain & tf_error
11212                 && last_loc != input_location)
11213               {
11214                 if (TREE_CODE (type) == VOID_TYPE)
11215                   error ("forming reference to void");
11216                else if (code == POINTER_TYPE)
11217                  error ("forming pointer to reference type %qT", type);
11218                else
11219                   error ("forming reference to reference type %qT", type);
11220                 last_loc = input_location;
11221               }
11222
11223             return error_mark_node;
11224           }
11225         else if (code == POINTER_TYPE)
11226           {
11227             r = build_pointer_type (type);
11228             if (TREE_CODE (type) == METHOD_TYPE)
11229               r = build_ptrmemfunc_type (r);
11230           }
11231         else if (TREE_CODE (type) == REFERENCE_TYPE)
11232           /* In C++0x, during template argument substitution, when there is an
11233              attempt to create a reference to a reference type, reference
11234              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11235
11236              "If a template-argument for a template-parameter T names a type
11237              that is a reference to a type A, an attempt to create the type
11238              'lvalue reference to cv T' creates the type 'lvalue reference to
11239              A,' while an attempt to create the type type rvalue reference to
11240              cv T' creates the type T"
11241           */
11242           r = cp_build_reference_type
11243               (TREE_TYPE (type),
11244                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11245         else
11246           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11247         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11248
11249         if (r != error_mark_node)
11250           /* Will this ever be needed for TYPE_..._TO values?  */
11251           layout_type (r);
11252
11253         return r;
11254       }
11255     case OFFSET_TYPE:
11256       {
11257         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11258         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11259           {
11260             /* [temp.deduct]
11261
11262                Type deduction may fail for any of the following
11263                reasons:
11264
11265                -- Attempting to create "pointer to member of T" when T
11266                   is not a class type.  */
11267             if (complain & tf_error)
11268               error ("creating pointer to member of non-class type %qT", r);
11269             return error_mark_node;
11270           }
11271         if (TREE_CODE (type) == REFERENCE_TYPE)
11272           {
11273             if (complain & tf_error)
11274               error ("creating pointer to member reference type %qT", type);
11275             return error_mark_node;
11276           }
11277         if (TREE_CODE (type) == VOID_TYPE)
11278           {
11279             if (complain & tf_error)
11280               error ("creating pointer to member of type void");
11281             return error_mark_node;
11282           }
11283         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11284         if (TREE_CODE (type) == FUNCTION_TYPE)
11285           {
11286             /* The type of the implicit object parameter gets its
11287                cv-qualifiers from the FUNCTION_TYPE. */
11288             tree memptr;
11289             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11290             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11291             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11292                                                  complain);
11293           }
11294         else
11295           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11296                                                cp_type_quals (t),
11297                                                complain);
11298       }
11299     case FUNCTION_TYPE:
11300     case METHOD_TYPE:
11301       {
11302         tree fntype;
11303         tree specs;
11304         fntype = tsubst_function_type (t, args, complain, in_decl);
11305         if (fntype == error_mark_node)
11306           return error_mark_node;
11307
11308         /* Substitute the exception specification.  */
11309         specs = tsubst_exception_specification (t, args, complain,
11310                                                 in_decl, /*defer_ok*/true);
11311         if (specs == error_mark_node)
11312           return error_mark_node;
11313         if (specs)
11314           fntype = build_exception_variant (fntype, specs);
11315         return fntype;
11316       }
11317     case ARRAY_TYPE:
11318       {
11319         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11320         if (domain == error_mark_node)
11321           return error_mark_node;
11322
11323         /* As an optimization, we avoid regenerating the array type if
11324            it will obviously be the same as T.  */
11325         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11326           return t;
11327
11328         /* These checks should match the ones in grokdeclarator.
11329
11330            [temp.deduct]
11331
11332            The deduction may fail for any of the following reasons:
11333
11334            -- Attempting to create an array with an element type that
11335               is void, a function type, or a reference type, or [DR337]
11336               an abstract class type.  */
11337         if (TREE_CODE (type) == VOID_TYPE
11338             || TREE_CODE (type) == FUNCTION_TYPE
11339             || TREE_CODE (type) == REFERENCE_TYPE)
11340           {
11341             if (complain & tf_error)
11342               error ("creating array of %qT", type);
11343             return error_mark_node;
11344           }
11345         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11346           {
11347             if (complain & tf_error)
11348               error ("creating array of %qT, which is an abstract class type",
11349                      type);
11350             return error_mark_node;
11351           }
11352
11353         r = build_cplus_array_type (type, domain);
11354
11355         if (TYPE_USER_ALIGN (t))
11356           {
11357             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11358             TYPE_USER_ALIGN (r) = 1;
11359           }
11360
11361         return r;
11362       }
11363
11364     case TYPENAME_TYPE:
11365       {
11366         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11367                                      in_decl, /*entering_scope=*/1);
11368         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11369                               complain, in_decl);
11370
11371         if (ctx == error_mark_node || f == error_mark_node)
11372           return error_mark_node;
11373
11374         if (!MAYBE_CLASS_TYPE_P (ctx))
11375           {
11376             if (complain & tf_error)
11377               error ("%qT is not a class, struct, or union type", ctx);
11378             return error_mark_node;
11379           }
11380         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11381           {
11382             /* Normally, make_typename_type does not require that the CTX
11383                have complete type in order to allow things like:
11384
11385                  template <class T> struct S { typename S<T>::X Y; };
11386
11387                But, such constructs have already been resolved by this
11388                point, so here CTX really should have complete type, unless
11389                it's a partial instantiation.  */
11390             ctx = complete_type (ctx);
11391             if (!COMPLETE_TYPE_P (ctx))
11392               {
11393                 if (complain & tf_error)
11394                   cxx_incomplete_type_error (NULL_TREE, ctx);
11395                 return error_mark_node;
11396               }
11397           }
11398
11399         f = make_typename_type (ctx, f, typename_type,
11400                                 (complain & tf_error) | tf_keep_type_decl);
11401         if (f == error_mark_node)
11402           return f;
11403         if (TREE_CODE (f) == TYPE_DECL)
11404           {
11405             complain |= tf_ignore_bad_quals;
11406             f = TREE_TYPE (f);
11407           }
11408
11409         if (TREE_CODE (f) != TYPENAME_TYPE)
11410           {
11411             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11412               {
11413                 if (complain & tf_error)
11414                   error ("%qT resolves to %qT, which is not an enumeration type",
11415                          t, f);
11416                 else
11417                   return error_mark_node;
11418               }
11419             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11420               {
11421                 if (complain & tf_error)
11422                   error ("%qT resolves to %qT, which is is not a class type",
11423                          t, f);
11424                 else
11425                   return error_mark_node;
11426               }
11427           }
11428
11429         return cp_build_qualified_type_real
11430           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11431       }
11432
11433     case UNBOUND_CLASS_TEMPLATE:
11434       {
11435         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11436                                      in_decl, /*entering_scope=*/1);
11437         tree name = TYPE_IDENTIFIER (t);
11438         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11439
11440         if (ctx == error_mark_node || name == error_mark_node)
11441           return error_mark_node;
11442
11443         if (parm_list)
11444           parm_list = tsubst_template_parms (parm_list, args, complain);
11445         return make_unbound_class_template (ctx, name, parm_list, complain);
11446       }
11447
11448     case TYPEOF_TYPE:
11449       {
11450         tree type;
11451
11452         ++cp_unevaluated_operand;
11453         ++c_inhibit_evaluation_warnings;
11454
11455         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11456                             complain, in_decl,
11457                             /*integral_constant_expression_p=*/false);
11458
11459         --cp_unevaluated_operand;
11460         --c_inhibit_evaluation_warnings;
11461
11462         type = finish_typeof (type);
11463         return cp_build_qualified_type_real (type,
11464                                              cp_type_quals (t)
11465                                              | cp_type_quals (type),
11466                                              complain);
11467       }
11468
11469     case DECLTYPE_TYPE:
11470       {
11471         tree type;
11472
11473         ++cp_unevaluated_operand;
11474         ++c_inhibit_evaluation_warnings;
11475
11476         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11477                             complain, in_decl,
11478                             /*integral_constant_expression_p=*/false);
11479
11480         --cp_unevaluated_operand;
11481         --c_inhibit_evaluation_warnings;
11482
11483         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11484           type = lambda_capture_field_type (type);
11485         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11486           type = lambda_proxy_type (type);
11487         else
11488           type = finish_decltype_type
11489             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11490         return cp_build_qualified_type_real (type,
11491                                              cp_type_quals (t)
11492                                              | cp_type_quals (type),
11493                                              complain);
11494       }
11495
11496     case UNDERLYING_TYPE:
11497       {
11498         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11499                             complain, in_decl);
11500         return finish_underlying_type (type);
11501       }
11502
11503     case TYPE_ARGUMENT_PACK:
11504     case NONTYPE_ARGUMENT_PACK:
11505       {
11506         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11507         tree packed_out = 
11508           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11509                                 args,
11510                                 complain,
11511                                 in_decl);
11512         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11513
11514         /* For template nontype argument packs, also substitute into
11515            the type.  */
11516         if (code == NONTYPE_ARGUMENT_PACK)
11517           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11518
11519         return r;
11520       }
11521       break;
11522
11523     case INTEGER_CST:
11524     case REAL_CST:
11525     case STRING_CST:
11526     case PLUS_EXPR:
11527     case MINUS_EXPR:
11528     case NEGATE_EXPR:
11529     case NOP_EXPR:
11530     case INDIRECT_REF:
11531     case ADDR_EXPR:
11532     case CALL_EXPR:
11533     case ARRAY_REF:
11534     case SCOPE_REF:
11535       /* We should use one of the expression tsubsts for these codes.  */
11536       gcc_unreachable ();
11537
11538     default:
11539       sorry ("use of %qs in template", tree_code_name [(int) code]);
11540       return error_mark_node;
11541     }
11542 }
11543
11544 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11545    type of the expression on the left-hand side of the "." or "->"
11546    operator.  */
11547
11548 static tree
11549 tsubst_baselink (tree baselink, tree object_type,
11550                  tree args, tsubst_flags_t complain, tree in_decl)
11551 {
11552     tree name;
11553     tree qualifying_scope;
11554     tree fns;
11555     tree optype;
11556     tree template_args = 0;
11557     bool template_id_p = false;
11558
11559     /* A baselink indicates a function from a base class.  Both the
11560        BASELINK_ACCESS_BINFO and the base class referenced may
11561        indicate bases of the template class, rather than the
11562        instantiated class.  In addition, lookups that were not
11563        ambiguous before may be ambiguous now.  Therefore, we perform
11564        the lookup again.  */
11565     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11566     qualifying_scope = tsubst (qualifying_scope, args,
11567                                complain, in_decl);
11568     fns = BASELINK_FUNCTIONS (baselink);
11569     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11570     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11571       {
11572         template_id_p = true;
11573         template_args = TREE_OPERAND (fns, 1);
11574         fns = TREE_OPERAND (fns, 0);
11575         if (template_args)
11576           template_args = tsubst_template_args (template_args, args,
11577                                                 complain, in_decl);
11578       }
11579     name = DECL_NAME (get_first_fn (fns));
11580     if (IDENTIFIER_TYPENAME_P (name))
11581       name = mangle_conv_op_name_for_type (optype);
11582     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11583     if (!baselink)
11584       return error_mark_node;
11585
11586     /* If lookup found a single function, mark it as used at this
11587        point.  (If it lookup found multiple functions the one selected
11588        later by overload resolution will be marked as used at that
11589        point.)  */
11590     if (BASELINK_P (baselink))
11591       fns = BASELINK_FUNCTIONS (baselink);
11592     if (!template_id_p && !really_overloaded_fn (fns))
11593       mark_used (OVL_CURRENT (fns));
11594
11595     /* Add back the template arguments, if present.  */
11596     if (BASELINK_P (baselink) && template_id_p)
11597       BASELINK_FUNCTIONS (baselink)
11598         = build_nt (TEMPLATE_ID_EXPR,
11599                     BASELINK_FUNCTIONS (baselink),
11600                     template_args);
11601     /* Update the conversion operator type.  */
11602     BASELINK_OPTYPE (baselink) = optype;
11603
11604     if (!object_type)
11605       object_type = current_class_type;
11606     return adjust_result_of_qualified_name_lookup (baselink,
11607                                                    qualifying_scope,
11608                                                    object_type);
11609 }
11610
11611 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11612    true if the qualified-id will be a postfix-expression in-and-of
11613    itself; false if more of the postfix-expression follows the
11614    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11615    of "&".  */
11616
11617 static tree
11618 tsubst_qualified_id (tree qualified_id, tree args,
11619                      tsubst_flags_t complain, tree in_decl,
11620                      bool done, bool address_p)
11621 {
11622   tree expr;
11623   tree scope;
11624   tree name;
11625   bool is_template;
11626   tree template_args;
11627
11628   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11629
11630   /* Figure out what name to look up.  */
11631   name = TREE_OPERAND (qualified_id, 1);
11632   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11633     {
11634       is_template = true;
11635       template_args = TREE_OPERAND (name, 1);
11636       if (template_args)
11637         template_args = tsubst_template_args (template_args, args,
11638                                               complain, in_decl);
11639       name = TREE_OPERAND (name, 0);
11640     }
11641   else
11642     {
11643       is_template = false;
11644       template_args = NULL_TREE;
11645     }
11646
11647   /* Substitute into the qualifying scope.  When there are no ARGS, we
11648      are just trying to simplify a non-dependent expression.  In that
11649      case the qualifying scope may be dependent, and, in any case,
11650      substituting will not help.  */
11651   scope = TREE_OPERAND (qualified_id, 0);
11652   if (args)
11653     {
11654       scope = tsubst (scope, args, complain, in_decl);
11655       expr = tsubst_copy (name, args, complain, in_decl);
11656     }
11657   else
11658     expr = name;
11659
11660   if (dependent_scope_p (scope))
11661     {
11662       if (is_template)
11663         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11664       return build_qualified_name (NULL_TREE, scope, expr,
11665                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11666     }
11667
11668   if (!BASELINK_P (name) && !DECL_P (expr))
11669     {
11670       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11671         {
11672           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11673           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11674             {
11675               error ("qualifying type %qT does not match destructor name ~%qT",
11676                      scope, TREE_OPERAND (expr, 0));
11677               expr = error_mark_node;
11678             }
11679           else
11680             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11681                                           /*is_type_p=*/0, false);
11682         }
11683       else
11684         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11685       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11686                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11687         {
11688           if (complain & tf_error)
11689             {
11690               error ("dependent-name %qE is parsed as a non-type, but "
11691                      "instantiation yields a type", qualified_id);
11692               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11693             }
11694           return error_mark_node;
11695         }
11696     }
11697
11698   if (DECL_P (expr))
11699     {
11700       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11701                                            scope);
11702       /* Remember that there was a reference to this entity.  */
11703       mark_used (expr);
11704     }
11705
11706   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11707     {
11708       if (complain & tf_error)
11709         qualified_name_lookup_error (scope,
11710                                      TREE_OPERAND (qualified_id, 1),
11711                                      expr, input_location);
11712       return error_mark_node;
11713     }
11714
11715   if (is_template)
11716     expr = lookup_template_function (expr, template_args);
11717
11718   if (expr == error_mark_node && complain & tf_error)
11719     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11720                                  expr, input_location);
11721   else if (TYPE_P (scope))
11722     {
11723       expr = (adjust_result_of_qualified_name_lookup
11724               (expr, scope, current_class_type));
11725       expr = (finish_qualified_id_expr
11726               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11727                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11728                /*template_arg_p=*/false));
11729     }
11730
11731   /* Expressions do not generally have reference type.  */
11732   if (TREE_CODE (expr) != SCOPE_REF
11733       /* However, if we're about to form a pointer-to-member, we just
11734          want the referenced member referenced.  */
11735       && TREE_CODE (expr) != OFFSET_REF)
11736     expr = convert_from_reference (expr);
11737
11738   return expr;
11739 }
11740
11741 /* Like tsubst, but deals with expressions.  This function just replaces
11742    template parms; to finish processing the resultant expression, use
11743    tsubst_copy_and_build or tsubst_expr.  */
11744
11745 static tree
11746 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11747 {
11748   enum tree_code code;
11749   tree r;
11750
11751   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11752     return t;
11753
11754   code = TREE_CODE (t);
11755
11756   switch (code)
11757     {
11758     case PARM_DECL:
11759       r = retrieve_local_specialization (t);
11760
11761       if (r == NULL)
11762         {
11763           tree c;
11764
11765           /* We get here for a use of 'this' in an NSDMI.  */
11766           if (DECL_NAME (t) == this_identifier
11767               && at_function_scope_p ()
11768               && DECL_CONSTRUCTOR_P (current_function_decl))
11769             return current_class_ptr;
11770
11771           /* This can happen for a parameter name used later in a function
11772              declaration (such as in a late-specified return type).  Just
11773              make a dummy decl, since it's only used for its type.  */
11774           gcc_assert (cp_unevaluated_operand != 0);
11775           /* We copy T because want to tsubst the PARM_DECL only,
11776              not the following PARM_DECLs that are chained to T.  */
11777           c = copy_node (t);
11778           r = tsubst_decl (c, args, complain);
11779           /* Give it the template pattern as its context; its true context
11780              hasn't been instantiated yet and this is good enough for
11781              mangling.  */
11782           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11783         }
11784       
11785       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11786         r = ARGUMENT_PACK_SELECT_ARG (r);
11787       mark_used (r);
11788       return r;
11789
11790     case CONST_DECL:
11791       {
11792         tree enum_type;
11793         tree v;
11794
11795         if (DECL_TEMPLATE_PARM_P (t))
11796           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11797         /* There is no need to substitute into namespace-scope
11798            enumerators.  */
11799         if (DECL_NAMESPACE_SCOPE_P (t))
11800           return t;
11801         /* If ARGS is NULL, then T is known to be non-dependent.  */
11802         if (args == NULL_TREE)
11803           return integral_constant_value (t);
11804
11805         /* Unfortunately, we cannot just call lookup_name here.
11806            Consider:
11807
11808              template <int I> int f() {
11809              enum E { a = I };
11810              struct S { void g() { E e = a; } };
11811              };
11812
11813            When we instantiate f<7>::S::g(), say, lookup_name is not
11814            clever enough to find f<7>::a.  */
11815         enum_type
11816           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11817                               /*entering_scope=*/0);
11818
11819         for (v = TYPE_VALUES (enum_type);
11820              v != NULL_TREE;
11821              v = TREE_CHAIN (v))
11822           if (TREE_PURPOSE (v) == DECL_NAME (t))
11823             return TREE_VALUE (v);
11824
11825           /* We didn't find the name.  That should never happen; if
11826              name-lookup found it during preliminary parsing, we
11827              should find it again here during instantiation.  */
11828         gcc_unreachable ();
11829       }
11830       return t;
11831
11832     case FIELD_DECL:
11833       if (DECL_CONTEXT (t))
11834         {
11835           tree ctx;
11836
11837           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11838                                   /*entering_scope=*/1);
11839           if (ctx != DECL_CONTEXT (t))
11840             {
11841               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11842               if (!r)
11843                 {
11844                   if (complain & tf_error)
11845                     error ("using invalid field %qD", t);
11846                   return error_mark_node;
11847                 }
11848               return r;
11849             }
11850         }
11851
11852       return t;
11853
11854     case VAR_DECL:
11855     case FUNCTION_DECL:
11856       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11857           || local_variable_p (t))
11858         t = tsubst (t, args, complain, in_decl);
11859       mark_used (t);
11860       return t;
11861
11862     case OVERLOAD:
11863       /* An OVERLOAD will always be a non-dependent overload set; an
11864          overload set from function scope will just be represented with an
11865          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11866       gcc_assert (!uses_template_parms (t));
11867       return t;
11868
11869     case BASELINK:
11870       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11871
11872     case TEMPLATE_DECL:
11873       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11874         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11875                        args, complain, in_decl);
11876       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11877         return tsubst (t, args, complain, in_decl);
11878       else if (DECL_CLASS_SCOPE_P (t)
11879                && uses_template_parms (DECL_CONTEXT (t)))
11880         {
11881           /* Template template argument like the following example need
11882              special treatment:
11883
11884                template <template <class> class TT> struct C {};
11885                template <class T> struct D {
11886                  template <class U> struct E {};
11887                  C<E> c;                                // #1
11888                };
11889                D<int> d;                                // #2
11890
11891              We are processing the template argument `E' in #1 for
11892              the template instantiation #2.  Originally, `E' is a
11893              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11894              have to substitute this with one having context `D<int>'.  */
11895
11896           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11897           return lookup_field (context, DECL_NAME(t), 0, false);
11898         }
11899       else
11900         /* Ordinary template template argument.  */
11901         return t;
11902
11903     case CAST_EXPR:
11904     case REINTERPRET_CAST_EXPR:
11905     case CONST_CAST_EXPR:
11906     case STATIC_CAST_EXPR:
11907     case DYNAMIC_CAST_EXPR:
11908     case IMPLICIT_CONV_EXPR:
11909     case CONVERT_EXPR:
11910     case NOP_EXPR:
11911       return build1
11912         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11913          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11914
11915     case SIZEOF_EXPR:
11916       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11917         {
11918
11919           tree expanded;
11920           int len = 0;
11921
11922           ++cp_unevaluated_operand;
11923           ++c_inhibit_evaluation_warnings;
11924           /* We only want to compute the number of arguments.  */
11925           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11926                                             complain, in_decl);
11927           --cp_unevaluated_operand;
11928           --c_inhibit_evaluation_warnings;
11929
11930           if (TREE_CODE (expanded) == TREE_VEC)
11931             len = TREE_VEC_LENGTH (expanded);
11932
11933           if (expanded == error_mark_node)
11934             return error_mark_node;
11935           else if (PACK_EXPANSION_P (expanded)
11936                    || (TREE_CODE (expanded) == TREE_VEC
11937                        && len > 0
11938                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11939             {
11940               if (TREE_CODE (expanded) == TREE_VEC)
11941                 expanded = TREE_VEC_ELT (expanded, len - 1);
11942
11943               if (TYPE_P (expanded))
11944                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11945                                                    complain & tf_error);
11946               else
11947                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11948                                                    complain & tf_error);
11949             }
11950           else
11951             return build_int_cst (size_type_node, len);
11952         }
11953       /* Fall through */
11954
11955     case INDIRECT_REF:
11956     case NEGATE_EXPR:
11957     case TRUTH_NOT_EXPR:
11958     case BIT_NOT_EXPR:
11959     case ADDR_EXPR:
11960     case UNARY_PLUS_EXPR:      /* Unary + */
11961     case ALIGNOF_EXPR:
11962     case AT_ENCODE_EXPR:
11963     case ARROW_EXPR:
11964     case THROW_EXPR:
11965     case TYPEID_EXPR:
11966     case REALPART_EXPR:
11967     case IMAGPART_EXPR:
11968       return build1
11969         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11970          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11971
11972     case COMPONENT_REF:
11973       {
11974         tree object;
11975         tree name;
11976
11977         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11978         name = TREE_OPERAND (t, 1);
11979         if (TREE_CODE (name) == BIT_NOT_EXPR)
11980           {
11981             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11982                                 complain, in_decl);
11983             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11984           }
11985         else if (TREE_CODE (name) == SCOPE_REF
11986                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11987           {
11988             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11989                                      complain, in_decl);
11990             name = TREE_OPERAND (name, 1);
11991             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11992                                 complain, in_decl);
11993             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11994             name = build_qualified_name (/*type=*/NULL_TREE,
11995                                          base, name,
11996                                          /*template_p=*/false);
11997           }
11998         else if (BASELINK_P (name))
11999           name = tsubst_baselink (name,
12000                                   non_reference (TREE_TYPE (object)),
12001                                   args, complain,
12002                                   in_decl);
12003         else
12004           name = tsubst_copy (name, args, complain, in_decl);
12005         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
12006       }
12007
12008     case PLUS_EXPR:
12009     case MINUS_EXPR:
12010     case MULT_EXPR:
12011     case TRUNC_DIV_EXPR:
12012     case CEIL_DIV_EXPR:
12013     case FLOOR_DIV_EXPR:
12014     case ROUND_DIV_EXPR:
12015     case EXACT_DIV_EXPR:
12016     case BIT_AND_EXPR:
12017     case BIT_IOR_EXPR:
12018     case BIT_XOR_EXPR:
12019     case TRUNC_MOD_EXPR:
12020     case FLOOR_MOD_EXPR:
12021     case TRUTH_ANDIF_EXPR:
12022     case TRUTH_ORIF_EXPR:
12023     case TRUTH_AND_EXPR:
12024     case TRUTH_OR_EXPR:
12025     case RSHIFT_EXPR:
12026     case LSHIFT_EXPR:
12027     case RROTATE_EXPR:
12028     case LROTATE_EXPR:
12029     case EQ_EXPR:
12030     case NE_EXPR:
12031     case MAX_EXPR:
12032     case MIN_EXPR:
12033     case LE_EXPR:
12034     case GE_EXPR:
12035     case LT_EXPR:
12036     case GT_EXPR:
12037     case COMPOUND_EXPR:
12038     case DOTSTAR_EXPR:
12039     case MEMBER_REF:
12040     case PREDECREMENT_EXPR:
12041     case PREINCREMENT_EXPR:
12042     case POSTDECREMENT_EXPR:
12043     case POSTINCREMENT_EXPR:
12044       return build_nt
12045         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12046          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12047
12048     case SCOPE_REF:
12049       return build_qualified_name (/*type=*/NULL_TREE,
12050                                    tsubst_copy (TREE_OPERAND (t, 0),
12051                                                 args, complain, in_decl),
12052                                    tsubst_copy (TREE_OPERAND (t, 1),
12053                                                 args, complain, in_decl),
12054                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12055
12056     case ARRAY_REF:
12057       return build_nt
12058         (ARRAY_REF,
12059          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12060          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12061          NULL_TREE, NULL_TREE);
12062
12063     case CALL_EXPR:
12064       {
12065         int n = VL_EXP_OPERAND_LENGTH (t);
12066         tree result = build_vl_exp (CALL_EXPR, n);
12067         int i;
12068         for (i = 0; i < n; i++)
12069           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12070                                              complain, in_decl);
12071         return result;
12072       }
12073
12074     case COND_EXPR:
12075     case MODOP_EXPR:
12076     case PSEUDO_DTOR_EXPR:
12077       {
12078         r = build_nt
12079           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12080            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12081            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12082         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12083         return r;
12084       }
12085
12086     case NEW_EXPR:
12087       {
12088         r = build_nt
12089         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12090          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12091          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12092         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12093         return r;
12094       }
12095
12096     case DELETE_EXPR:
12097       {
12098         r = build_nt
12099         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12100          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12101         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12102         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12103         return r;
12104       }
12105
12106     case TEMPLATE_ID_EXPR:
12107       {
12108         /* Substituted template arguments */
12109         tree fn = TREE_OPERAND (t, 0);
12110         tree targs = TREE_OPERAND (t, 1);
12111
12112         fn = tsubst_copy (fn, args, complain, in_decl);
12113         if (targs)
12114           targs = tsubst_template_args (targs, args, complain, in_decl);
12115
12116         return lookup_template_function (fn, targs);
12117       }
12118
12119     case TREE_LIST:
12120       {
12121         tree purpose, value, chain;
12122
12123         if (t == void_list_node)
12124           return t;
12125
12126         purpose = TREE_PURPOSE (t);
12127         if (purpose)
12128           purpose = tsubst_copy (purpose, args, complain, in_decl);
12129         value = TREE_VALUE (t);
12130         if (value)
12131           value = tsubst_copy (value, args, complain, in_decl);
12132         chain = TREE_CHAIN (t);
12133         if (chain && chain != void_type_node)
12134           chain = tsubst_copy (chain, args, complain, in_decl);
12135         if (purpose == TREE_PURPOSE (t)
12136             && value == TREE_VALUE (t)
12137             && chain == TREE_CHAIN (t))
12138           return t;
12139         return tree_cons (purpose, value, chain);
12140       }
12141
12142     case RECORD_TYPE:
12143     case UNION_TYPE:
12144     case ENUMERAL_TYPE:
12145     case INTEGER_TYPE:
12146     case TEMPLATE_TYPE_PARM:
12147     case TEMPLATE_TEMPLATE_PARM:
12148     case BOUND_TEMPLATE_TEMPLATE_PARM:
12149     case TEMPLATE_PARM_INDEX:
12150     case POINTER_TYPE:
12151     case REFERENCE_TYPE:
12152     case OFFSET_TYPE:
12153     case FUNCTION_TYPE:
12154     case METHOD_TYPE:
12155     case ARRAY_TYPE:
12156     case TYPENAME_TYPE:
12157     case UNBOUND_CLASS_TEMPLATE:
12158     case TYPEOF_TYPE:
12159     case DECLTYPE_TYPE:
12160     case TYPE_DECL:
12161       return tsubst (t, args, complain, in_decl);
12162
12163     case IDENTIFIER_NODE:
12164       if (IDENTIFIER_TYPENAME_P (t))
12165         {
12166           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12167           return mangle_conv_op_name_for_type (new_type);
12168         }
12169       else
12170         return t;
12171
12172     case CONSTRUCTOR:
12173       /* This is handled by tsubst_copy_and_build.  */
12174       gcc_unreachable ();
12175
12176     case VA_ARG_EXPR:
12177       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12178                                           in_decl),
12179                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12180
12181     case CLEANUP_POINT_EXPR:
12182       /* We shouldn't have built any of these during initial template
12183          generation.  Instead, they should be built during instantiation
12184          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12185       gcc_unreachable ();
12186
12187     case OFFSET_REF:
12188       r = build2
12189         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12190          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12191          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12192       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12193       mark_used (TREE_OPERAND (r, 1));
12194       return r;
12195
12196     case EXPR_PACK_EXPANSION:
12197       error ("invalid use of pack expansion expression");
12198       return error_mark_node;
12199
12200     case NONTYPE_ARGUMENT_PACK:
12201       error ("use %<...%> to expand argument pack");
12202       return error_mark_node;
12203
12204     case INTEGER_CST:
12205     case REAL_CST:
12206     case STRING_CST:
12207     case COMPLEX_CST:
12208       {
12209         /* Instantiate any typedefs in the type.  */
12210         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12211         r = fold_convert (type, t);
12212         gcc_assert (TREE_CODE (r) == code);
12213         return r;
12214       }
12215
12216     case PTRMEM_CST:
12217       /* These can sometimes show up in a partial instantiation, but never
12218          involve template parms.  */
12219       gcc_assert (!uses_template_parms (t));
12220       return t;
12221
12222     default:
12223       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12224       gcc_checking_assert (false);
12225       return t;
12226     }
12227 }
12228
12229 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12230
12231 static tree
12232 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12233                     tree in_decl)
12234 {
12235   tree new_clauses = NULL, nc, oc;
12236
12237   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12238     {
12239       nc = copy_node (oc);
12240       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12241       new_clauses = nc;
12242
12243       switch (OMP_CLAUSE_CODE (nc))
12244         {
12245         case OMP_CLAUSE_LASTPRIVATE:
12246           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12247             {
12248               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12249               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12250                            in_decl, /*integral_constant_expression_p=*/false);
12251               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12252                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12253             }
12254           /* FALLTHRU */
12255         case OMP_CLAUSE_PRIVATE:
12256         case OMP_CLAUSE_SHARED:
12257         case OMP_CLAUSE_FIRSTPRIVATE:
12258         case OMP_CLAUSE_REDUCTION:
12259         case OMP_CLAUSE_COPYIN:
12260         case OMP_CLAUSE_COPYPRIVATE:
12261         case OMP_CLAUSE_IF:
12262         case OMP_CLAUSE_NUM_THREADS:
12263         case OMP_CLAUSE_SCHEDULE:
12264         case OMP_CLAUSE_COLLAPSE:
12265         case OMP_CLAUSE_FINAL:
12266           OMP_CLAUSE_OPERAND (nc, 0)
12267             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12268                            in_decl, /*integral_constant_expression_p=*/false);
12269           break;
12270         case OMP_CLAUSE_NOWAIT:
12271         case OMP_CLAUSE_ORDERED:
12272         case OMP_CLAUSE_DEFAULT:
12273         case OMP_CLAUSE_UNTIED:
12274         case OMP_CLAUSE_MERGEABLE:
12275           break;
12276         default:
12277           gcc_unreachable ();
12278         }
12279     }
12280
12281   return finish_omp_clauses (nreverse (new_clauses));
12282 }
12283
12284 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12285
12286 static tree
12287 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12288                           tree in_decl)
12289 {
12290 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12291
12292   tree purpose, value, chain;
12293
12294   if (t == NULL)
12295     return t;
12296
12297   if (TREE_CODE (t) != TREE_LIST)
12298     return tsubst_copy_and_build (t, args, complain, in_decl,
12299                                   /*function_p=*/false,
12300                                   /*integral_constant_expression_p=*/false);
12301
12302   if (t == void_list_node)
12303     return t;
12304
12305   purpose = TREE_PURPOSE (t);
12306   if (purpose)
12307     purpose = RECUR (purpose);
12308   value = TREE_VALUE (t);
12309   if (value && TREE_CODE (value) != LABEL_DECL)
12310     value = RECUR (value);
12311   chain = TREE_CHAIN (t);
12312   if (chain && chain != void_type_node)
12313     chain = RECUR (chain);
12314   return tree_cons (purpose, value, chain);
12315 #undef RECUR
12316 }
12317
12318 /* Substitute one OMP_FOR iterator.  */
12319
12320 static void
12321 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12322                          tree condv, tree incrv, tree *clauses,
12323                          tree args, tsubst_flags_t complain, tree in_decl,
12324                          bool integral_constant_expression_p)
12325 {
12326 #define RECUR(NODE)                             \
12327   tsubst_expr ((NODE), args, complain, in_decl, \
12328                integral_constant_expression_p)
12329   tree decl, init, cond, incr, auto_node;
12330
12331   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12332   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12333   decl = RECUR (TREE_OPERAND (init, 0));
12334   init = TREE_OPERAND (init, 1);
12335   auto_node = type_uses_auto (TREE_TYPE (decl));
12336   if (auto_node && init)
12337     {
12338       tree init_expr = init;
12339       if (TREE_CODE (init_expr) == DECL_EXPR)
12340         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12341       init_expr = RECUR (init_expr);
12342       TREE_TYPE (decl)
12343         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12344     }
12345   gcc_assert (!type_dependent_expression_p (decl));
12346
12347   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12348     {
12349       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12350       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12351       if (TREE_CODE (incr) == MODIFY_EXPR)
12352         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12353                                     RECUR (TREE_OPERAND (incr, 1)),
12354                                     complain);
12355       else
12356         incr = RECUR (incr);
12357       TREE_VEC_ELT (declv, i) = decl;
12358       TREE_VEC_ELT (initv, i) = init;
12359       TREE_VEC_ELT (condv, i) = cond;
12360       TREE_VEC_ELT (incrv, i) = incr;
12361       return;
12362     }
12363
12364   if (init && TREE_CODE (init) != DECL_EXPR)
12365     {
12366       tree c;
12367       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12368         {
12369           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12370                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12371               && OMP_CLAUSE_DECL (c) == decl)
12372             break;
12373           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12374                    && OMP_CLAUSE_DECL (c) == decl)
12375             error ("iteration variable %qD should not be firstprivate", decl);
12376           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12377                    && OMP_CLAUSE_DECL (c) == decl)
12378             error ("iteration variable %qD should not be reduction", decl);
12379         }
12380       if (c == NULL)
12381         {
12382           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12383           OMP_CLAUSE_DECL (c) = decl;
12384           c = finish_omp_clauses (c);
12385           if (c)
12386             {
12387               OMP_CLAUSE_CHAIN (c) = *clauses;
12388               *clauses = c;
12389             }
12390         }
12391     }
12392   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12393   if (COMPARISON_CLASS_P (cond))
12394     cond = build2 (TREE_CODE (cond), boolean_type_node,
12395                    RECUR (TREE_OPERAND (cond, 0)),
12396                    RECUR (TREE_OPERAND (cond, 1)));
12397   else
12398     cond = RECUR (cond);
12399   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12400   switch (TREE_CODE (incr))
12401     {
12402     case PREINCREMENT_EXPR:
12403     case PREDECREMENT_EXPR:
12404     case POSTINCREMENT_EXPR:
12405     case POSTDECREMENT_EXPR:
12406       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12407                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12408       break;
12409     case MODIFY_EXPR:
12410       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12411           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12412         {
12413           tree rhs = TREE_OPERAND (incr, 1);
12414           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12415                          RECUR (TREE_OPERAND (incr, 0)),
12416                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12417                                  RECUR (TREE_OPERAND (rhs, 0)),
12418                                  RECUR (TREE_OPERAND (rhs, 1))));
12419         }
12420       else
12421         incr = RECUR (incr);
12422       break;
12423     case MODOP_EXPR:
12424       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12425           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12426         {
12427           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12428           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12429                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12430                                  TREE_TYPE (decl), lhs,
12431                                  RECUR (TREE_OPERAND (incr, 2))));
12432         }
12433       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12434                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12435                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12436         {
12437           tree rhs = TREE_OPERAND (incr, 2);
12438           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12439                          RECUR (TREE_OPERAND (incr, 0)),
12440                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12441                                  RECUR (TREE_OPERAND (rhs, 0)),
12442                                  RECUR (TREE_OPERAND (rhs, 1))));
12443         }
12444       else
12445         incr = RECUR (incr);
12446       break;
12447     default:
12448       incr = RECUR (incr);
12449       break;
12450     }
12451
12452   TREE_VEC_ELT (declv, i) = decl;
12453   TREE_VEC_ELT (initv, i) = init;
12454   TREE_VEC_ELT (condv, i) = cond;
12455   TREE_VEC_ELT (incrv, i) = incr;
12456 #undef RECUR
12457 }
12458
12459 /* Like tsubst_copy for expressions, etc. but also does semantic
12460    processing.  */
12461
12462 static tree
12463 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12464              bool integral_constant_expression_p)
12465 {
12466 #define RECUR(NODE)                             \
12467   tsubst_expr ((NODE), args, complain, in_decl, \
12468                integral_constant_expression_p)
12469
12470   tree stmt, tmp;
12471
12472   if (t == NULL_TREE || t == error_mark_node)
12473     return t;
12474
12475   if (EXPR_HAS_LOCATION (t))
12476     input_location = EXPR_LOCATION (t);
12477   if (STATEMENT_CODE_P (TREE_CODE (t)))
12478     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12479
12480   switch (TREE_CODE (t))
12481     {
12482     case STATEMENT_LIST:
12483       {
12484         tree_stmt_iterator i;
12485         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12486           RECUR (tsi_stmt (i));
12487         break;
12488       }
12489
12490     case CTOR_INITIALIZER:
12491       finish_mem_initializers (tsubst_initializer_list
12492                                (TREE_OPERAND (t, 0), args));
12493       break;
12494
12495     case RETURN_EXPR:
12496       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12497       break;
12498
12499     case EXPR_STMT:
12500       tmp = RECUR (EXPR_STMT_EXPR (t));
12501       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12502         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12503       else
12504         finish_expr_stmt (tmp);
12505       break;
12506
12507     case USING_STMT:
12508       do_using_directive (USING_STMT_NAMESPACE (t));
12509       break;
12510
12511     case DECL_EXPR:
12512       {
12513         tree decl, pattern_decl;
12514         tree init;
12515
12516         pattern_decl = decl = DECL_EXPR_DECL (t);
12517         if (TREE_CODE (decl) == LABEL_DECL)
12518           finish_label_decl (DECL_NAME (decl));
12519         else if (TREE_CODE (decl) == USING_DECL)
12520           {
12521             tree scope = USING_DECL_SCOPE (decl);
12522             tree name = DECL_NAME (decl);
12523             tree decl;
12524
12525             scope = tsubst (scope, args, complain, in_decl);
12526             decl = lookup_qualified_name (scope, name,
12527                                           /*is_type_p=*/false,
12528                                           /*complain=*/false);
12529             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12530               qualified_name_lookup_error (scope, name, decl, input_location);
12531             else
12532               do_local_using_decl (decl, scope, name);
12533           }
12534         else
12535           {
12536             init = DECL_INITIAL (decl);
12537             decl = tsubst (decl, args, complain, in_decl);
12538             if (decl != error_mark_node)
12539               {
12540                 /* By marking the declaration as instantiated, we avoid
12541                    trying to instantiate it.  Since instantiate_decl can't
12542                    handle local variables, and since we've already done
12543                    all that needs to be done, that's the right thing to
12544                    do.  */
12545                 if (TREE_CODE (decl) == VAR_DECL)
12546                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12547                 if (TREE_CODE (decl) == VAR_DECL
12548                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12549                   /* Anonymous aggregates are a special case.  */
12550                   finish_anon_union (decl);
12551                 else
12552                   {
12553                     int const_init = false;
12554                     maybe_push_decl (decl);
12555                     if (TREE_CODE (decl) == VAR_DECL
12556                         && DECL_PRETTY_FUNCTION_P (decl))
12557                       {
12558                         /* For __PRETTY_FUNCTION__ we have to adjust the
12559                            initializer.  */
12560                         const char *const name
12561                           = cxx_printable_name (current_function_decl, 2);
12562                         init = cp_fname_init (name, &TREE_TYPE (decl));
12563                       }
12564                     else
12565                       {
12566                         tree t = RECUR (init);
12567
12568                         if (init && !t)
12569                           {
12570                             /* If we had an initializer but it
12571                                instantiated to nothing,
12572                                value-initialize the object.  This will
12573                                only occur when the initializer was a
12574                                pack expansion where the parameter packs
12575                                used in that expansion were of length
12576                                zero.  */
12577                             init = build_value_init (TREE_TYPE (decl),
12578                                                      complain);
12579                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12580                               init = get_target_expr_sfinae (init, complain);
12581                           }
12582                         else
12583                           init = t;
12584                       }
12585
12586                     if (TREE_CODE (decl) == VAR_DECL)
12587                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12588                                     (pattern_decl));
12589                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12590                   }
12591               }
12592           }
12593
12594         /* A DECL_EXPR can also be used as an expression, in the condition
12595            clause of an if/for/while construct.  */
12596         return decl;
12597       }
12598
12599     case FOR_STMT:
12600       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12601       RECUR (FOR_INIT_STMT (t));
12602       finish_for_init_stmt (stmt);
12603       tmp = RECUR (FOR_COND (t));
12604       finish_for_cond (tmp, stmt);
12605       tmp = RECUR (FOR_EXPR (t));
12606       finish_for_expr (tmp, stmt);
12607       RECUR (FOR_BODY (t));
12608       finish_for_stmt (stmt);
12609       break;
12610
12611     case RANGE_FOR_STMT:
12612       {
12613         tree decl, expr;
12614         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12615         decl = RANGE_FOR_DECL (t);
12616         decl = tsubst (decl, args, complain, in_decl);
12617         maybe_push_decl (decl);
12618         expr = RECUR (RANGE_FOR_EXPR (t));
12619         stmt = cp_convert_range_for (stmt, decl, expr);
12620         RECUR (RANGE_FOR_BODY (t));
12621         finish_for_stmt (stmt);
12622       }
12623       break;
12624
12625     case WHILE_STMT:
12626       stmt = begin_while_stmt ();
12627       tmp = RECUR (WHILE_COND (t));
12628       finish_while_stmt_cond (tmp, stmt);
12629       RECUR (WHILE_BODY (t));
12630       finish_while_stmt (stmt);
12631       break;
12632
12633     case DO_STMT:
12634       stmt = begin_do_stmt ();
12635       RECUR (DO_BODY (t));
12636       finish_do_body (stmt);
12637       tmp = RECUR (DO_COND (t));
12638       finish_do_stmt (tmp, stmt);
12639       break;
12640
12641     case IF_STMT:
12642       stmt = begin_if_stmt ();
12643       tmp = RECUR (IF_COND (t));
12644       finish_if_stmt_cond (tmp, stmt);
12645       RECUR (THEN_CLAUSE (t));
12646       finish_then_clause (stmt);
12647
12648       if (ELSE_CLAUSE (t))
12649         {
12650           begin_else_clause (stmt);
12651           RECUR (ELSE_CLAUSE (t));
12652           finish_else_clause (stmt);
12653         }
12654
12655       finish_if_stmt (stmt);
12656       break;
12657
12658     case BIND_EXPR:
12659       if (BIND_EXPR_BODY_BLOCK (t))
12660         stmt = begin_function_body ();
12661       else
12662         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12663                                     ? BCS_TRY_BLOCK : 0);
12664
12665       RECUR (BIND_EXPR_BODY (t));
12666
12667       if (BIND_EXPR_BODY_BLOCK (t))
12668         finish_function_body (stmt);
12669       else
12670         finish_compound_stmt (stmt);
12671       break;
12672
12673     case BREAK_STMT:
12674       finish_break_stmt ();
12675       break;
12676
12677     case CONTINUE_STMT:
12678       finish_continue_stmt ();
12679       break;
12680
12681     case SWITCH_STMT:
12682       stmt = begin_switch_stmt ();
12683       tmp = RECUR (SWITCH_STMT_COND (t));
12684       finish_switch_cond (tmp, stmt);
12685       RECUR (SWITCH_STMT_BODY (t));
12686       finish_switch_stmt (stmt);
12687       break;
12688
12689     case CASE_LABEL_EXPR:
12690       finish_case_label (EXPR_LOCATION (t),
12691                          RECUR (CASE_LOW (t)),
12692                          RECUR (CASE_HIGH (t)));
12693       break;
12694
12695     case LABEL_EXPR:
12696       {
12697         tree decl = LABEL_EXPR_LABEL (t);
12698         tree label;
12699
12700         label = finish_label_stmt (DECL_NAME (decl));
12701         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12702           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12703       }
12704       break;
12705
12706     case GOTO_EXPR:
12707       tmp = GOTO_DESTINATION (t);
12708       if (TREE_CODE (tmp) != LABEL_DECL)
12709         /* Computed goto's must be tsubst'd into.  On the other hand,
12710            non-computed gotos must not be; the identifier in question
12711            will have no binding.  */
12712         tmp = RECUR (tmp);
12713       else
12714         tmp = DECL_NAME (tmp);
12715       finish_goto_stmt (tmp);
12716       break;
12717
12718     case ASM_EXPR:
12719       tmp = finish_asm_stmt
12720         (ASM_VOLATILE_P (t),
12721          RECUR (ASM_STRING (t)),
12722          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12723          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12724          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12725          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12726       {
12727         tree asm_expr = tmp;
12728         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12729           asm_expr = TREE_OPERAND (asm_expr, 0);
12730         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12731       }
12732       break;
12733
12734     case TRY_BLOCK:
12735       if (CLEANUP_P (t))
12736         {
12737           stmt = begin_try_block ();
12738           RECUR (TRY_STMTS (t));
12739           finish_cleanup_try_block (stmt);
12740           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12741         }
12742       else
12743         {
12744           tree compound_stmt = NULL_TREE;
12745
12746           if (FN_TRY_BLOCK_P (t))
12747             stmt = begin_function_try_block (&compound_stmt);
12748           else
12749             stmt = begin_try_block ();
12750
12751           RECUR (TRY_STMTS (t));
12752
12753           if (FN_TRY_BLOCK_P (t))
12754             finish_function_try_block (stmt);
12755           else
12756             finish_try_block (stmt);
12757
12758           RECUR (TRY_HANDLERS (t));
12759           if (FN_TRY_BLOCK_P (t))
12760             finish_function_handler_sequence (stmt, compound_stmt);
12761           else
12762             finish_handler_sequence (stmt);
12763         }
12764       break;
12765
12766     case HANDLER:
12767       {
12768         tree decl = HANDLER_PARMS (t);
12769
12770         if (decl)
12771           {
12772             decl = tsubst (decl, args, complain, in_decl);
12773             /* Prevent instantiate_decl from trying to instantiate
12774                this variable.  We've already done all that needs to be
12775                done.  */
12776             if (decl != error_mark_node)
12777               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12778           }
12779         stmt = begin_handler ();
12780         finish_handler_parms (decl, stmt);
12781         RECUR (HANDLER_BODY (t));
12782         finish_handler (stmt);
12783       }
12784       break;
12785
12786     case TAG_DEFN:
12787       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12788       break;
12789
12790     case STATIC_ASSERT:
12791       {
12792         tree condition = 
12793           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12794                        args,
12795                        complain, in_decl,
12796                        /*integral_constant_expression_p=*/true);
12797         finish_static_assert (condition,
12798                               STATIC_ASSERT_MESSAGE (t),
12799                               STATIC_ASSERT_SOURCE_LOCATION (t),
12800                               /*member_p=*/false);
12801       }
12802       break;
12803
12804     case OMP_PARALLEL:
12805       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12806                                 args, complain, in_decl);
12807       stmt = begin_omp_parallel ();
12808       RECUR (OMP_PARALLEL_BODY (t));
12809       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12810         = OMP_PARALLEL_COMBINED (t);
12811       break;
12812
12813     case OMP_TASK:
12814       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12815                                 args, complain, in_decl);
12816       stmt = begin_omp_task ();
12817       RECUR (OMP_TASK_BODY (t));
12818       finish_omp_task (tmp, stmt);
12819       break;
12820
12821     case OMP_FOR:
12822       {
12823         tree clauses, body, pre_body;
12824         tree declv, initv, condv, incrv;
12825         int i;
12826
12827         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12828                                       args, complain, in_decl);
12829         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12830         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12831         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12832         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12833
12834         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12835           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12836                                    &clauses, args, complain, in_decl,
12837                                    integral_constant_expression_p);
12838
12839         stmt = begin_omp_structured_block ();
12840
12841         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12842           if (TREE_VEC_ELT (initv, i) == NULL
12843               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12844             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12845           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12846             {
12847               tree init = RECUR (TREE_VEC_ELT (initv, i));
12848               gcc_assert (init == TREE_VEC_ELT (declv, i));
12849               TREE_VEC_ELT (initv, i) = NULL_TREE;
12850             }
12851           else
12852             {
12853               tree decl_expr = TREE_VEC_ELT (initv, i);
12854               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12855               gcc_assert (init != NULL);
12856               TREE_VEC_ELT (initv, i) = RECUR (init);
12857               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12858               RECUR (decl_expr);
12859               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12860             }
12861
12862         pre_body = push_stmt_list ();
12863         RECUR (OMP_FOR_PRE_BODY (t));
12864         pre_body = pop_stmt_list (pre_body);
12865
12866         body = push_stmt_list ();
12867         RECUR (OMP_FOR_BODY (t));
12868         body = pop_stmt_list (body);
12869
12870         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12871                             body, pre_body, clauses);
12872
12873         add_stmt (finish_omp_structured_block (stmt));
12874       }
12875       break;
12876
12877     case OMP_SECTIONS:
12878     case OMP_SINGLE:
12879       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12880       stmt = push_stmt_list ();
12881       RECUR (OMP_BODY (t));
12882       stmt = pop_stmt_list (stmt);
12883
12884       t = copy_node (t);
12885       OMP_BODY (t) = stmt;
12886       OMP_CLAUSES (t) = tmp;
12887       add_stmt (t);
12888       break;
12889
12890     case OMP_SECTION:
12891     case OMP_CRITICAL:
12892     case OMP_MASTER:
12893     case OMP_ORDERED:
12894       stmt = push_stmt_list ();
12895       RECUR (OMP_BODY (t));
12896       stmt = pop_stmt_list (stmt);
12897
12898       t = copy_node (t);
12899       OMP_BODY (t) = stmt;
12900       add_stmt (t);
12901       break;
12902
12903     case OMP_ATOMIC:
12904       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12905       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12906         {
12907           tree op1 = TREE_OPERAND (t, 1);
12908           tree rhs1 = NULL_TREE;
12909           tree lhs, rhs;
12910           if (TREE_CODE (op1) == COMPOUND_EXPR)
12911             {
12912               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12913               op1 = TREE_OPERAND (op1, 1);
12914             }
12915           lhs = RECUR (TREE_OPERAND (op1, 0));
12916           rhs = RECUR (TREE_OPERAND (op1, 1));
12917           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12918                              NULL_TREE, NULL_TREE, rhs1);
12919         }
12920       else
12921         {
12922           tree op1 = TREE_OPERAND (t, 1);
12923           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12924           tree rhs1 = NULL_TREE;
12925           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12926           enum tree_code opcode = NOP_EXPR;
12927           if (code == OMP_ATOMIC_READ)
12928             {
12929               v = RECUR (TREE_OPERAND (op1, 0));
12930               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12931             }
12932           else if (code == OMP_ATOMIC_CAPTURE_OLD
12933                    || code == OMP_ATOMIC_CAPTURE_NEW)
12934             {
12935               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12936               v = RECUR (TREE_OPERAND (op1, 0));
12937               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12938               if (TREE_CODE (op11) == COMPOUND_EXPR)
12939                 {
12940                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12941                   op11 = TREE_OPERAND (op11, 1);
12942                 }
12943               lhs = RECUR (TREE_OPERAND (op11, 0));
12944               rhs = RECUR (TREE_OPERAND (op11, 1));
12945               opcode = TREE_CODE (op11);
12946             }
12947           else
12948             {
12949               code = OMP_ATOMIC;
12950               lhs = RECUR (TREE_OPERAND (op1, 0));
12951               rhs = RECUR (TREE_OPERAND (op1, 1));
12952             }
12953           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12954         }
12955       break;
12956
12957     case EXPR_PACK_EXPANSION:
12958       error ("invalid use of pack expansion expression");
12959       return error_mark_node;
12960
12961     case NONTYPE_ARGUMENT_PACK:
12962       error ("use %<...%> to expand argument pack");
12963       return error_mark_node;
12964
12965     default:
12966       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12967
12968       return tsubst_copy_and_build (t, args, complain, in_decl,
12969                                     /*function_p=*/false,
12970                                     integral_constant_expression_p);
12971     }
12972
12973   return NULL_TREE;
12974 #undef RECUR
12975 }
12976
12977 /* T is a postfix-expression that is not being used in a function
12978    call.  Return the substituted version of T.  */
12979
12980 static tree
12981 tsubst_non_call_postfix_expression (tree t, tree args,
12982                                     tsubst_flags_t complain,
12983                                     tree in_decl)
12984 {
12985   if (TREE_CODE (t) == SCOPE_REF)
12986     t = tsubst_qualified_id (t, args, complain, in_decl,
12987                              /*done=*/false, /*address_p=*/false);
12988   else
12989     t = tsubst_copy_and_build (t, args, complain, in_decl,
12990                                /*function_p=*/false,
12991                                /*integral_constant_expression_p=*/false);
12992
12993   return t;
12994 }
12995
12996 /* Like tsubst but deals with expressions and performs semantic
12997    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12998
12999 tree
13000 tsubst_copy_and_build (tree t,
13001                        tree args,
13002                        tsubst_flags_t complain,
13003                        tree in_decl,
13004                        bool function_p,
13005                        bool integral_constant_expression_p)
13006 {
13007 #define RECUR(NODE)                                             \
13008   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
13009                          /*function_p=*/false,                  \
13010                          integral_constant_expression_p)
13011
13012   tree op1;
13013
13014   if (t == NULL_TREE || t == error_mark_node)
13015     return t;
13016
13017   switch (TREE_CODE (t))
13018     {
13019     case USING_DECL:
13020       t = DECL_NAME (t);
13021       /* Fall through.  */
13022     case IDENTIFIER_NODE:
13023       {
13024         tree decl;
13025         cp_id_kind idk;
13026         bool non_integral_constant_expression_p;
13027         const char *error_msg;
13028
13029         if (IDENTIFIER_TYPENAME_P (t))
13030           {
13031             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13032             t = mangle_conv_op_name_for_type (new_type);
13033           }
13034
13035         /* Look up the name.  */
13036         decl = lookup_name (t);
13037
13038         /* By convention, expressions use ERROR_MARK_NODE to indicate
13039            failure, not NULL_TREE.  */
13040         if (decl == NULL_TREE)
13041           decl = error_mark_node;
13042
13043         decl = finish_id_expression (t, decl, NULL_TREE,
13044                                      &idk,
13045                                      integral_constant_expression_p,
13046                                      /*allow_non_integral_constant_expression_p=*/false,
13047                                      &non_integral_constant_expression_p,
13048                                      /*template_p=*/false,
13049                                      /*done=*/true,
13050                                      /*address_p=*/false,
13051                                      /*template_arg_p=*/false,
13052                                      &error_msg,
13053                                      input_location);
13054         if (error_msg)
13055           error (error_msg);
13056         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13057           {
13058             if (complain & tf_error)
13059               unqualified_name_lookup_error (decl);
13060             decl = error_mark_node;
13061           }
13062         return decl;
13063       }
13064
13065     case TEMPLATE_ID_EXPR:
13066       {
13067         tree object;
13068         tree templ = RECUR (TREE_OPERAND (t, 0));
13069         tree targs = TREE_OPERAND (t, 1);
13070
13071         if (targs)
13072           targs = tsubst_template_args (targs, args, complain, in_decl);
13073
13074         if (TREE_CODE (templ) == COMPONENT_REF)
13075           {
13076             object = TREE_OPERAND (templ, 0);
13077             templ = TREE_OPERAND (templ, 1);
13078           }
13079         else
13080           object = NULL_TREE;
13081         templ = lookup_template_function (templ, targs);
13082
13083         if (object)
13084           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13085                          object, templ, NULL_TREE);
13086         else
13087           return baselink_for_fns (templ);
13088       }
13089
13090     case INDIRECT_REF:
13091       {
13092         tree r = RECUR (TREE_OPERAND (t, 0));
13093
13094         if (REFERENCE_REF_P (t))
13095           {
13096             /* A type conversion to reference type will be enclosed in
13097                such an indirect ref, but the substitution of the cast
13098                will have also added such an indirect ref.  */
13099             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13100               r = convert_from_reference (r);
13101           }
13102         else
13103           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13104         return r;
13105       }
13106
13107     case NOP_EXPR:
13108       return build_nop
13109         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13110          RECUR (TREE_OPERAND (t, 0)));
13111
13112     case IMPLICIT_CONV_EXPR:
13113       {
13114         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13115         tree expr = RECUR (TREE_OPERAND (t, 0));
13116         int flags = LOOKUP_IMPLICIT;
13117         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13118           flags = LOOKUP_NORMAL;
13119         return perform_implicit_conversion_flags (type, expr, complain,
13120                                                   flags);
13121       }
13122
13123     case CONVERT_EXPR:
13124       return build1
13125         (CONVERT_EXPR,
13126          tsubst (TREE_TYPE (t), args, complain, in_decl),
13127          RECUR (TREE_OPERAND (t, 0)));
13128
13129     case CAST_EXPR:
13130     case REINTERPRET_CAST_EXPR:
13131     case CONST_CAST_EXPR:
13132     case DYNAMIC_CAST_EXPR:
13133     case STATIC_CAST_EXPR:
13134       {
13135         tree type;
13136         tree op;
13137
13138         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13139         if (integral_constant_expression_p
13140             && !cast_valid_in_integral_constant_expression_p (type))
13141           {
13142             if (complain & tf_error)
13143               error ("a cast to a type other than an integral or "
13144                      "enumeration type cannot appear in a constant-expression");
13145             return error_mark_node; 
13146           }
13147
13148         op = RECUR (TREE_OPERAND (t, 0));
13149
13150         switch (TREE_CODE (t))
13151           {
13152           case CAST_EXPR:
13153             return build_functional_cast (type, op, complain);
13154           case REINTERPRET_CAST_EXPR:
13155             return build_reinterpret_cast (type, op, complain);
13156           case CONST_CAST_EXPR:
13157             return build_const_cast (type, op, complain);
13158           case DYNAMIC_CAST_EXPR:
13159             return build_dynamic_cast (type, op, complain);
13160           case STATIC_CAST_EXPR:
13161             return build_static_cast (type, op, complain);
13162           default:
13163             gcc_unreachable ();
13164           }
13165       }
13166
13167     case POSTDECREMENT_EXPR:
13168     case POSTINCREMENT_EXPR:
13169       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13170                                                 args, complain, in_decl);
13171       return build_x_unary_op (TREE_CODE (t), op1, complain);
13172
13173     case PREDECREMENT_EXPR:
13174     case PREINCREMENT_EXPR:
13175     case NEGATE_EXPR:
13176     case BIT_NOT_EXPR:
13177     case ABS_EXPR:
13178     case TRUTH_NOT_EXPR:
13179     case UNARY_PLUS_EXPR:  /* Unary + */
13180     case REALPART_EXPR:
13181     case IMAGPART_EXPR:
13182       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13183                                complain);
13184
13185     case ADDR_EXPR:
13186       op1 = TREE_OPERAND (t, 0);
13187       if (TREE_CODE (op1) == LABEL_DECL)
13188         return finish_label_address_expr (DECL_NAME (op1),
13189                                           EXPR_LOCATION (op1));
13190       if (TREE_CODE (op1) == SCOPE_REF)
13191         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13192                                    /*done=*/true, /*address_p=*/true);
13193       else
13194         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13195                                                   in_decl);
13196       return build_x_unary_op (ADDR_EXPR, op1, complain);
13197
13198     case PLUS_EXPR:
13199     case MINUS_EXPR:
13200     case MULT_EXPR:
13201     case TRUNC_DIV_EXPR:
13202     case CEIL_DIV_EXPR:
13203     case FLOOR_DIV_EXPR:
13204     case ROUND_DIV_EXPR:
13205     case EXACT_DIV_EXPR:
13206     case BIT_AND_EXPR:
13207     case BIT_IOR_EXPR:
13208     case BIT_XOR_EXPR:
13209     case TRUNC_MOD_EXPR:
13210     case FLOOR_MOD_EXPR:
13211     case TRUTH_ANDIF_EXPR:
13212     case TRUTH_ORIF_EXPR:
13213     case TRUTH_AND_EXPR:
13214     case TRUTH_OR_EXPR:
13215     case RSHIFT_EXPR:
13216     case LSHIFT_EXPR:
13217     case RROTATE_EXPR:
13218     case LROTATE_EXPR:
13219     case EQ_EXPR:
13220     case NE_EXPR:
13221     case MAX_EXPR:
13222     case MIN_EXPR:
13223     case LE_EXPR:
13224     case GE_EXPR:
13225     case LT_EXPR:
13226     case GT_EXPR:
13227     case MEMBER_REF:
13228     case DOTSTAR_EXPR:
13229       return build_x_binary_op
13230         (TREE_CODE (t),
13231          RECUR (TREE_OPERAND (t, 0)),
13232          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13233           ? ERROR_MARK
13234           : TREE_CODE (TREE_OPERAND (t, 0))),
13235          RECUR (TREE_OPERAND (t, 1)),
13236          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13237           ? ERROR_MARK
13238           : TREE_CODE (TREE_OPERAND (t, 1))),
13239          /*overload=*/NULL,
13240          complain);
13241
13242     case SCOPE_REF:
13243       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13244                                   /*address_p=*/false);
13245     case ARRAY_REF:
13246       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13247                                                 args, complain, in_decl);
13248       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13249
13250     case SIZEOF_EXPR:
13251       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13252         return tsubst_copy (t, args, complain, in_decl);
13253       /* Fall through */
13254       
13255     case ALIGNOF_EXPR:
13256       op1 = TREE_OPERAND (t, 0);
13257       if (!args)
13258         {
13259           /* When there are no ARGS, we are trying to evaluate a
13260              non-dependent expression from the parser.  Trying to do
13261              the substitutions may not work.  */
13262           if (!TYPE_P (op1))
13263             op1 = TREE_TYPE (op1);
13264         }
13265       else
13266         {
13267           ++cp_unevaluated_operand;
13268           ++c_inhibit_evaluation_warnings;
13269           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13270                                        /*function_p=*/false,
13271                                        /*integral_constant_expression_p=*/false);
13272           --cp_unevaluated_operand;
13273           --c_inhibit_evaluation_warnings;
13274         }
13275       if (TYPE_P (op1))
13276         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13277                                            complain & tf_error);
13278       else
13279         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13280                                            complain & tf_error);
13281
13282     case AT_ENCODE_EXPR:
13283       {
13284         op1 = TREE_OPERAND (t, 0);
13285         ++cp_unevaluated_operand;
13286         ++c_inhibit_evaluation_warnings;
13287         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13288                                      /*function_p=*/false,
13289                                      /*integral_constant_expression_p=*/false);
13290         --cp_unevaluated_operand;
13291         --c_inhibit_evaluation_warnings;
13292         return objc_build_encode_expr (op1);
13293       }
13294
13295     case NOEXCEPT_EXPR:
13296       op1 = TREE_OPERAND (t, 0);
13297       ++cp_unevaluated_operand;
13298       ++c_inhibit_evaluation_warnings;
13299       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13300                                    /*function_p=*/false,
13301                                    /*integral_constant_expression_p=*/false);
13302       --cp_unevaluated_operand;
13303       --c_inhibit_evaluation_warnings;
13304       return finish_noexcept_expr (op1, complain);
13305
13306     case MODOP_EXPR:
13307       {
13308         tree r = build_x_modify_expr
13309           (RECUR (TREE_OPERAND (t, 0)),
13310            TREE_CODE (TREE_OPERAND (t, 1)),
13311            RECUR (TREE_OPERAND (t, 2)),
13312            complain);
13313         /* TREE_NO_WARNING must be set if either the expression was
13314            parenthesized or it uses an operator such as >>= rather
13315            than plain assignment.  In the former case, it was already
13316            set and must be copied.  In the latter case,
13317            build_x_modify_expr sets it and it must not be reset
13318            here.  */
13319         if (TREE_NO_WARNING (t))
13320           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13321         return r;
13322       }
13323
13324     case ARROW_EXPR:
13325       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13326                                                 args, complain, in_decl);
13327       /* Remember that there was a reference to this entity.  */
13328       if (DECL_P (op1))
13329         mark_used (op1);
13330       return build_x_arrow (op1);
13331
13332     case NEW_EXPR:
13333       {
13334         tree placement = RECUR (TREE_OPERAND (t, 0));
13335         tree init = RECUR (TREE_OPERAND (t, 3));
13336         VEC(tree,gc) *placement_vec;
13337         VEC(tree,gc) *init_vec;
13338         tree ret;
13339
13340         if (placement == NULL_TREE)
13341           placement_vec = NULL;
13342         else
13343           {
13344             placement_vec = make_tree_vector ();
13345             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13346               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13347           }
13348
13349         /* If there was an initializer in the original tree, but it
13350            instantiated to an empty list, then we should pass a
13351            non-NULL empty vector to tell build_new that it was an
13352            empty initializer() rather than no initializer.  This can
13353            only happen when the initializer is a pack expansion whose
13354            parameter packs are of length zero.  */
13355         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13356           init_vec = NULL;
13357         else
13358           {
13359             init_vec = make_tree_vector ();
13360             if (init == void_zero_node)
13361               gcc_assert (init_vec != NULL);
13362             else
13363               {
13364                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13365                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13366               }
13367           }
13368
13369         ret = build_new (&placement_vec,
13370                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13371                          RECUR (TREE_OPERAND (t, 2)),
13372                          &init_vec,
13373                          NEW_EXPR_USE_GLOBAL (t),
13374                          complain);
13375
13376         if (placement_vec != NULL)
13377           release_tree_vector (placement_vec);
13378         if (init_vec != NULL)
13379           release_tree_vector (init_vec);
13380
13381         return ret;
13382       }
13383
13384     case DELETE_EXPR:
13385      return delete_sanity
13386        (RECUR (TREE_OPERAND (t, 0)),
13387         RECUR (TREE_OPERAND (t, 1)),
13388         DELETE_EXPR_USE_VEC (t),
13389         DELETE_EXPR_USE_GLOBAL (t),
13390         complain);
13391
13392     case COMPOUND_EXPR:
13393       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13394                                     RECUR (TREE_OPERAND (t, 1)),
13395                                     complain);
13396
13397     case CALL_EXPR:
13398       {
13399         tree function;
13400         VEC(tree,gc) *call_args;
13401         unsigned int nargs, i;
13402         bool qualified_p;
13403         bool koenig_p;
13404         tree ret;
13405
13406         function = CALL_EXPR_FN (t);
13407         /* When we parsed the expression,  we determined whether or
13408            not Koenig lookup should be performed.  */
13409         koenig_p = KOENIG_LOOKUP_P (t);
13410         if (TREE_CODE (function) == SCOPE_REF)
13411           {
13412             qualified_p = true;
13413             function = tsubst_qualified_id (function, args, complain, in_decl,
13414                                             /*done=*/false,
13415                                             /*address_p=*/false);
13416           }
13417         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13418           {
13419             /* Do nothing; calling tsubst_copy_and_build on an identifier
13420                would incorrectly perform unqualified lookup again.
13421
13422                Note that we can also have an IDENTIFIER_NODE if the earlier
13423                unqualified lookup found a member function; in that case
13424                koenig_p will be false and we do want to do the lookup
13425                again to find the instantiated member function.
13426
13427                FIXME but doing that causes c++/15272, so we need to stop
13428                using IDENTIFIER_NODE in that situation.  */
13429             qualified_p = false;
13430           }
13431         else
13432           {
13433             if (TREE_CODE (function) == COMPONENT_REF)
13434               {
13435                 tree op = TREE_OPERAND (function, 1);
13436
13437                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13438                                || (BASELINK_P (op)
13439                                    && BASELINK_QUALIFIED_P (op)));
13440               }
13441             else
13442               qualified_p = false;
13443
13444             function = tsubst_copy_and_build (function, args, complain,
13445                                               in_decl,
13446                                               !qualified_p,
13447                                               integral_constant_expression_p);
13448
13449             if (BASELINK_P (function))
13450               qualified_p = true;
13451           }
13452
13453         nargs = call_expr_nargs (t);
13454         call_args = make_tree_vector ();
13455         for (i = 0; i < nargs; ++i)
13456           {
13457             tree arg = CALL_EXPR_ARG (t, i);
13458
13459             if (!PACK_EXPANSION_P (arg))
13460               VEC_safe_push (tree, gc, call_args,
13461                              RECUR (CALL_EXPR_ARG (t, i)));
13462             else
13463               {
13464                 /* Expand the pack expansion and push each entry onto
13465                    CALL_ARGS.  */
13466                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13467                 if (TREE_CODE (arg) == TREE_VEC)
13468                   {
13469                     unsigned int len, j;
13470
13471                     len = TREE_VEC_LENGTH (arg);
13472                     for (j = 0; j < len; ++j)
13473                       {
13474                         tree value = TREE_VEC_ELT (arg, j);
13475                         if (value != NULL_TREE)
13476                           value = convert_from_reference (value);
13477                         VEC_safe_push (tree, gc, call_args, value);
13478                       }
13479                   }
13480                 else
13481                   {
13482                     /* A partial substitution.  Add one entry.  */
13483                     VEC_safe_push (tree, gc, call_args, arg);
13484                   }
13485               }
13486           }
13487
13488         /* We do not perform argument-dependent lookup if normal
13489            lookup finds a non-function, in accordance with the
13490            expected resolution of DR 218.  */
13491         if (koenig_p
13492             && ((is_overloaded_fn (function)
13493                  /* If lookup found a member function, the Koenig lookup is
13494                     not appropriate, even if an unqualified-name was used
13495                     to denote the function.  */
13496                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13497                 || TREE_CODE (function) == IDENTIFIER_NODE)
13498             /* Only do this when substitution turns a dependent call
13499                into a non-dependent call.  */
13500             && type_dependent_expression_p_push (t)
13501             && !any_type_dependent_arguments_p (call_args))
13502           function = perform_koenig_lookup (function, call_args, false,
13503                                             tf_none);
13504
13505         if (TREE_CODE (function) == IDENTIFIER_NODE
13506             && !any_type_dependent_arguments_p (call_args))
13507           {
13508             if (koenig_p && (complain & tf_warning_or_error))
13509               {
13510                 /* For backwards compatibility and good diagnostics, try
13511                    the unqualified lookup again if we aren't in SFINAE
13512                    context.  */
13513                 tree unq = (tsubst_copy_and_build
13514                             (function, args, complain, in_decl, true,
13515                              integral_constant_expression_p));
13516                 if (unq == error_mark_node)
13517                   return error_mark_node;
13518
13519                 if (unq != function)
13520                   {
13521                     tree fn = unq;
13522                     if (TREE_CODE (fn) == COMPONENT_REF)
13523                       fn = TREE_OPERAND (fn, 1);
13524                     if (is_overloaded_fn (fn))
13525                       fn = get_first_fn (fn);
13526                     permerror (EXPR_LOC_OR_HERE (t),
13527                                "%qD was not declared in this scope, "
13528                                "and no declarations were found by "
13529                                "argument-dependent lookup at the point "
13530                                "of instantiation", function);
13531                     if (DECL_CLASS_SCOPE_P (fn))
13532                       {
13533                         inform (EXPR_LOC_OR_HERE (t),
13534                                 "declarations in dependent base %qT are "
13535                                 "not found by unqualified lookup",
13536                                 DECL_CLASS_CONTEXT (fn));
13537                         if (current_class_ptr)
13538                           inform (EXPR_LOC_OR_HERE (t),
13539                                   "use %<this->%D%> instead", function);
13540                         else
13541                           inform (EXPR_LOC_OR_HERE (t),
13542                                   "use %<%T::%D%> instead",
13543                                   current_class_name, function);
13544                       }
13545                     else
13546                       inform (0, "%q+D declared here, later in the "
13547                                 "translation unit", fn);
13548                     function = unq;
13549                   }
13550               }
13551             if (TREE_CODE (function) == IDENTIFIER_NODE)
13552               {
13553                 unqualified_name_lookup_error (function);
13554                 release_tree_vector (call_args);
13555                 return error_mark_node;
13556               }
13557           }
13558
13559         /* Remember that there was a reference to this entity.  */
13560         if (DECL_P (function))
13561           mark_used (function);
13562
13563         if (TREE_CODE (function) == OFFSET_REF)
13564           ret = build_offset_ref_call_from_tree (function, &call_args);
13565         else if (TREE_CODE (function) == COMPONENT_REF)
13566           {
13567             tree instance = TREE_OPERAND (function, 0);
13568             tree fn = TREE_OPERAND (function, 1);
13569
13570             if (processing_template_decl
13571                 && (type_dependent_expression_p (instance)
13572                     || (!BASELINK_P (fn)
13573                         && TREE_CODE (fn) != FIELD_DECL)
13574                     || type_dependent_expression_p (fn)
13575                     || any_type_dependent_arguments_p (call_args)))
13576               ret = build_nt_call_vec (function, call_args);
13577             else if (!BASELINK_P (fn))
13578               ret = finish_call_expr (function, &call_args,
13579                                        /*disallow_virtual=*/false,
13580                                        /*koenig_p=*/false,
13581                                        complain);
13582             else
13583               ret = (build_new_method_call
13584                       (instance, fn,
13585                        &call_args, NULL_TREE,
13586                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13587                        /*fn_p=*/NULL,
13588                        complain));
13589           }
13590         else
13591           ret = finish_call_expr (function, &call_args,
13592                                   /*disallow_virtual=*/qualified_p,
13593                                   koenig_p,
13594                                   complain);
13595
13596         release_tree_vector (call_args);
13597
13598         return ret;
13599       }
13600
13601     case COND_EXPR:
13602       return build_x_conditional_expr
13603         (RECUR (TREE_OPERAND (t, 0)),
13604          RECUR (TREE_OPERAND (t, 1)),
13605          RECUR (TREE_OPERAND (t, 2)),
13606          complain);
13607
13608     case PSEUDO_DTOR_EXPR:
13609       return finish_pseudo_destructor_expr
13610         (RECUR (TREE_OPERAND (t, 0)),
13611          RECUR (TREE_OPERAND (t, 1)),
13612          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13613
13614     case TREE_LIST:
13615       {
13616         tree purpose, value, chain;
13617
13618         if (t == void_list_node)
13619           return t;
13620
13621         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13622             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13623           {
13624             /* We have pack expansions, so expand those and
13625                create a new list out of it.  */
13626             tree purposevec = NULL_TREE;
13627             tree valuevec = NULL_TREE;
13628             tree chain;
13629             int i, len = -1;
13630
13631             /* Expand the argument expressions.  */
13632             if (TREE_PURPOSE (t))
13633               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13634                                                  complain, in_decl);
13635             if (TREE_VALUE (t))
13636               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13637                                                complain, in_decl);
13638
13639             /* Build the rest of the list.  */
13640             chain = TREE_CHAIN (t);
13641             if (chain && chain != void_type_node)
13642               chain = RECUR (chain);
13643
13644             /* Determine the number of arguments.  */
13645             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13646               {
13647                 len = TREE_VEC_LENGTH (purposevec);
13648                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13649               }
13650             else if (TREE_CODE (valuevec) == TREE_VEC)
13651               len = TREE_VEC_LENGTH (valuevec);
13652             else
13653               {
13654                 /* Since we only performed a partial substitution into
13655                    the argument pack, we only return a single list
13656                    node.  */
13657                 if (purposevec == TREE_PURPOSE (t)
13658                     && valuevec == TREE_VALUE (t)
13659                     && chain == TREE_CHAIN (t))
13660                   return t;
13661
13662                 return tree_cons (purposevec, valuevec, chain);
13663               }
13664             
13665             /* Convert the argument vectors into a TREE_LIST */
13666             i = len;
13667             while (i > 0)
13668               {
13669                 /* Grab the Ith values.  */
13670                 i--;
13671                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13672                                      : NULL_TREE;
13673                 value 
13674                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13675                              : NULL_TREE;
13676
13677                 /* Build the list (backwards).  */
13678                 chain = tree_cons (purpose, value, chain);
13679               }
13680
13681             return chain;
13682           }
13683
13684         purpose = TREE_PURPOSE (t);
13685         if (purpose)
13686           purpose = RECUR (purpose);
13687         value = TREE_VALUE (t);
13688         if (value)
13689           value = RECUR (value);
13690         chain = TREE_CHAIN (t);
13691         if (chain && chain != void_type_node)
13692           chain = RECUR (chain);
13693         if (purpose == TREE_PURPOSE (t)
13694             && value == TREE_VALUE (t)
13695             && chain == TREE_CHAIN (t))
13696           return t;
13697         return tree_cons (purpose, value, chain);
13698       }
13699
13700     case COMPONENT_REF:
13701       {
13702         tree object;
13703         tree object_type;
13704         tree member;
13705
13706         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13707                                                      args, complain, in_decl);
13708         /* Remember that there was a reference to this entity.  */
13709         if (DECL_P (object))
13710           mark_used (object);
13711         object_type = TREE_TYPE (object);
13712
13713         member = TREE_OPERAND (t, 1);
13714         if (BASELINK_P (member))
13715           member = tsubst_baselink (member,
13716                                     non_reference (TREE_TYPE (object)),
13717                                     args, complain, in_decl);
13718         else
13719           member = tsubst_copy (member, args, complain, in_decl);
13720         if (member == error_mark_node)
13721           return error_mark_node;
13722
13723         if (object_type && !CLASS_TYPE_P (object_type))
13724           {
13725             if (SCALAR_TYPE_P (object_type))
13726               {
13727                 tree s = NULL_TREE;
13728                 tree dtor = member;
13729
13730                 if (TREE_CODE (dtor) == SCOPE_REF)
13731                   {
13732                     s = TREE_OPERAND (dtor, 0);
13733                     dtor = TREE_OPERAND (dtor, 1);
13734                   }
13735                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13736                   {
13737                     dtor = TREE_OPERAND (dtor, 0);
13738                     if (TYPE_P (dtor))
13739                       return finish_pseudo_destructor_expr (object, s, dtor);
13740                   }
13741               }
13742           }
13743         else if (TREE_CODE (member) == SCOPE_REF
13744                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13745           {
13746             tree tmpl;
13747             tree args;
13748
13749             /* Lookup the template functions now that we know what the
13750                scope is.  */
13751             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13752             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13753             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13754                                             /*is_type_p=*/false,
13755                                             /*complain=*/false);
13756             if (BASELINK_P (member))
13757               {
13758                 BASELINK_FUNCTIONS (member)
13759                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13760                               args);
13761                 member = (adjust_result_of_qualified_name_lookup
13762                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13763                            object_type));
13764               }
13765             else
13766               {
13767                 qualified_name_lookup_error (object_type, tmpl, member,
13768                                              input_location);
13769                 return error_mark_node;
13770               }
13771           }
13772         else if (TREE_CODE (member) == SCOPE_REF
13773                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13774                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13775           {
13776             if (complain & tf_error)
13777               {
13778                 if (TYPE_P (TREE_OPERAND (member, 0)))
13779                   error ("%qT is not a class or namespace",
13780                          TREE_OPERAND (member, 0));
13781                 else
13782                   error ("%qD is not a class or namespace",
13783                          TREE_OPERAND (member, 0));
13784               }
13785             return error_mark_node;
13786           }
13787         else if (TREE_CODE (member) == FIELD_DECL)
13788           return finish_non_static_data_member (member, object, NULL_TREE);
13789
13790         return finish_class_member_access_expr (object, member,
13791                                                 /*template_p=*/false,
13792                                                 complain);
13793       }
13794
13795     case THROW_EXPR:
13796       return build_throw
13797         (RECUR (TREE_OPERAND (t, 0)));
13798
13799     case CONSTRUCTOR:
13800       {
13801         VEC(constructor_elt,gc) *n;
13802         constructor_elt *ce;
13803         unsigned HOST_WIDE_INT idx;
13804         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13805         bool process_index_p;
13806         int newlen;
13807         bool need_copy_p = false;
13808         tree r;
13809
13810         if (type == error_mark_node)
13811           return error_mark_node;
13812
13813         /* digest_init will do the wrong thing if we let it.  */
13814         if (type && TYPE_PTRMEMFUNC_P (type))
13815           return t;
13816
13817         /* We do not want to process the index of aggregate
13818            initializers as they are identifier nodes which will be
13819            looked up by digest_init.  */
13820         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13821
13822         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13823         newlen = VEC_length (constructor_elt, n);
13824         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13825           {
13826             if (ce->index && process_index_p)
13827               ce->index = RECUR (ce->index);
13828
13829             if (PACK_EXPANSION_P (ce->value))
13830               {
13831                 /* Substitute into the pack expansion.  */
13832                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13833                                                   in_decl);
13834
13835                 if (ce->value == error_mark_node
13836                     || PACK_EXPANSION_P (ce->value))
13837                   ;
13838                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13839                   /* Just move the argument into place.  */
13840                   ce->value = TREE_VEC_ELT (ce->value, 0);
13841                 else
13842                   {
13843                     /* Update the length of the final CONSTRUCTOR
13844                        arguments vector, and note that we will need to
13845                        copy.*/
13846                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13847                     need_copy_p = true;
13848                   }
13849               }
13850             else
13851               ce->value = RECUR (ce->value);
13852           }
13853
13854         if (need_copy_p)
13855           {
13856             VEC(constructor_elt,gc) *old_n = n;
13857
13858             n = VEC_alloc (constructor_elt, gc, newlen);
13859             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13860               {
13861                 if (TREE_CODE (ce->value) == TREE_VEC)
13862                   {
13863                     int i, len = TREE_VEC_LENGTH (ce->value);
13864                     for (i = 0; i < len; ++i)
13865                       CONSTRUCTOR_APPEND_ELT (n, 0,
13866                                               TREE_VEC_ELT (ce->value, i));
13867                   }
13868                 else
13869                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13870               }
13871           }
13872
13873         r = build_constructor (init_list_type_node, n);
13874         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13875
13876         if (TREE_HAS_CONSTRUCTOR (t))
13877           return finish_compound_literal (type, r, complain);
13878
13879         TREE_TYPE (r) = type;
13880         return r;
13881       }
13882
13883     case TYPEID_EXPR:
13884       {
13885         tree operand_0 = TREE_OPERAND (t, 0);
13886         if (TYPE_P (operand_0))
13887           {
13888             operand_0 = tsubst (operand_0, args, complain, in_decl);
13889             return get_typeid (operand_0);
13890           }
13891         else
13892           {
13893             operand_0 = RECUR (operand_0);
13894             return build_typeid (operand_0);
13895           }
13896       }
13897
13898     case VAR_DECL:
13899       if (!args)
13900         return t;
13901       /* Fall through */
13902
13903     case PARM_DECL:
13904       {
13905         tree r = tsubst_copy (t, args, complain, in_decl);
13906
13907         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13908           /* If the original type was a reference, we'll be wrapped in
13909              the appropriate INDIRECT_REF.  */
13910           r = convert_from_reference (r);
13911         return r;
13912       }
13913
13914     case VA_ARG_EXPR:
13915       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13916                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13917
13918     case OFFSETOF_EXPR:
13919       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13920
13921     case TRAIT_EXPR:
13922       {
13923         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13924                                   complain, in_decl);
13925
13926         tree type2 = TRAIT_EXPR_TYPE2 (t);
13927         if (type2)
13928           type2 = tsubst_copy (type2, args, complain, in_decl);
13929         
13930         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13931       }
13932
13933     case STMT_EXPR:
13934       {
13935         tree old_stmt_expr = cur_stmt_expr;
13936         tree stmt_expr = begin_stmt_expr ();
13937
13938         cur_stmt_expr = stmt_expr;
13939         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13940                      integral_constant_expression_p);
13941         stmt_expr = finish_stmt_expr (stmt_expr, false);
13942         cur_stmt_expr = old_stmt_expr;
13943
13944         /* If the resulting list of expression statement is empty,
13945            fold it further into void_zero_node.  */
13946         if (empty_expr_stmt_p (stmt_expr))
13947           stmt_expr = void_zero_node;
13948
13949         return stmt_expr;
13950       }
13951
13952     case CONST_DECL:
13953       t = tsubst_copy (t, args, complain, in_decl);
13954       /* As in finish_id_expression, we resolve enumeration constants
13955          to their underlying values.  */
13956       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
13957         {
13958           used_types_insert (TREE_TYPE (t));
13959           return DECL_INITIAL (t);
13960         }
13961       return t;
13962
13963     case LAMBDA_EXPR:
13964       {
13965         tree r = build_lambda_expr ();
13966
13967         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
13968         LAMBDA_EXPR_CLOSURE (r) = type;
13969         CLASSTYPE_LAMBDA_EXPR (type) = r;
13970
13971         LAMBDA_EXPR_LOCATION (r)
13972           = LAMBDA_EXPR_LOCATION (t);
13973         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13974           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13975         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13976         LAMBDA_EXPR_DISCRIMINATOR (r)
13977           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13978         LAMBDA_EXPR_EXTRA_SCOPE (r)
13979           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13980         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
13981           {
13982             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
13983             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
13984           }
13985         else
13986           LAMBDA_EXPR_RETURN_TYPE (r)
13987             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13988
13989         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13990                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13991
13992         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13993         determine_visibility (TYPE_NAME (type));
13994         /* Now that we know visibility, instantiate the type so we have a
13995            declaration of the op() for later calls to lambda_function.  */
13996         complete_type (type);
13997
13998         /* The capture list refers to closure members, so this needs to
13999            wait until after we finish instantiating the type.  */
14000         LAMBDA_EXPR_CAPTURE_LIST (r)
14001           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
14002
14003         return build_lambda_object (r);
14004       }
14005
14006     case TARGET_EXPR:
14007       /* We can get here for a constant initializer of non-dependent type.
14008          FIXME stop folding in cp_parser_initializer_clause.  */
14009       gcc_assert (TREE_CONSTANT (t));
14010       {
14011         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
14012         TREE_CONSTANT (r) = true;
14013         return r;
14014       }
14015
14016     default:
14017       /* Handle Objective-C++ constructs, if appropriate.  */
14018       {
14019         tree subst
14020           = objcp_tsubst_copy_and_build (t, args, complain,
14021                                          in_decl, /*function_p=*/false);
14022         if (subst)
14023           return subst;
14024       }
14025       return tsubst_copy (t, args, complain, in_decl);
14026     }
14027
14028 #undef RECUR
14029 }
14030
14031 /* Verify that the instantiated ARGS are valid. For type arguments,
14032    make sure that the type's linkage is ok. For non-type arguments,
14033    make sure they are constants if they are integral or enumerations.
14034    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14035
14036 static bool
14037 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14038 {
14039   if (ARGUMENT_PACK_P (t))
14040     {
14041       tree vec = ARGUMENT_PACK_ARGS (t);
14042       int len = TREE_VEC_LENGTH (vec);
14043       bool result = false;
14044       int i;
14045
14046       for (i = 0; i < len; ++i)
14047         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14048           result = true;
14049       return result;
14050     }
14051   else if (TYPE_P (t))
14052     {
14053       /* [basic.link]: A name with no linkage (notably, the name
14054          of a class or enumeration declared in a local scope)
14055          shall not be used to declare an entity with linkage.
14056          This implies that names with no linkage cannot be used as
14057          template arguments
14058
14059          DR 757 relaxes this restriction for C++0x.  */
14060       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14061                  : no_linkage_check (t, /*relaxed_p=*/false));
14062
14063       if (nt)
14064         {
14065           /* DR 488 makes use of a type with no linkage cause
14066              type deduction to fail.  */
14067           if (complain & tf_error)
14068             {
14069               if (TYPE_ANONYMOUS_P (nt))
14070                 error ("%qT is/uses anonymous type", t);
14071               else
14072                 error ("template argument for %qD uses local type %qT",
14073                        tmpl, t);
14074             }
14075           return true;
14076         }
14077       /* In order to avoid all sorts of complications, we do not
14078          allow variably-modified types as template arguments.  */
14079       else if (variably_modified_type_p (t, NULL_TREE))
14080         {
14081           if (complain & tf_error)
14082             error ("%qT is a variably modified type", t);
14083           return true;
14084         }
14085     }
14086   /* A non-type argument of integral or enumerated type must be a
14087      constant.  */
14088   else if (TREE_TYPE (t)
14089            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14090            && !TREE_CONSTANT (t))
14091     {
14092       if (complain & tf_error)
14093         error ("integral expression %qE is not constant", t);
14094       return true;
14095     }
14096   return false;
14097 }
14098
14099 static bool
14100 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14101 {
14102   int ix, len = DECL_NTPARMS (tmpl);
14103   bool result = false;
14104
14105   for (ix = 0; ix != len; ix++)
14106     {
14107       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14108         result = true;
14109     }
14110   if (result && (complain & tf_error))
14111     error ("  trying to instantiate %qD", tmpl);
14112   return result;
14113 }
14114
14115 /* In C++0x, it's possible to have a function template whose type depends
14116    on itself recursively.  This is most obvious with decltype, but can also
14117    occur with enumeration scope (c++/48969).  So we need to catch infinite
14118    recursion and reject the substitution at deduction time; this function
14119    will return error_mark_node for any repeated substitution.
14120
14121    This also catches excessive recursion such as when f<N> depends on
14122    f<N-1> across all integers, and returns error_mark_node for all the
14123    substitutions back up to the initial one.
14124
14125    This is, of course, not reentrant.  */
14126
14127 static tree
14128 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14129 {
14130   static bool excessive_deduction_depth;
14131   static int deduction_depth;
14132   struct pending_template *old_last_pend = last_pending_template;
14133   struct tinst_level *old_error_tinst = last_error_tinst_level;
14134
14135   tree fntype = TREE_TYPE (fn);
14136   tree tinst;
14137   tree r;
14138
14139   if (excessive_deduction_depth)
14140     return error_mark_node;
14141
14142   tinst = build_tree_list (fn, targs);
14143   if (!push_tinst_level (tinst))
14144     {
14145       excessive_deduction_depth = true;
14146       ggc_free (tinst);
14147       return error_mark_node;
14148     }
14149
14150   input_location = DECL_SOURCE_LOCATION (fn);
14151   ++deduction_depth;
14152   push_deduction_access_scope (fn);
14153   r = tsubst (fntype, targs, complain, NULL_TREE);
14154   pop_deduction_access_scope (fn);
14155   --deduction_depth;
14156
14157   if (excessive_deduction_depth)
14158     {
14159       r = error_mark_node;
14160       if (deduction_depth == 0)
14161         /* Reset once we're all the way out.  */
14162         excessive_deduction_depth = false;
14163     }
14164
14165   pop_tinst_level ();
14166   /* We can't free this if a pending_template entry or last_error_tinst_level
14167      is pointing at it.  */
14168   if (last_pending_template == old_last_pend
14169       && last_error_tinst_level == old_error_tinst)
14170     ggc_free (tinst);
14171   return r;
14172 }
14173
14174 /* Instantiate the indicated variable or function template TMPL with
14175    the template arguments in TARG_PTR.  */
14176
14177 static tree
14178 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14179 {
14180   tree targ_ptr = orig_args;
14181   tree fndecl;
14182   tree gen_tmpl;
14183   tree spec;
14184   HOST_WIDE_INT saved_processing_template_decl;
14185
14186   if (tmpl == error_mark_node)
14187     return error_mark_node;
14188
14189   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14190
14191   /* If this function is a clone, handle it specially.  */
14192   if (DECL_CLONED_FUNCTION_P (tmpl))
14193     {
14194       tree spec;
14195       tree clone;
14196
14197       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14198          DECL_CLONED_FUNCTION.  */
14199       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14200                                    targ_ptr, complain);
14201       if (spec == error_mark_node)
14202         return error_mark_node;
14203
14204       /* Look for the clone.  */
14205       FOR_EACH_CLONE (clone, spec)
14206         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14207           return clone;
14208       /* We should always have found the clone by now.  */
14209       gcc_unreachable ();
14210       return NULL_TREE;
14211     }
14212
14213   /* Check to see if we already have this specialization.  */
14214   gen_tmpl = most_general_template (tmpl);
14215   if (tmpl != gen_tmpl)
14216     /* The TMPL is a partial instantiation.  To get a full set of
14217        arguments we must add the arguments used to perform the
14218        partial instantiation.  */
14219     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14220                                             targ_ptr);
14221
14222   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14223      but it doesn't seem to be on the hot path.  */
14224   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14225
14226   gcc_assert (tmpl == gen_tmpl
14227               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14228                   == spec)
14229               || fndecl == NULL_TREE);
14230
14231   if (spec != NULL_TREE)
14232     return spec;
14233
14234   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14235                                complain))
14236     return error_mark_node;
14237
14238   /* We are building a FUNCTION_DECL, during which the access of its
14239      parameters and return types have to be checked.  However this
14240      FUNCTION_DECL which is the desired context for access checking
14241      is not built yet.  We solve this chicken-and-egg problem by
14242      deferring all checks until we have the FUNCTION_DECL.  */
14243   push_deferring_access_checks (dk_deferred);
14244
14245   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14246      (because, for example, we have encountered a non-dependent
14247      function call in the body of a template function and must now
14248      determine which of several overloaded functions will be called),
14249      within the instantiation itself we are not processing a
14250      template.  */  
14251   saved_processing_template_decl = processing_template_decl;
14252   processing_template_decl = 0;
14253   /* Substitute template parameters to obtain the specialization.  */
14254   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14255                    targ_ptr, complain, gen_tmpl);
14256   processing_template_decl = saved_processing_template_decl;
14257   if (fndecl == error_mark_node)
14258     return error_mark_node;
14259
14260   /* Now we know the specialization, compute access previously
14261      deferred.  */
14262   push_access_scope (fndecl);
14263
14264   /* Some typedefs referenced from within the template code need to be access
14265      checked at template instantiation time, i.e now. These types were
14266      added to the template at parsing time. Let's get those and perfom
14267      the acces checks then.  */
14268   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14269   perform_deferred_access_checks ();
14270   pop_access_scope (fndecl);
14271   pop_deferring_access_checks ();
14272
14273   /* The DECL_TI_TEMPLATE should always be the immediate parent
14274      template, not the most general template.  */
14275   DECL_TI_TEMPLATE (fndecl) = tmpl;
14276
14277   /* If we've just instantiated the main entry point for a function,
14278      instantiate all the alternate entry points as well.  We do this
14279      by cloning the instantiation of the main entry point, not by
14280      instantiating the template clones.  */
14281   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14282     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14283
14284   return fndecl;
14285 }
14286
14287 /* Wrapper for instantiate_template_1.  */
14288
14289 tree
14290 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14291 {
14292   tree ret;
14293   timevar_push (TV_TEMPLATE_INST);
14294   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14295   timevar_pop (TV_TEMPLATE_INST);
14296   return ret;
14297 }
14298
14299 /* We're going to do deduction substitution on the type of TMPL, a function
14300    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14301    disable access checking.  */
14302
14303 static void
14304 push_deduction_access_scope (tree tmpl)
14305 {
14306   if (cxx_dialect >= cxx0x)
14307     {
14308       int ptd = processing_template_decl;
14309       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14310       /* Preserve processing_template_decl across push_to_top_level.  */
14311       if (ptd && !processing_template_decl)
14312         ++processing_template_decl;
14313     }
14314   else
14315     push_deferring_access_checks (dk_no_check);
14316 }
14317
14318 /* And pop back out.  */
14319
14320 static void
14321 pop_deduction_access_scope (tree tmpl)
14322 {
14323   if (cxx_dialect >= cxx0x)
14324     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14325   else
14326     pop_deferring_access_checks ();
14327 }
14328
14329 /* PARM is a template parameter pack for FN.  Returns true iff
14330    PARM is used in a deducible way in the argument list of FN.  */
14331
14332 static bool
14333 pack_deducible_p (tree parm, tree fn)
14334 {
14335   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14336   for (; t; t = TREE_CHAIN (t))
14337     {
14338       tree type = TREE_VALUE (t);
14339       tree packs;
14340       if (!PACK_EXPANSION_P (type))
14341         continue;
14342       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14343            packs; packs = TREE_CHAIN (packs))
14344         if (TREE_VALUE (packs) == parm)
14345           {
14346             /* The template parameter pack is used in a function parameter
14347                pack.  If this is the end of the parameter list, the
14348                template parameter pack is deducible.  */
14349             if (TREE_CHAIN (t) == void_list_node)
14350               return true;
14351             else
14352               /* Otherwise, not.  Well, it could be deduced from
14353                  a non-pack parameter, but doing so would end up with
14354                  a deduction mismatch, so don't bother.  */
14355               return false;
14356           }
14357     }
14358   /* The template parameter pack isn't used in any function parameter
14359      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14360   return true;
14361 }
14362
14363 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14364    NARGS elements of the arguments that are being used when calling
14365    it.  TARGS is a vector into which the deduced template arguments
14366    are placed.
14367
14368    Return zero for success, 2 for an incomplete match that doesn't resolve
14369    all the types, and 1 for complete failure.  An error message will be
14370    printed only for an incomplete match.
14371
14372    If FN is a conversion operator, or we are trying to produce a specific
14373    specialization, RETURN_TYPE is the return type desired.
14374
14375    The EXPLICIT_TARGS are explicit template arguments provided via a
14376    template-id.
14377
14378    The parameter STRICT is one of:
14379
14380    DEDUCE_CALL:
14381      We are deducing arguments for a function call, as in
14382      [temp.deduct.call].
14383
14384    DEDUCE_CONV:
14385      We are deducing arguments for a conversion function, as in
14386      [temp.deduct.conv].
14387
14388    DEDUCE_EXACT:
14389      We are deducing arguments when doing an explicit instantiation
14390      as in [temp.explicit], when determining an explicit specialization
14391      as in [temp.expl.spec], or when taking the address of a function
14392      template, as in [temp.deduct.funcaddr].  */
14393
14394 int
14395 fn_type_unification (tree fn,
14396                      tree explicit_targs,
14397                      tree targs,
14398                      const tree *args,
14399                      unsigned int nargs,
14400                      tree return_type,
14401                      unification_kind_t strict,
14402                      int flags,
14403                      bool explain_p)
14404 {
14405   tree parms;
14406   tree fntype;
14407   int result;
14408
14409   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14410
14411   fntype = TREE_TYPE (fn);
14412   if (explicit_targs)
14413     {
14414       /* [temp.deduct]
14415
14416          The specified template arguments must match the template
14417          parameters in kind (i.e., type, nontype, template), and there
14418          must not be more arguments than there are parameters;
14419          otherwise type deduction fails.
14420
14421          Nontype arguments must match the types of the corresponding
14422          nontype template parameters, or must be convertible to the
14423          types of the corresponding nontype parameters as specified in
14424          _temp.arg.nontype_, otherwise type deduction fails.
14425
14426          All references in the function type of the function template
14427          to the corresponding template parameters are replaced by the
14428          specified template argument values.  If a substitution in a
14429          template parameter or in the function type of the function
14430          template results in an invalid type, type deduction fails.  */
14431       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14432       int i, len = TREE_VEC_LENGTH (tparms);
14433       tree converted_args;
14434       bool incomplete = false;
14435
14436       if (explicit_targs == error_mark_node)
14437         return unify_invalid (explain_p);
14438
14439       converted_args
14440         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14441                                   (explain_p
14442                                    ? tf_warning_or_error
14443                                    : tf_none),
14444                                    /*require_all_args=*/false,
14445                                    /*use_default_args=*/false));
14446       if (converted_args == error_mark_node)
14447         return 1;
14448
14449       /* Substitute the explicit args into the function type.  This is
14450          necessary so that, for instance, explicitly declared function
14451          arguments can match null pointed constants.  If we were given
14452          an incomplete set of explicit args, we must not do semantic
14453          processing during substitution as we could create partial
14454          instantiations.  */
14455       for (i = 0; i < len; i++)
14456         {
14457           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14458           bool parameter_pack = false;
14459           tree targ = TREE_VEC_ELT (converted_args, i);
14460
14461           /* Dig out the actual parm.  */
14462           if (TREE_CODE (parm) == TYPE_DECL
14463               || TREE_CODE (parm) == TEMPLATE_DECL)
14464             {
14465               parm = TREE_TYPE (parm);
14466               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14467             }
14468           else if (TREE_CODE (parm) == PARM_DECL)
14469             {
14470               parm = DECL_INITIAL (parm);
14471               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14472             }
14473
14474           if (!parameter_pack && targ == NULL_TREE)
14475             /* No explicit argument for this template parameter.  */
14476             incomplete = true;
14477
14478           if (parameter_pack && pack_deducible_p (parm, fn))
14479             {
14480               /* Mark the argument pack as "incomplete". We could
14481                  still deduce more arguments during unification.
14482                  We remove this mark in type_unification_real.  */
14483               if (targ)
14484                 {
14485                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14486                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14487                     = ARGUMENT_PACK_ARGS (targ);
14488                 }
14489
14490               /* We have some incomplete argument packs.  */
14491               incomplete = true;
14492             }
14493         }
14494
14495       processing_template_decl += incomplete;
14496       fntype = deduction_tsubst_fntype (fn, converted_args,
14497                                         (explain_p
14498                                          ? tf_warning_or_error
14499                                          : tf_none));
14500       processing_template_decl -= incomplete;
14501
14502       if (fntype == error_mark_node)
14503         return 1;
14504
14505       /* Place the explicitly specified arguments in TARGS.  */
14506       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14507         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14508     }
14509
14510   /* Never do unification on the 'this' parameter.  */
14511   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14512
14513   if (return_type)
14514     {
14515       tree *new_args;
14516
14517       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14518       new_args = XALLOCAVEC (tree, nargs + 1);
14519       new_args[0] = return_type;
14520       memcpy (new_args + 1, args, nargs * sizeof (tree));
14521       args = new_args;
14522       ++nargs;
14523     }
14524
14525   /* We allow incomplete unification without an error message here
14526      because the standard doesn't seem to explicitly prohibit it.  Our
14527      callers must be ready to deal with unification failures in any
14528      event.  */
14529   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14530                                   targs, parms, args, nargs, /*subr=*/0,
14531                                   strict, flags, explain_p);
14532
14533   /* Now that we have bindings for all of the template arguments,
14534      ensure that the arguments deduced for the template template
14535      parameters have compatible template parameter lists.  We cannot
14536      check this property before we have deduced all template
14537      arguments, because the template parameter types of a template
14538      template parameter might depend on prior template parameters
14539      deduced after the template template parameter.  The following
14540      ill-formed example illustrates this issue:
14541
14542        template<typename T, template<T> class C> void f(C<5>, T);
14543
14544        template<int N> struct X {};
14545
14546        void g() {
14547          f(X<5>(), 5l); // error: template argument deduction fails
14548        }
14549
14550      The template parameter list of 'C' depends on the template type
14551      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14552      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14553      time that we deduce 'C'.  */
14554   if (result == 0
14555       && !template_template_parm_bindings_ok_p 
14556            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14557     return unify_inconsistent_template_template_parameters (explain_p);
14558
14559   if (result == 0)
14560     /* All is well so far.  Now, check:
14561
14562        [temp.deduct]
14563
14564        When all template arguments have been deduced, all uses of
14565        template parameters in nondeduced contexts are replaced with
14566        the corresponding deduced argument values.  If the
14567        substitution results in an invalid type, as described above,
14568        type deduction fails.  */
14569     {
14570       tree substed = deduction_tsubst_fntype (fn, targs,
14571                                               (explain_p
14572                                                ? tf_warning_or_error
14573                                                : tf_none));
14574       if (substed == error_mark_node)
14575         return 1;
14576
14577       /* If we're looking for an exact match, check that what we got
14578          is indeed an exact match.  It might not be if some template
14579          parameters are used in non-deduced contexts.  */
14580       if (strict == DEDUCE_EXACT)
14581         {
14582           unsigned int i;
14583
14584           tree sarg
14585             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14586           if (return_type)
14587             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14588           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14589             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14590               return unify_type_mismatch (explain_p, args[i],
14591                                           TREE_VALUE (sarg));
14592         }
14593     }
14594
14595   return result;
14596 }
14597
14598 /* Adjust types before performing type deduction, as described in
14599    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14600    sections are symmetric.  PARM is the type of a function parameter
14601    or the return type of the conversion function.  ARG is the type of
14602    the argument passed to the call, or the type of the value
14603    initialized with the result of the conversion function.
14604    ARG_EXPR is the original argument expression, which may be null.  */
14605
14606 static int
14607 maybe_adjust_types_for_deduction (unification_kind_t strict,
14608                                   tree* parm,
14609                                   tree* arg,
14610                                   tree arg_expr)
14611 {
14612   int result = 0;
14613
14614   switch (strict)
14615     {
14616     case DEDUCE_CALL:
14617       break;
14618
14619     case DEDUCE_CONV:
14620       {
14621         /* Swap PARM and ARG throughout the remainder of this
14622            function; the handling is precisely symmetric since PARM
14623            will initialize ARG rather than vice versa.  */
14624         tree* temp = parm;
14625         parm = arg;
14626         arg = temp;
14627         break;
14628       }
14629
14630     case DEDUCE_EXACT:
14631       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14632          too, but here handle it by stripping the reference from PARM
14633          rather than by adding it to ARG.  */
14634       if (TREE_CODE (*parm) == REFERENCE_TYPE
14635           && TYPE_REF_IS_RVALUE (*parm)
14636           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14637           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14638           && TREE_CODE (*arg) == REFERENCE_TYPE
14639           && !TYPE_REF_IS_RVALUE (*arg))
14640         *parm = TREE_TYPE (*parm);
14641       /* Nothing else to do in this case.  */
14642       return 0;
14643
14644     default:
14645       gcc_unreachable ();
14646     }
14647
14648   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14649     {
14650       /* [temp.deduct.call]
14651
14652          If P is not a reference type:
14653
14654          --If A is an array type, the pointer type produced by the
14655          array-to-pointer standard conversion (_conv.array_) is
14656          used in place of A for type deduction; otherwise,
14657
14658          --If A is a function type, the pointer type produced by
14659          the function-to-pointer standard conversion
14660          (_conv.func_) is used in place of A for type deduction;
14661          otherwise,
14662
14663          --If A is a cv-qualified type, the top level
14664          cv-qualifiers of A's type are ignored for type
14665          deduction.  */
14666       if (TREE_CODE (*arg) == ARRAY_TYPE)
14667         *arg = build_pointer_type (TREE_TYPE (*arg));
14668       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14669         *arg = build_pointer_type (*arg);
14670       else
14671         *arg = TYPE_MAIN_VARIANT (*arg);
14672     }
14673
14674   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14675      of the form T&&, where T is a template parameter, and the argument
14676      is an lvalue, T is deduced as A& */
14677   if (TREE_CODE (*parm) == REFERENCE_TYPE
14678       && TYPE_REF_IS_RVALUE (*parm)
14679       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14680       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14681       && (arg_expr ? real_lvalue_p (arg_expr)
14682           /* try_one_overload doesn't provide an arg_expr, but
14683              functions are always lvalues.  */
14684           : TREE_CODE (*arg) == FUNCTION_TYPE))
14685     *arg = build_reference_type (*arg);
14686
14687   /* [temp.deduct.call]
14688
14689      If P is a cv-qualified type, the top level cv-qualifiers
14690      of P's type are ignored for type deduction.  If P is a
14691      reference type, the type referred to by P is used for
14692      type deduction.  */
14693   *parm = TYPE_MAIN_VARIANT (*parm);
14694   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14695     {
14696       *parm = TREE_TYPE (*parm);
14697       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14698     }
14699
14700   /* DR 322. For conversion deduction, remove a reference type on parm
14701      too (which has been swapped into ARG).  */
14702   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14703     *arg = TREE_TYPE (*arg);
14704
14705   return result;
14706 }
14707
14708 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14709    template which does contain any deducible template parameters; check if
14710    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14711    unify_one_argument.  */
14712
14713 static int
14714 check_non_deducible_conversion (tree parm, tree arg, int strict,
14715                                 int flags, bool explain_p)
14716 {
14717   tree type;
14718
14719   if (!TYPE_P (arg))
14720     type = TREE_TYPE (arg);
14721   else
14722     type = arg;
14723
14724   if (same_type_p (parm, type))
14725     return unify_success (explain_p);
14726
14727   if (strict == DEDUCE_CONV)
14728     {
14729       if (can_convert_arg (type, parm, NULL_TREE, flags))
14730         return unify_success (explain_p);
14731     }
14732   else if (strict != DEDUCE_EXACT)
14733     {
14734       if (can_convert_arg (parm, type,
14735                            TYPE_P (arg) ? NULL_TREE : arg,
14736                            flags))
14737         return unify_success (explain_p);
14738     }
14739
14740   if (strict == DEDUCE_EXACT)
14741     return unify_type_mismatch (explain_p, parm, arg);
14742   else
14743     return unify_arg_conversion (explain_p, parm, type, arg);
14744 }
14745
14746 /* Subroutine of type_unification_real and unify_pack_expansion to
14747    handle unification of a single P/A pair.  Parameters are as
14748    for those functions.  */
14749
14750 static int
14751 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14752                     int subr, unification_kind_t strict, int flags,
14753                     bool explain_p)
14754 {
14755   tree arg_expr = NULL_TREE;
14756   int arg_strict;
14757
14758   if (arg == error_mark_node || parm == error_mark_node)
14759     return unify_invalid (explain_p);
14760   if (arg == unknown_type_node)
14761     /* We can't deduce anything from this, but we might get all the
14762        template args from other function args.  */
14763     return unify_success (explain_p);
14764
14765   /* FIXME uses_deducible_template_parms */
14766   if (TYPE_P (parm) && !uses_template_parms (parm))
14767     return check_non_deducible_conversion (parm, arg, strict, flags,
14768                                            explain_p);
14769
14770   switch (strict)
14771     {
14772     case DEDUCE_CALL:
14773       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14774                     | UNIFY_ALLOW_MORE_CV_QUAL
14775                     | UNIFY_ALLOW_DERIVED);
14776       break;
14777
14778     case DEDUCE_CONV:
14779       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14780       break;
14781
14782     case DEDUCE_EXACT:
14783       arg_strict = UNIFY_ALLOW_NONE;
14784       break;
14785
14786     default:
14787       gcc_unreachable ();
14788     }
14789
14790   /* We only do these transformations if this is the top-level
14791      parameter_type_list in a call or declaration matching; in other
14792      situations (nested function declarators, template argument lists) we
14793      won't be comparing a type to an expression, and we don't do any type
14794      adjustments.  */
14795   if (!subr)
14796     {
14797       if (!TYPE_P (arg))
14798         {
14799           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14800           if (type_unknown_p (arg))
14801             {
14802               /* [temp.deduct.type] A template-argument can be
14803                  deduced from a pointer to function or pointer
14804                  to member function argument if the set of
14805                  overloaded functions does not contain function
14806                  templates and at most one of a set of
14807                  overloaded functions provides a unique
14808                  match.  */
14809
14810               if (resolve_overloaded_unification
14811                   (tparms, targs, parm, arg, strict,
14812                    arg_strict, explain_p))
14813                 return unify_success (explain_p);
14814               return unify_overload_resolution_failure (explain_p, arg);
14815             }
14816
14817           arg_expr = arg;
14818           arg = unlowered_expr_type (arg);
14819           if (arg == error_mark_node)
14820             return unify_invalid (explain_p);
14821         }
14822
14823       arg_strict |=
14824         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
14825     }
14826   else
14827     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
14828                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
14829
14830   /* For deduction from an init-list we need the actual list.  */
14831   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14832     arg = arg_expr;
14833   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
14834 }
14835
14836 /* Most parms like fn_type_unification.
14837
14838    If SUBR is 1, we're being called recursively (to unify the
14839    arguments of a function or method parameter of a function
14840    template). */
14841
14842 static int
14843 type_unification_real (tree tparms,
14844                        tree targs,
14845                        tree xparms,
14846                        const tree *xargs,
14847                        unsigned int xnargs,
14848                        int subr,
14849                        unification_kind_t strict,
14850                        int flags,
14851                        bool explain_p)
14852 {
14853   tree parm, arg;
14854   int i;
14855   int ntparms = TREE_VEC_LENGTH (tparms);
14856   int saw_undeduced = 0;
14857   tree parms;
14858   const tree *args;
14859   unsigned int nargs;
14860   unsigned int ia;
14861
14862   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14863   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14864   gcc_assert (ntparms > 0);
14865
14866   /* Reset the number of non-defaulted template arguments contained
14867      in TARGS.  */
14868   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14869
14870  again:
14871   parms = xparms;
14872   args = xargs;
14873   nargs = xnargs;
14874
14875   ia = 0;
14876   while (parms && parms != void_list_node
14877          && ia < nargs)
14878     {
14879       parm = TREE_VALUE (parms);
14880
14881       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14882           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14883         /* For a function parameter pack that occurs at the end of the
14884            parameter-declaration-list, the type A of each remaining
14885            argument of the call is compared with the type P of the
14886            declarator-id of the function parameter pack.  */
14887         break;
14888
14889       parms = TREE_CHAIN (parms);
14890
14891       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14892         /* For a function parameter pack that does not occur at the
14893            end of the parameter-declaration-list, the type of the
14894            parameter pack is a non-deduced context.  */
14895         continue;
14896
14897       arg = args[ia];
14898       ++ia;
14899
14900       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
14901                               flags, explain_p))
14902         return 1;
14903     }
14904
14905   if (parms 
14906       && parms != void_list_node
14907       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14908     {
14909       /* Unify the remaining arguments with the pack expansion type.  */
14910       tree argvec;
14911       tree parmvec = make_tree_vec (1);
14912
14913       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14914       argvec = make_tree_vec (nargs - ia);
14915       for (i = 0; ia < nargs; ++ia, ++i)
14916         TREE_VEC_ELT (argvec, i) = args[ia];
14917
14918       /* Copy the parameter into parmvec.  */
14919       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14920       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14921                                 /*subr=*/subr, explain_p))
14922         return 1;
14923
14924       /* Advance to the end of the list of parameters.  */
14925       parms = TREE_CHAIN (parms);
14926     }
14927
14928   /* Fail if we've reached the end of the parm list, and more args
14929      are present, and the parm list isn't variadic.  */
14930   if (ia < nargs && parms == void_list_node)
14931     return unify_too_many_arguments (explain_p, nargs, ia);
14932   /* Fail if parms are left and they don't have default values.  */
14933   if (parms && parms != void_list_node
14934       && TREE_PURPOSE (parms) == NULL_TREE)
14935     {
14936       unsigned int count = nargs;
14937       tree p = parms;
14938       while (p && p != void_list_node)
14939         {
14940           count++;
14941           p = TREE_CHAIN (p);
14942         }
14943       return unify_too_few_arguments (explain_p, ia, count);
14944     }
14945
14946   if (!subr)
14947     {
14948       tsubst_flags_t complain = (explain_p
14949                                  ? tf_warning_or_error
14950                                  : tf_none);
14951
14952       /* Check to see if we need another pass before we start clearing
14953          ARGUMENT_PACK_INCOMPLETE_P.  */
14954       for (i = 0; i < ntparms; i++)
14955         {
14956           tree targ = TREE_VEC_ELT (targs, i);
14957           tree tparm = TREE_VEC_ELT (tparms, i);
14958
14959           if (targ || tparm == error_mark_node)
14960             continue;
14961           tparm = TREE_VALUE (tparm);
14962
14963           /* If this is an undeduced nontype parameter that depends on
14964              a type parameter, try another pass; its type may have been
14965              deduced from a later argument than the one from which
14966              this parameter can be deduced.  */
14967           if (TREE_CODE (tparm) == PARM_DECL
14968               && uses_template_parms (TREE_TYPE (tparm))
14969               && !saw_undeduced++)
14970             goto again;
14971         }
14972
14973       for (i = 0; i < ntparms; i++)
14974         {
14975           tree targ = TREE_VEC_ELT (targs, i);
14976           tree tparm = TREE_VEC_ELT (tparms, i);
14977
14978           /* Clear the "incomplete" flags on all argument packs now so that
14979              substituting them into later default arguments works.  */
14980           if (targ && ARGUMENT_PACK_P (targ))
14981             {
14982               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14983               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14984             }
14985
14986           if (targ || tparm == error_mark_node)
14987             continue;
14988           tparm = TREE_VALUE (tparm);
14989
14990           /* Core issue #226 (C++0x) [temp.deduct]:
14991
14992              If a template argument has not been deduced, its
14993              default template argument, if any, is used. 
14994
14995              When we are in C++98 mode, TREE_PURPOSE will either
14996              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14997              to explicitly check cxx_dialect here.  */
14998           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14999             {
15000               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
15001               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
15002               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
15003               arg = convert_template_argument (parm, arg, targs, complain,
15004                                                i, NULL_TREE);
15005               if (arg == error_mark_node)
15006                 return 1;
15007               else
15008                 {
15009                   TREE_VEC_ELT (targs, i) = arg;
15010                   /* The position of the first default template argument,
15011                      is also the number of non-defaulted arguments in TARGS.
15012                      Record that.  */
15013                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15014                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
15015                   continue;
15016                 }
15017             }
15018
15019           /* If the type parameter is a parameter pack, then it will
15020              be deduced to an empty parameter pack.  */
15021           if (template_parameter_pack_p (tparm))
15022             {
15023               tree arg;
15024
15025               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15026                 {
15027                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15028                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15029                   TREE_CONSTANT (arg) = 1;
15030                 }
15031               else
15032                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15033
15034               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15035
15036               TREE_VEC_ELT (targs, i) = arg;
15037               continue;
15038             }
15039
15040           return unify_parameter_deduction_failure (explain_p, tparm);
15041         }
15042     }
15043 #ifdef ENABLE_CHECKING
15044   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15045     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15046 #endif
15047
15048   return unify_success (explain_p);
15049 }
15050
15051 /* Subroutine of type_unification_real.  Args are like the variables
15052    at the call site.  ARG is an overloaded function (or template-id);
15053    we try deducing template args from each of the overloads, and if
15054    only one succeeds, we go with that.  Modifies TARGS and returns
15055    true on success.  */
15056
15057 static bool
15058 resolve_overloaded_unification (tree tparms,
15059                                 tree targs,
15060                                 tree parm,
15061                                 tree arg,
15062                                 unification_kind_t strict,
15063                                 int sub_strict,
15064                                 bool explain_p)
15065 {
15066   tree tempargs = copy_node (targs);
15067   int good = 0;
15068   tree goodfn = NULL_TREE;
15069   bool addr_p;
15070
15071   if (TREE_CODE (arg) == ADDR_EXPR)
15072     {
15073       arg = TREE_OPERAND (arg, 0);
15074       addr_p = true;
15075     }
15076   else
15077     addr_p = false;
15078
15079   if (TREE_CODE (arg) == COMPONENT_REF)
15080     /* Handle `&x' where `x' is some static or non-static member
15081        function name.  */
15082     arg = TREE_OPERAND (arg, 1);
15083
15084   if (TREE_CODE (arg) == OFFSET_REF)
15085     arg = TREE_OPERAND (arg, 1);
15086
15087   /* Strip baselink information.  */
15088   if (BASELINK_P (arg))
15089     arg = BASELINK_FUNCTIONS (arg);
15090
15091   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15092     {
15093       /* If we got some explicit template args, we need to plug them into
15094          the affected templates before we try to unify, in case the
15095          explicit args will completely resolve the templates in question.  */
15096
15097       int ok = 0;
15098       tree expl_subargs = TREE_OPERAND (arg, 1);
15099       arg = TREE_OPERAND (arg, 0);
15100
15101       for (; arg; arg = OVL_NEXT (arg))
15102         {
15103           tree fn = OVL_CURRENT (arg);
15104           tree subargs, elem;
15105
15106           if (TREE_CODE (fn) != TEMPLATE_DECL)
15107             continue;
15108
15109           ++processing_template_decl;
15110           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15111                                   expl_subargs, /*check_ret=*/false);
15112           if (subargs && !any_dependent_template_arguments_p (subargs))
15113             {
15114               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15115               if (try_one_overload (tparms, targs, tempargs, parm,
15116                                     elem, strict, sub_strict, addr_p, explain_p)
15117                   && (!goodfn || !decls_match (goodfn, elem)))
15118                 {
15119                   goodfn = elem;
15120                   ++good;
15121                 }
15122             }
15123           else if (subargs)
15124             ++ok;
15125           --processing_template_decl;
15126         }
15127       /* If no templates (or more than one) are fully resolved by the
15128          explicit arguments, this template-id is a non-deduced context; it
15129          could still be OK if we deduce all template arguments for the
15130          enclosing call through other arguments.  */
15131       if (good != 1)
15132         good = ok;
15133     }
15134   else if (TREE_CODE (arg) != OVERLOAD
15135            && TREE_CODE (arg) != FUNCTION_DECL)
15136     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15137        -- but the deduction does not succeed because the expression is
15138        not just the function on its own.  */
15139     return false;
15140   else
15141     for (; arg; arg = OVL_NEXT (arg))
15142       if (try_one_overload (tparms, targs, tempargs, parm,
15143                             TREE_TYPE (OVL_CURRENT (arg)),
15144                             strict, sub_strict, addr_p, explain_p)
15145           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15146         {
15147           goodfn = OVL_CURRENT (arg);
15148           ++good;
15149         }
15150
15151   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15152      to function or pointer to member function argument if the set of
15153      overloaded functions does not contain function templates and at most
15154      one of a set of overloaded functions provides a unique match.
15155
15156      So if we found multiple possibilities, we return success but don't
15157      deduce anything.  */
15158
15159   if (good == 1)
15160     {
15161       int i = TREE_VEC_LENGTH (targs);
15162       for (; i--; )
15163         if (TREE_VEC_ELT (tempargs, i))
15164           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15165     }
15166   if (good)
15167     return true;
15168
15169   return false;
15170 }
15171
15172 /* Core DR 115: In contexts where deduction is done and fails, or in
15173    contexts where deduction is not done, if a template argument list is
15174    specified and it, along with any default template arguments, identifies
15175    a single function template specialization, then the template-id is an
15176    lvalue for the function template specialization.  */
15177
15178 tree
15179 resolve_nondeduced_context (tree orig_expr)
15180 {
15181   tree expr, offset, baselink;
15182   bool addr;
15183
15184   if (!type_unknown_p (orig_expr))
15185     return orig_expr;
15186
15187   expr = orig_expr;
15188   addr = false;
15189   offset = NULL_TREE;
15190   baselink = NULL_TREE;
15191
15192   if (TREE_CODE (expr) == ADDR_EXPR)
15193     {
15194       expr = TREE_OPERAND (expr, 0);
15195       addr = true;
15196     }
15197   if (TREE_CODE (expr) == OFFSET_REF)
15198     {
15199       offset = expr;
15200       expr = TREE_OPERAND (expr, 1);
15201     }
15202   if (BASELINK_P (expr))
15203     {
15204       baselink = expr;
15205       expr = BASELINK_FUNCTIONS (expr);
15206     }
15207
15208   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15209     {
15210       int good = 0;
15211       tree goodfn = NULL_TREE;
15212
15213       /* If we got some explicit template args, we need to plug them into
15214          the affected templates before we try to unify, in case the
15215          explicit args will completely resolve the templates in question.  */
15216
15217       tree expl_subargs = TREE_OPERAND (expr, 1);
15218       tree arg = TREE_OPERAND (expr, 0);
15219       tree badfn = NULL_TREE;
15220       tree badargs = NULL_TREE;
15221
15222       for (; arg; arg = OVL_NEXT (arg))
15223         {
15224           tree fn = OVL_CURRENT (arg);
15225           tree subargs, elem;
15226
15227           if (TREE_CODE (fn) != TEMPLATE_DECL)
15228             continue;
15229
15230           ++processing_template_decl;
15231           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15232                                   expl_subargs, /*check_ret=*/false);
15233           if (subargs && !any_dependent_template_arguments_p (subargs))
15234             {
15235               elem = instantiate_template (fn, subargs, tf_none);
15236               if (elem == error_mark_node)
15237                 {
15238                   badfn = fn;
15239                   badargs = subargs;
15240                 }
15241               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15242                 {
15243                   goodfn = elem;
15244                   ++good;
15245                 }
15246             }
15247           --processing_template_decl;
15248         }
15249       if (good == 1)
15250         {
15251           mark_used (goodfn);
15252           expr = goodfn;
15253           if (baselink)
15254             expr = build_baselink (BASELINK_BINFO (baselink),
15255                                    BASELINK_ACCESS_BINFO (baselink),
15256                                    expr, BASELINK_OPTYPE (baselink));
15257           if (offset)
15258             {
15259               tree base
15260                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15261               expr = build_offset_ref (base, expr, addr);
15262             }
15263           if (addr)
15264             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15265           return expr;
15266         }
15267       else if (good == 0 && badargs)
15268         /* There were no good options and at least one bad one, so let the
15269            user know what the problem is.  */
15270         instantiate_template (badfn, badargs, tf_warning_or_error);
15271     }
15272   return orig_expr;
15273 }
15274
15275 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15276    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15277    different overloads deduce different arguments for a given parm.
15278    ADDR_P is true if the expression for which deduction is being
15279    performed was of the form "& fn" rather than simply "fn".
15280
15281    Returns 1 on success.  */
15282
15283 static int
15284 try_one_overload (tree tparms,
15285                   tree orig_targs,
15286                   tree targs,
15287                   tree parm,
15288                   tree arg,
15289                   unification_kind_t strict,
15290                   int sub_strict,
15291                   bool addr_p,
15292                   bool explain_p)
15293 {
15294   int nargs;
15295   tree tempargs;
15296   int i;
15297
15298   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15299      to function or pointer to member function argument if the set of
15300      overloaded functions does not contain function templates and at most
15301      one of a set of overloaded functions provides a unique match.
15302
15303      So if this is a template, just return success.  */
15304
15305   if (uses_template_parms (arg))
15306     return 1;
15307
15308   if (TREE_CODE (arg) == METHOD_TYPE)
15309     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15310   else if (addr_p)
15311     arg = build_pointer_type (arg);
15312
15313   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15314
15315   /* We don't copy orig_targs for this because if we have already deduced
15316      some template args from previous args, unify would complain when we
15317      try to deduce a template parameter for the same argument, even though
15318      there isn't really a conflict.  */
15319   nargs = TREE_VEC_LENGTH (targs);
15320   tempargs = make_tree_vec (nargs);
15321
15322   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15323     return 0;
15324
15325   /* First make sure we didn't deduce anything that conflicts with
15326      explicitly specified args.  */
15327   for (i = nargs; i--; )
15328     {
15329       tree elt = TREE_VEC_ELT (tempargs, i);
15330       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15331
15332       if (!elt)
15333         /*NOP*/;
15334       else if (uses_template_parms (elt))
15335         /* Since we're unifying against ourselves, we will fill in
15336            template args used in the function parm list with our own
15337            template parms.  Discard them.  */
15338         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15339       else if (oldelt && !template_args_equal (oldelt, elt))
15340         return 0;
15341     }
15342
15343   for (i = nargs; i--; )
15344     {
15345       tree elt = TREE_VEC_ELT (tempargs, i);
15346
15347       if (elt)
15348         TREE_VEC_ELT (targs, i) = elt;
15349     }
15350
15351   return 1;
15352 }
15353
15354 /* PARM is a template class (perhaps with unbound template
15355    parameters).  ARG is a fully instantiated type.  If ARG can be
15356    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15357    TARGS are as for unify.  */
15358
15359 static tree
15360 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15361                        bool explain_p)
15362 {
15363   tree copy_of_targs;
15364
15365   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15366       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15367           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15368     return NULL_TREE;
15369
15370   /* We need to make a new template argument vector for the call to
15371      unify.  If we used TARGS, we'd clutter it up with the result of
15372      the attempted unification, even if this class didn't work out.
15373      We also don't want to commit ourselves to all the unifications
15374      we've already done, since unification is supposed to be done on
15375      an argument-by-argument basis.  In other words, consider the
15376      following pathological case:
15377
15378        template <int I, int J, int K>
15379        struct S {};
15380
15381        template <int I, int J>
15382        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15383
15384        template <int I, int J, int K>
15385        void f(S<I, J, K>, S<I, I, I>);
15386
15387        void g() {
15388          S<0, 0, 0> s0;
15389          S<0, 1, 2> s2;
15390
15391          f(s0, s2);
15392        }
15393
15394      Now, by the time we consider the unification involving `s2', we
15395      already know that we must have `f<0, 0, 0>'.  But, even though
15396      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15397      because there are two ways to unify base classes of S<0, 1, 2>
15398      with S<I, I, I>.  If we kept the already deduced knowledge, we
15399      would reject the possibility I=1.  */
15400   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15401
15402   /* If unification failed, we're done.  */
15403   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15404              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15405     return NULL_TREE;
15406
15407   return arg;
15408 }
15409
15410 /* Given a template type PARM and a class type ARG, find the unique
15411    base type in ARG that is an instance of PARM.  We do not examine
15412    ARG itself; only its base-classes.  If there is not exactly one
15413    appropriate base class, return NULL_TREE.  PARM may be the type of
15414    a partial specialization, as well as a plain template type.  Used
15415    by unify.  */
15416
15417 static enum template_base_result
15418 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15419                    bool explain_p, tree *result)
15420 {
15421   tree rval = NULL_TREE;
15422   tree binfo;
15423
15424   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15425
15426   binfo = TYPE_BINFO (complete_type (arg));
15427   if (!binfo)
15428     {
15429       /* The type could not be completed.  */
15430       *result = NULL_TREE;
15431       return tbr_incomplete_type;
15432     }
15433
15434   /* Walk in inheritance graph order.  The search order is not
15435      important, and this avoids multiple walks of virtual bases.  */
15436   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15437     {
15438       tree r = try_class_unification (tparms, targs, parm,
15439                                       BINFO_TYPE (binfo), explain_p);
15440
15441       if (r)
15442         {
15443           /* If there is more than one satisfactory baseclass, then:
15444
15445                [temp.deduct.call]
15446
15447               If they yield more than one possible deduced A, the type
15448               deduction fails.
15449
15450              applies.  */
15451           if (rval && !same_type_p (r, rval))
15452             {
15453               *result = NULL_TREE;
15454               return tbr_ambiguous_baseclass;
15455             }
15456
15457           rval = r;
15458         }
15459     }
15460
15461   *result = rval;
15462   return tbr_success;
15463 }
15464
15465 /* Returns the level of DECL, which declares a template parameter.  */
15466
15467 static int
15468 template_decl_level (tree decl)
15469 {
15470   switch (TREE_CODE (decl))
15471     {
15472     case TYPE_DECL:
15473     case TEMPLATE_DECL:
15474       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15475
15476     case PARM_DECL:
15477       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15478
15479     default:
15480       gcc_unreachable ();
15481     }
15482   return 0;
15483 }
15484
15485 /* Decide whether ARG can be unified with PARM, considering only the
15486    cv-qualifiers of each type, given STRICT as documented for unify.
15487    Returns nonzero iff the unification is OK on that basis.  */
15488
15489 static int
15490 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15491 {
15492   int arg_quals = cp_type_quals (arg);
15493   int parm_quals = cp_type_quals (parm);
15494
15495   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15496       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15497     {
15498       /*  Although a CVR qualifier is ignored when being applied to a
15499           substituted template parameter ([8.3.2]/1 for example), that
15500           does not allow us to unify "const T" with "int&" because both
15501           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15502           It is ok when we're allowing additional CV qualifiers
15503           at the outer level [14.8.2.1]/3,1st bullet.  */
15504       if ((TREE_CODE (arg) == REFERENCE_TYPE
15505            || TREE_CODE (arg) == FUNCTION_TYPE
15506            || TREE_CODE (arg) == METHOD_TYPE)
15507           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15508         return 0;
15509
15510       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15511           && (parm_quals & TYPE_QUAL_RESTRICT))
15512         return 0;
15513     }
15514
15515   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15516       && (arg_quals & parm_quals) != parm_quals)
15517     return 0;
15518
15519   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15520       && (parm_quals & arg_quals) != arg_quals)
15521     return 0;
15522
15523   return 1;
15524 }
15525
15526 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15527 void 
15528 template_parm_level_and_index (tree parm, int* level, int* index)
15529 {
15530   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15531       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15532       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15533     {
15534       *index = TEMPLATE_TYPE_IDX (parm);
15535       *level = TEMPLATE_TYPE_LEVEL (parm);
15536     }
15537   else
15538     {
15539       *index = TEMPLATE_PARM_IDX (parm);
15540       *level = TEMPLATE_PARM_LEVEL (parm);
15541     }
15542 }
15543
15544 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15545   do {                                                                  \
15546     if (unify (TP, TA, P, A, S, EP))                                    \
15547       return 1;                                                         \
15548   } while (0);
15549
15550 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15551    expansion at the end of PACKED_PARMS. Returns 0 if the type
15552    deduction succeeds, 1 otherwise. STRICT is the same as in
15553    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15554    call argument list. We'll need to adjust the arguments to make them
15555    types. SUBR tells us if this is from a recursive call to
15556    type_unification_real, or for comparing two template argument
15557    lists. */
15558
15559 static int
15560 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15561                       tree packed_args, unification_kind_t strict,
15562                       bool subr, bool explain_p)
15563 {
15564   tree parm 
15565     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15566   tree pattern = PACK_EXPANSION_PATTERN (parm);
15567   tree pack, packs = NULL_TREE;
15568   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15569   int len = TREE_VEC_LENGTH (packed_args);
15570
15571   /* Determine the parameter packs we will be deducing from the
15572      pattern, and record their current deductions.  */
15573   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15574        pack; pack = TREE_CHAIN (pack))
15575     {
15576       tree parm_pack = TREE_VALUE (pack);
15577       int idx, level;
15578
15579       /* Determine the index and level of this parameter pack.  */
15580       template_parm_level_and_index (parm_pack, &level, &idx);
15581
15582       /* Keep track of the parameter packs and their corresponding
15583          argument packs.  */
15584       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15585       TREE_TYPE (packs) = make_tree_vec (len - start);
15586     }
15587   
15588   /* Loop through all of the arguments that have not yet been
15589      unified and unify each with the pattern.  */
15590   for (i = start; i < len; i++)
15591     {
15592       tree parm;
15593       bool any_explicit = false;
15594       tree arg = TREE_VEC_ELT (packed_args, i);
15595
15596       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15597          or the element of its argument pack at the current index if
15598          this argument was explicitly specified.  */
15599       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15600         {
15601           int idx, level;
15602           tree arg, pargs;
15603           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15604
15605           arg = NULL_TREE;
15606           if (TREE_VALUE (pack)
15607               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15608               && (i < TREE_VEC_LENGTH (pargs)))
15609             {
15610               any_explicit = true;
15611               arg = TREE_VEC_ELT (pargs, i);
15612             }
15613           TMPL_ARG (targs, level, idx) = arg;
15614         }
15615
15616       /* If we had explicit template arguments, substitute them into the
15617          pattern before deduction.  */
15618       if (any_explicit)
15619         {
15620           /* Some arguments might still be unspecified or dependent.  */
15621           bool dependent;
15622           ++processing_template_decl;
15623           dependent = any_dependent_template_arguments_p (targs);
15624           if (!dependent)
15625             --processing_template_decl;
15626           parm = tsubst (pattern, targs,
15627                          explain_p ? tf_warning_or_error : tf_none,
15628                          NULL_TREE);
15629           if (dependent)
15630             --processing_template_decl;
15631           if (parm == error_mark_node)
15632             return 1;
15633         }
15634       else
15635         parm = pattern;
15636
15637       /* Unify the pattern with the current argument.  */
15638       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15639                               LOOKUP_IMPLICIT, explain_p))
15640         return 1;
15641
15642       /* For each parameter pack, collect the deduced value.  */
15643       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15644         {
15645           int idx, level;
15646           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15647
15648           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15649             TMPL_ARG (targs, level, idx);
15650         }
15651     }
15652
15653   /* Verify that the results of unification with the parameter packs
15654      produce results consistent with what we've seen before, and make
15655      the deduced argument packs available.  */
15656   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15657     {
15658       tree old_pack = TREE_VALUE (pack);
15659       tree new_args = TREE_TYPE (pack);
15660       int i, len = TREE_VEC_LENGTH (new_args);
15661       int idx, level;
15662       bool nondeduced_p = false;
15663
15664       /* By default keep the original deduced argument pack.
15665          If necessary, more specific code is going to update the
15666          resulting deduced argument later down in this function.  */
15667       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15668       TMPL_ARG (targs, level, idx) = old_pack;
15669
15670       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15671          actually deduce anything.  */
15672       for (i = 0; i < len && !nondeduced_p; ++i)
15673         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15674           nondeduced_p = true;
15675       if (nondeduced_p)
15676         continue;
15677
15678       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15679         {
15680           /* If we had fewer function args than explicit template args,
15681              just use the explicits.  */
15682           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15683           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15684           if (len < explicit_len)
15685             new_args = explicit_args;
15686         }
15687
15688       if (!old_pack)
15689         {
15690           tree result;
15691           /* Build the deduced *_ARGUMENT_PACK.  */
15692           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15693             {
15694               result = make_node (NONTYPE_ARGUMENT_PACK);
15695               TREE_TYPE (result) = 
15696                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15697               TREE_CONSTANT (result) = 1;
15698             }
15699           else
15700             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15701
15702           SET_ARGUMENT_PACK_ARGS (result, new_args);
15703
15704           /* Note the deduced argument packs for this parameter
15705              pack.  */
15706           TMPL_ARG (targs, level, idx) = result;
15707         }
15708       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15709                && (ARGUMENT_PACK_ARGS (old_pack) 
15710                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15711         {
15712           /* We only had the explicitly-provided arguments before, but
15713              now we have a complete set of arguments.  */
15714           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15715
15716           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15717           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15718           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15719         }
15720       else
15721         {
15722           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
15723           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15724
15725           if (!comp_template_args_with_info (old_args, new_args,
15726                                              &bad_old_arg, &bad_new_arg))
15727             /* Inconsistent unification of this parameter pack.  */
15728             return unify_parameter_pack_inconsistent (explain_p,
15729                                                       bad_old_arg,
15730                                                       bad_new_arg);
15731         }
15732     }
15733
15734   return unify_success (explain_p);
15735 }
15736
15737 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15738    set of template parameters to a template.  TARGS is the bindings
15739    for those template parameters, as determined thus far; TARGS may
15740    include template arguments for outer levels of template parameters
15741    as well.  PARM is a parameter to a template function, or a
15742    subcomponent of that parameter; ARG is the corresponding argument.
15743    This function attempts to match PARM with ARG in a manner
15744    consistent with the existing assignments in TARGS.  If more values
15745    are deduced, then TARGS is updated.
15746
15747    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15748    parameter STRICT is a bitwise or of the following flags:
15749
15750      UNIFY_ALLOW_NONE:
15751        Require an exact match between PARM and ARG.
15752      UNIFY_ALLOW_MORE_CV_QUAL:
15753        Allow the deduced ARG to be more cv-qualified (by qualification
15754        conversion) than ARG.
15755      UNIFY_ALLOW_LESS_CV_QUAL:
15756        Allow the deduced ARG to be less cv-qualified than ARG.
15757      UNIFY_ALLOW_DERIVED:
15758        Allow the deduced ARG to be a template base class of ARG,
15759        or a pointer to a template base class of the type pointed to by
15760        ARG.
15761      UNIFY_ALLOW_INTEGER:
15762        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15763        case for more information.
15764      UNIFY_ALLOW_OUTER_LEVEL:
15765        This is the outermost level of a deduction. Used to determine validity
15766        of qualification conversions. A valid qualification conversion must
15767        have const qualified pointers leading up to the inner type which
15768        requires additional CV quals, except at the outer level, where const
15769        is not required [conv.qual]. It would be normal to set this flag in
15770        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15771      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15772        This is the outermost level of a deduction, and PARM can be more CV
15773        qualified at this point.
15774      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15775        This is the outermost level of a deduction, and PARM can be less CV
15776        qualified at this point.  */
15777
15778 static int
15779 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15780        bool explain_p)
15781 {
15782   int idx;
15783   tree targ;
15784   tree tparm;
15785   int strict_in = strict;
15786
15787   /* I don't think this will do the right thing with respect to types.
15788      But the only case I've seen it in so far has been array bounds, where
15789      signedness is the only information lost, and I think that will be
15790      okay.  */
15791   while (TREE_CODE (parm) == NOP_EXPR)
15792     parm = TREE_OPERAND (parm, 0);
15793
15794   if (arg == error_mark_node)
15795     return unify_invalid (explain_p);
15796   if (arg == unknown_type_node
15797       || arg == init_list_type_node)
15798     /* We can't deduce anything from this, but we might get all the
15799        template args from other function args.  */
15800     return unify_success (explain_p);
15801
15802   /* If PARM uses template parameters, then we can't bail out here,
15803      even if ARG == PARM, since we won't record unifications for the
15804      template parameters.  We might need them if we're trying to
15805      figure out which of two things is more specialized.  */
15806   if (arg == parm && !uses_template_parms (parm))
15807     return unify_success (explain_p);
15808
15809   /* Handle init lists early, so the rest of the function can assume
15810      we're dealing with a type. */
15811   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15812     {
15813       tree elt, elttype;
15814       unsigned i;
15815       tree orig_parm = parm;
15816
15817       /* Replace T with std::initializer_list<T> for deduction.  */
15818       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15819           && flag_deduce_init_list)
15820         parm = listify (parm);
15821
15822       if (!is_std_init_list (parm))
15823         /* We can only deduce from an initializer list argument if the
15824            parameter is std::initializer_list; otherwise this is a
15825            non-deduced context. */
15826         return unify_success (explain_p);
15827
15828       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15829
15830       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15831         {
15832           int elt_strict = strict;
15833
15834           if (elt == error_mark_node)
15835             return unify_invalid (explain_p);
15836
15837           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15838             {
15839               tree type = TREE_TYPE (elt);
15840               /* It should only be possible to get here for a call.  */
15841               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15842               elt_strict |= maybe_adjust_types_for_deduction
15843                 (DEDUCE_CALL, &elttype, &type, elt);
15844               elt = type;
15845             }
15846
15847           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15848                                    explain_p);
15849         }
15850
15851       /* If the std::initializer_list<T> deduction worked, replace the
15852          deduced A with std::initializer_list<A>.  */
15853       if (orig_parm != parm)
15854         {
15855           idx = TEMPLATE_TYPE_IDX (orig_parm);
15856           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15857           targ = listify (targ);
15858           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15859         }
15860       return unify_success (explain_p);
15861     }
15862
15863   /* Immediately reject some pairs that won't unify because of
15864      cv-qualification mismatches.  */
15865   if (TREE_CODE (arg) == TREE_CODE (parm)
15866       && TYPE_P (arg)
15867       /* It is the elements of the array which hold the cv quals of an array
15868          type, and the elements might be template type parms. We'll check
15869          when we recurse.  */
15870       && TREE_CODE (arg) != ARRAY_TYPE
15871       /* We check the cv-qualifiers when unifying with template type
15872          parameters below.  We want to allow ARG `const T' to unify with
15873          PARM `T' for example, when computing which of two templates
15874          is more specialized, for example.  */
15875       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15876       && !check_cv_quals_for_unify (strict_in, arg, parm))
15877     return unify_cv_qual_mismatch (explain_p, parm, arg);
15878
15879   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15880       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15881     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15882   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15883   strict &= ~UNIFY_ALLOW_DERIVED;
15884   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15885   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15886
15887   switch (TREE_CODE (parm))
15888     {
15889     case TYPENAME_TYPE:
15890     case SCOPE_REF:
15891     case UNBOUND_CLASS_TEMPLATE:
15892       /* In a type which contains a nested-name-specifier, template
15893          argument values cannot be deduced for template parameters used
15894          within the nested-name-specifier.  */
15895       return unify_success (explain_p);
15896
15897     case TEMPLATE_TYPE_PARM:
15898     case TEMPLATE_TEMPLATE_PARM:
15899     case BOUND_TEMPLATE_TEMPLATE_PARM:
15900       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15901       if (tparm == error_mark_node)
15902         return unify_invalid (explain_p);
15903
15904       if (TEMPLATE_TYPE_LEVEL (parm)
15905           != template_decl_level (tparm))
15906         /* The PARM is not one we're trying to unify.  Just check
15907            to see if it matches ARG.  */
15908         {
15909           if (TREE_CODE (arg) == TREE_CODE (parm)
15910               && same_type_p (parm, arg))
15911             return unify_success (explain_p);
15912           else
15913             return unify_type_mismatch (explain_p, parm, arg);
15914         }
15915       idx = TEMPLATE_TYPE_IDX (parm);
15916       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15917       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15918
15919       /* Check for mixed types and values.  */
15920       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15921            && TREE_CODE (tparm) != TYPE_DECL)
15922           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15923               && TREE_CODE (tparm) != TEMPLATE_DECL))
15924         gcc_unreachable ();
15925
15926       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15927         {
15928           /* ARG must be constructed from a template class or a template
15929              template parameter.  */
15930           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15931               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15932             return unify_template_deduction_failure (explain_p, parm, arg);
15933
15934           {
15935             tree parmvec = TYPE_TI_ARGS (parm);
15936             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15937             tree full_argvec = add_to_template_args (targs, argvec);
15938             tree parm_parms 
15939               = DECL_INNERMOST_TEMPLATE_PARMS
15940                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15941             int i, len;
15942             int parm_variadic_p = 0;
15943
15944             /* The resolution to DR150 makes clear that default
15945                arguments for an N-argument may not be used to bind T
15946                to a template template parameter with fewer than N
15947                parameters.  It is not safe to permit the binding of
15948                default arguments as an extension, as that may change
15949                the meaning of a conforming program.  Consider:
15950
15951                   struct Dense { static const unsigned int dim = 1; };
15952
15953                   template <template <typename> class View,
15954                             typename Block>
15955                   void operator+(float, View<Block> const&);
15956
15957                   template <typename Block,
15958                             unsigned int Dim = Block::dim>
15959                   struct Lvalue_proxy { operator float() const; };
15960
15961                   void
15962                   test_1d (void) {
15963                     Lvalue_proxy<Dense> p;
15964                     float b;
15965                     b + p;
15966                   }
15967
15968               Here, if Lvalue_proxy is permitted to bind to View, then
15969               the global operator+ will be used; if they are not, the
15970               Lvalue_proxy will be converted to float.  */
15971             if (coerce_template_parms (parm_parms,
15972                                        full_argvec,
15973                                        TYPE_TI_TEMPLATE (parm),
15974                                        (explain_p
15975                                         ? tf_warning_or_error
15976                                         : tf_none),
15977                                        /*require_all_args=*/true,
15978                                        /*use_default_args=*/false)
15979                 == error_mark_node)
15980               return 1;
15981
15982             /* Deduce arguments T, i from TT<T> or TT<i>.
15983                We check each element of PARMVEC and ARGVEC individually
15984                rather than the whole TREE_VEC since they can have
15985                different number of elements.  */
15986
15987             parmvec = expand_template_argument_pack (parmvec);
15988             argvec = expand_template_argument_pack (argvec);
15989
15990             len = TREE_VEC_LENGTH (parmvec);
15991
15992             /* Check if the parameters end in a pack, making them
15993                variadic.  */
15994             if (len > 0
15995                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15996               parm_variadic_p = 1;
15997             
15998             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15999               return unify_too_few_arguments (explain_p,
16000                                               TREE_VEC_LENGTH (argvec), len);
16001
16002              for (i = 0; i < len - parm_variadic_p; ++i)
16003               {
16004                 RECUR_AND_CHECK_FAILURE (tparms, targs,
16005                                          TREE_VEC_ELT (parmvec, i),
16006                                          TREE_VEC_ELT (argvec, i),
16007                                          UNIFY_ALLOW_NONE, explain_p);
16008               }
16009
16010             if (parm_variadic_p
16011                 && unify_pack_expansion (tparms, targs,
16012                                          parmvec, argvec,
16013                                          DEDUCE_EXACT,
16014                                          /*subr=*/true, explain_p))
16015               return 1;
16016           }
16017           arg = TYPE_TI_TEMPLATE (arg);
16018
16019           /* Fall through to deduce template name.  */
16020         }
16021
16022       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16023           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16024         {
16025           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16026
16027           /* Simple cases: Value already set, does match or doesn't.  */
16028           if (targ != NULL_TREE && template_args_equal (targ, arg))
16029             return unify_success (explain_p);
16030           else if (targ)
16031             return unify_inconsistency (explain_p, parm, targ, arg);
16032         }
16033       else
16034         {
16035           /* If PARM is `const T' and ARG is only `int', we don't have
16036              a match unless we are allowing additional qualification.
16037              If ARG is `const int' and PARM is just `T' that's OK;
16038              that binds `const int' to `T'.  */
16039           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16040                                          arg, parm))
16041             return unify_cv_qual_mismatch (explain_p, parm, arg);
16042
16043           /* Consider the case where ARG is `const volatile int' and
16044              PARM is `const T'.  Then, T should be `volatile int'.  */
16045           arg = cp_build_qualified_type_real
16046             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16047           if (arg == error_mark_node)
16048             return unify_invalid (explain_p);
16049
16050           /* Simple cases: Value already set, does match or doesn't.  */
16051           if (targ != NULL_TREE && same_type_p (targ, arg))
16052             return unify_success (explain_p);
16053           else if (targ)
16054             return unify_inconsistency (explain_p, parm, targ, arg);
16055
16056           /* Make sure that ARG is not a variable-sized array.  (Note
16057              that were talking about variable-sized arrays (like
16058              `int[n]'), rather than arrays of unknown size (like
16059              `int[]').)  We'll get very confused by such a type since
16060              the bound of the array is not constant, and therefore
16061              not mangleable.  Besides, such types are not allowed in
16062              ISO C++, so we can do as we please here.  We do allow
16063              them for 'auto' deduction, since that isn't ABI-exposed.  */
16064           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16065             return unify_vla_arg (explain_p, arg);
16066
16067           /* Strip typedefs as in convert_template_argument.  */
16068           arg = canonicalize_type_argument (arg, tf_none);
16069         }
16070
16071       /* If ARG is a parameter pack or an expansion, we cannot unify
16072          against it unless PARM is also a parameter pack.  */
16073       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16074           && !template_parameter_pack_p (parm))
16075         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16076
16077       /* If the argument deduction results is a METHOD_TYPE,
16078          then there is a problem.
16079          METHOD_TYPE doesn't map to any real C++ type the result of
16080          the deduction can not be of that type.  */
16081       if (TREE_CODE (arg) == METHOD_TYPE)
16082         return unify_method_type_error (explain_p, arg);
16083
16084       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16085       return unify_success (explain_p);
16086
16087     case TEMPLATE_PARM_INDEX:
16088       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16089       if (tparm == error_mark_node)
16090         return unify_invalid (explain_p);
16091
16092       if (TEMPLATE_PARM_LEVEL (parm)
16093           != template_decl_level (tparm))
16094         {
16095           /* The PARM is not one we're trying to unify.  Just check
16096              to see if it matches ARG.  */
16097           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16098                          && cp_tree_equal (parm, arg));
16099           if (result)
16100             unify_expression_unequal (explain_p, parm, arg);
16101           return result;
16102         }
16103
16104       idx = TEMPLATE_PARM_IDX (parm);
16105       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16106
16107       if (targ)
16108         {
16109           int x = !cp_tree_equal (targ, arg);
16110           if (x)
16111             unify_inconsistency (explain_p, parm, targ, arg);
16112           return x;
16113         }
16114
16115       /* [temp.deduct.type] If, in the declaration of a function template
16116          with a non-type template-parameter, the non-type
16117          template-parameter is used in an expression in the function
16118          parameter-list and, if the corresponding template-argument is
16119          deduced, the template-argument type shall match the type of the
16120          template-parameter exactly, except that a template-argument
16121          deduced from an array bound may be of any integral type.
16122          The non-type parameter might use already deduced type parameters.  */
16123       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16124       if (!TREE_TYPE (arg))
16125         /* Template-parameter dependent expression.  Just accept it for now.
16126            It will later be processed in convert_template_argument.  */
16127         ;
16128       else if (same_type_p (TREE_TYPE (arg), tparm))
16129         /* OK */;
16130       else if ((strict & UNIFY_ALLOW_INTEGER)
16131                && (TREE_CODE (tparm) == INTEGER_TYPE
16132                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16133         /* Convert the ARG to the type of PARM; the deduced non-type
16134            template argument must exactly match the types of the
16135            corresponding parameter.  */
16136         arg = fold (build_nop (tparm, arg));
16137       else if (uses_template_parms (tparm))
16138         /* We haven't deduced the type of this parameter yet.  Try again
16139            later.  */
16140         return unify_success (explain_p);
16141       else
16142         return unify_type_mismatch (explain_p, tparm, arg);
16143
16144       /* If ARG is a parameter pack or an expansion, we cannot unify
16145          against it unless PARM is also a parameter pack.  */
16146       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16147           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16148         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16149
16150       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16151       return unify_success (explain_p);
16152
16153     case PTRMEM_CST:
16154      {
16155         /* A pointer-to-member constant can be unified only with
16156          another constant.  */
16157       if (TREE_CODE (arg) != PTRMEM_CST)
16158         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16159
16160       /* Just unify the class member. It would be useless (and possibly
16161          wrong, depending on the strict flags) to unify also
16162          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16163          arg refer to the same variable, even if through different
16164          classes. For instance:
16165
16166          struct A { int x; };
16167          struct B : A { };
16168
16169          Unification of &A::x and &B::x must succeed.  */
16170       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16171                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16172      }
16173
16174     case POINTER_TYPE:
16175       {
16176         if (TREE_CODE (arg) != POINTER_TYPE)
16177           return unify_type_mismatch (explain_p, parm, arg);
16178
16179         /* [temp.deduct.call]
16180
16181            A can be another pointer or pointer to member type that can
16182            be converted to the deduced A via a qualification
16183            conversion (_conv.qual_).
16184
16185            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16186            This will allow for additional cv-qualification of the
16187            pointed-to types if appropriate.  */
16188
16189         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16190           /* The derived-to-base conversion only persists through one
16191              level of pointers.  */
16192           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16193
16194         return unify (tparms, targs, TREE_TYPE (parm),
16195                       TREE_TYPE (arg), strict, explain_p);
16196       }
16197
16198     case REFERENCE_TYPE:
16199       if (TREE_CODE (arg) != REFERENCE_TYPE)
16200         return unify_type_mismatch (explain_p, parm, arg);
16201       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16202                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16203
16204     case ARRAY_TYPE:
16205       if (TREE_CODE (arg) != ARRAY_TYPE)
16206         return unify_type_mismatch (explain_p, parm, arg);
16207       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16208           != (TYPE_DOMAIN (arg) == NULL_TREE))
16209         return unify_type_mismatch (explain_p, parm, arg);
16210       if (TYPE_DOMAIN (parm) != NULL_TREE)
16211         {
16212           tree parm_max;
16213           tree arg_max;
16214           bool parm_cst;
16215           bool arg_cst;
16216
16217           /* Our representation of array types uses "N - 1" as the
16218              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16219              not an integer constant.  We cannot unify arbitrarily
16220              complex expressions, so we eliminate the MINUS_EXPRs
16221              here.  */
16222           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16223           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16224           if (!parm_cst)
16225             {
16226               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16227               parm_max = TREE_OPERAND (parm_max, 0);
16228             }
16229           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16230           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16231           if (!arg_cst)
16232             {
16233               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16234                  trying to unify the type of a variable with the type
16235                  of a template parameter.  For example:
16236
16237                    template <unsigned int N>
16238                    void f (char (&) [N]);
16239                    int g(); 
16240                    void h(int i) {
16241                      char a[g(i)];
16242                      f(a); 
16243                    }
16244
16245                 Here, the type of the ARG will be "int [g(i)]", and
16246                 may be a SAVE_EXPR, etc.  */
16247               if (TREE_CODE (arg_max) != MINUS_EXPR)
16248                 return unify_vla_arg (explain_p, arg);
16249               arg_max = TREE_OPERAND (arg_max, 0);
16250             }
16251
16252           /* If only one of the bounds used a MINUS_EXPR, compensate
16253              by adding one to the other bound.  */
16254           if (parm_cst && !arg_cst)
16255             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16256                                     integer_type_node,
16257                                     parm_max,
16258                                     integer_one_node);
16259           else if (arg_cst && !parm_cst)
16260             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16261                                    integer_type_node,
16262                                    arg_max,
16263                                    integer_one_node);
16264
16265           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16266                                    UNIFY_ALLOW_INTEGER, explain_p);
16267         }
16268       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16269                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16270
16271     case REAL_TYPE:
16272     case COMPLEX_TYPE:
16273     case VECTOR_TYPE:
16274     case INTEGER_TYPE:
16275     case BOOLEAN_TYPE:
16276     case ENUMERAL_TYPE:
16277     case VOID_TYPE:
16278       if (TREE_CODE (arg) != TREE_CODE (parm))
16279         return unify_type_mismatch (explain_p, parm, arg);
16280
16281       /* We have already checked cv-qualification at the top of the
16282          function.  */
16283       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16284         return unify_type_mismatch (explain_p, parm, arg);
16285
16286       /* As far as unification is concerned, this wins.  Later checks
16287          will invalidate it if necessary.  */
16288       return unify_success (explain_p);
16289
16290       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16291       /* Type INTEGER_CST can come from ordinary constant template args.  */
16292     case INTEGER_CST:
16293       while (TREE_CODE (arg) == NOP_EXPR)
16294         arg = TREE_OPERAND (arg, 0);
16295
16296       if (TREE_CODE (arg) != INTEGER_CST)
16297         return unify_template_argument_mismatch (explain_p, parm, arg);
16298       return (tree_int_cst_equal (parm, arg)
16299               ? unify_success (explain_p)
16300               : unify_template_argument_mismatch (explain_p, parm, arg));
16301
16302     case TREE_VEC:
16303       {
16304         int i, len, argslen;
16305         int parm_variadic_p = 0;
16306
16307         if (TREE_CODE (arg) != TREE_VEC)
16308           return unify_template_argument_mismatch (explain_p, parm, arg);
16309
16310         len = TREE_VEC_LENGTH (parm);
16311         argslen = TREE_VEC_LENGTH (arg);
16312
16313         /* Check for pack expansions in the parameters.  */
16314         for (i = 0; i < len; ++i)
16315           {
16316             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16317               {
16318                 if (i == len - 1)
16319                   /* We can unify against something with a trailing
16320                      parameter pack.  */
16321                   parm_variadic_p = 1;
16322                 else
16323                   /* [temp.deduct.type]/9: If the template argument list of
16324                      P contains a pack expansion that is not the last
16325                      template argument, the entire template argument list
16326                      is a non-deduced context.  */
16327                   return unify_success (explain_p);
16328               }
16329           }
16330
16331         /* If we don't have enough arguments to satisfy the parameters
16332            (not counting the pack expression at the end), or we have
16333            too many arguments for a parameter list that doesn't end in
16334            a pack expression, we can't unify.  */
16335         if (parm_variadic_p
16336             ? argslen < len - parm_variadic_p
16337             : argslen != len)
16338           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16339
16340         /* Unify all of the parameters that precede the (optional)
16341            pack expression.  */
16342         for (i = 0; i < len - parm_variadic_p; ++i)
16343           {
16344             RECUR_AND_CHECK_FAILURE (tparms, targs,
16345                                      TREE_VEC_ELT (parm, i),
16346                                      TREE_VEC_ELT (arg, i),
16347                                      UNIFY_ALLOW_NONE, explain_p);
16348           }
16349         if (parm_variadic_p)
16350           return unify_pack_expansion (tparms, targs, parm, arg,
16351                                        DEDUCE_EXACT,
16352                                        /*subr=*/true, explain_p);
16353         return unify_success (explain_p);
16354       }
16355
16356     case RECORD_TYPE:
16357     case UNION_TYPE:
16358       if (TREE_CODE (arg) != TREE_CODE (parm))
16359         return unify_type_mismatch (explain_p, parm, arg);
16360
16361       if (TYPE_PTRMEMFUNC_P (parm))
16362         {
16363           if (!TYPE_PTRMEMFUNC_P (arg))
16364             return unify_type_mismatch (explain_p, parm, arg);
16365
16366           return unify (tparms, targs,
16367                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16368                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16369                         strict, explain_p);
16370         }
16371
16372       if (CLASSTYPE_TEMPLATE_INFO (parm))
16373         {
16374           tree t = NULL_TREE;
16375
16376           if (strict_in & UNIFY_ALLOW_DERIVED)
16377             {
16378               /* First, we try to unify the PARM and ARG directly.  */
16379               t = try_class_unification (tparms, targs,
16380                                          parm, arg, explain_p);
16381
16382               if (!t)
16383                 {
16384                   /* Fallback to the special case allowed in
16385                      [temp.deduct.call]:
16386
16387                        If P is a class, and P has the form
16388                        template-id, then A can be a derived class of
16389                        the deduced A.  Likewise, if P is a pointer to
16390                        a class of the form template-id, A can be a
16391                        pointer to a derived class pointed to by the
16392                        deduced A.  */
16393                   enum template_base_result r;
16394                   r = get_template_base (tparms, targs, parm, arg,
16395                                          explain_p, &t);
16396
16397                   if (!t)
16398                     return unify_no_common_base (explain_p, r, parm, arg);
16399                 }
16400             }
16401           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16402                    && (CLASSTYPE_TI_TEMPLATE (parm)
16403                        == CLASSTYPE_TI_TEMPLATE (arg)))
16404             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16405                Then, we should unify `int' and `U'.  */
16406             t = arg;
16407           else
16408             /* There's no chance of unification succeeding.  */
16409             return unify_type_mismatch (explain_p, parm, arg);
16410
16411           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16412                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16413         }
16414       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16415         return unify_type_mismatch (explain_p, parm, arg);
16416       return unify_success (explain_p);
16417
16418     case METHOD_TYPE:
16419     case FUNCTION_TYPE:
16420       {
16421         unsigned int nargs;
16422         tree *args;
16423         tree a;
16424         unsigned int i;
16425
16426         if (TREE_CODE (arg) != TREE_CODE (parm))
16427           return unify_type_mismatch (explain_p, parm, arg);
16428
16429         /* CV qualifications for methods can never be deduced, they must
16430            match exactly.  We need to check them explicitly here,
16431            because type_unification_real treats them as any other
16432            cv-qualified parameter.  */
16433         if (TREE_CODE (parm) == METHOD_TYPE
16434             && (!check_cv_quals_for_unify
16435                 (UNIFY_ALLOW_NONE,
16436                  class_of_this_parm (arg),
16437                  class_of_this_parm (parm))))
16438           return unify_cv_qual_mismatch (explain_p, parm, arg);
16439
16440         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16441                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16442
16443         nargs = list_length (TYPE_ARG_TYPES (arg));
16444         args = XALLOCAVEC (tree, nargs);
16445         for (a = TYPE_ARG_TYPES (arg), i = 0;
16446              a != NULL_TREE && a != void_list_node;
16447              a = TREE_CHAIN (a), ++i)
16448           args[i] = TREE_VALUE (a);
16449         nargs = i;
16450
16451         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16452                                       args, nargs, 1, DEDUCE_EXACT,
16453                                       LOOKUP_NORMAL, explain_p);
16454       }
16455
16456     case OFFSET_TYPE:
16457       /* Unify a pointer to member with a pointer to member function, which
16458          deduces the type of the member as a function type. */
16459       if (TYPE_PTRMEMFUNC_P (arg))
16460         {
16461           tree method_type;
16462           tree fntype;
16463
16464           /* Check top-level cv qualifiers */
16465           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16466             return unify_cv_qual_mismatch (explain_p, parm, arg);
16467
16468           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16469                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16470                                    UNIFY_ALLOW_NONE, explain_p);
16471
16472           /* Determine the type of the function we are unifying against. */
16473           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16474           fntype =
16475             build_function_type (TREE_TYPE (method_type),
16476                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16477
16478           /* Extract the cv-qualifiers of the member function from the
16479              implicit object parameter and place them on the function
16480              type to be restored later. */
16481           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16482           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16483         }
16484
16485       if (TREE_CODE (arg) != OFFSET_TYPE)
16486         return unify_type_mismatch (explain_p, parm, arg);
16487       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16488                                TYPE_OFFSET_BASETYPE (arg),
16489                                UNIFY_ALLOW_NONE, explain_p);
16490       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16491                     strict, explain_p);
16492
16493     case CONST_DECL:
16494       if (DECL_TEMPLATE_PARM_P (parm))
16495         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16496       if (arg != integral_constant_value (parm))
16497         return unify_template_argument_mismatch (explain_p, parm, arg);
16498       return unify_success (explain_p);
16499
16500     case FIELD_DECL:
16501     case TEMPLATE_DECL:
16502       /* Matched cases are handled by the ARG == PARM test above.  */
16503       return unify_template_argument_mismatch (explain_p, parm, arg);
16504
16505     case VAR_DECL:
16506       /* A non-type template parameter that is a variable should be a
16507          an integral constant, in which case, it whould have been
16508          folded into its (constant) value. So we should not be getting
16509          a variable here.  */
16510       gcc_unreachable ();
16511
16512     case TYPE_ARGUMENT_PACK:
16513     case NONTYPE_ARGUMENT_PACK:
16514       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16515                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16516
16517     case TYPEOF_TYPE:
16518     case DECLTYPE_TYPE:
16519     case UNDERLYING_TYPE:
16520       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16521          or UNDERLYING_TYPE nodes.  */
16522       return unify_success (explain_p);
16523
16524     case ERROR_MARK:
16525       /* Unification fails if we hit an error node.  */
16526       return unify_invalid (explain_p);
16527
16528     default:
16529       /* An unresolved overload is a nondeduced context.  */
16530       if (type_unknown_p (parm))
16531         return unify_success (explain_p);
16532       gcc_assert (EXPR_P (parm));
16533
16534       /* We must be looking at an expression.  This can happen with
16535          something like:
16536
16537            template <int I>
16538            void foo(S<I>, S<I + 2>);
16539
16540          This is a "nondeduced context":
16541
16542            [deduct.type]
16543
16544            The nondeduced contexts are:
16545
16546            --A type that is a template-id in which one or more of
16547              the template-arguments is an expression that references
16548              a template-parameter.
16549
16550          In these cases, we assume deduction succeeded, but don't
16551          actually infer any unifications.  */
16552
16553       if (!uses_template_parms (parm)
16554           && !template_args_equal (parm, arg))
16555         return unify_expression_unequal (explain_p, parm, arg);
16556       else
16557         return unify_success (explain_p);
16558     }
16559 }
16560 #undef RECUR_AND_CHECK_FAILURE
16561 \f
16562 /* Note that DECL can be defined in this translation unit, if
16563    required.  */
16564
16565 static void
16566 mark_definable (tree decl)
16567 {
16568   tree clone;
16569   DECL_NOT_REALLY_EXTERN (decl) = 1;
16570   FOR_EACH_CLONE (clone, decl)
16571     DECL_NOT_REALLY_EXTERN (clone) = 1;
16572 }
16573
16574 /* Called if RESULT is explicitly instantiated, or is a member of an
16575    explicitly instantiated class.  */
16576
16577 void
16578 mark_decl_instantiated (tree result, int extern_p)
16579 {
16580   SET_DECL_EXPLICIT_INSTANTIATION (result);
16581
16582   /* If this entity has already been written out, it's too late to
16583      make any modifications.  */
16584   if (TREE_ASM_WRITTEN (result))
16585     return;
16586
16587   if (TREE_CODE (result) != FUNCTION_DECL)
16588     /* The TREE_PUBLIC flag for function declarations will have been
16589        set correctly by tsubst.  */
16590     TREE_PUBLIC (result) = 1;
16591
16592   /* This might have been set by an earlier implicit instantiation.  */
16593   DECL_COMDAT (result) = 0;
16594
16595   if (extern_p)
16596     DECL_NOT_REALLY_EXTERN (result) = 0;
16597   else
16598     {
16599       mark_definable (result);
16600       /* Always make artificials weak.  */
16601       if (DECL_ARTIFICIAL (result) && flag_weak)
16602         comdat_linkage (result);
16603       /* For WIN32 we also want to put explicit instantiations in
16604          linkonce sections.  */
16605       else if (TREE_PUBLIC (result))
16606         maybe_make_one_only (result);
16607     }
16608
16609   /* If EXTERN_P, then this function will not be emitted -- unless
16610      followed by an explicit instantiation, at which point its linkage
16611      will be adjusted.  If !EXTERN_P, then this function will be
16612      emitted here.  In neither circumstance do we want
16613      import_export_decl to adjust the linkage.  */
16614   DECL_INTERFACE_KNOWN (result) = 1;
16615 }
16616
16617 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16618    important template arguments.  If any are missing, we check whether
16619    they're important by using error_mark_node for substituting into any
16620    args that were used for partial ordering (the ones between ARGS and END)
16621    and seeing if it bubbles up.  */
16622
16623 static bool
16624 check_undeduced_parms (tree targs, tree args, tree end)
16625 {
16626   bool found = false;
16627   int i;
16628   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16629     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16630       {
16631         found = true;
16632         TREE_VEC_ELT (targs, i) = error_mark_node;
16633       }
16634   if (found)
16635     {
16636       for (; args != end; args = TREE_CHAIN (args))
16637         {
16638           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16639           if (substed == error_mark_node)
16640             return true;
16641         }
16642     }
16643   return false;
16644 }
16645
16646 /* Given two function templates PAT1 and PAT2, return:
16647
16648    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16649    -1 if PAT2 is more specialized than PAT1.
16650    0 if neither is more specialized.
16651
16652    LEN indicates the number of parameters we should consider
16653    (defaulted parameters should not be considered).
16654
16655    The 1998 std underspecified function template partial ordering, and
16656    DR214 addresses the issue.  We take pairs of arguments, one from
16657    each of the templates, and deduce them against each other.  One of
16658    the templates will be more specialized if all the *other*
16659    template's arguments deduce against its arguments and at least one
16660    of its arguments *does* *not* deduce against the other template's
16661    corresponding argument.  Deduction is done as for class templates.
16662    The arguments used in deduction have reference and top level cv
16663    qualifiers removed.  Iff both arguments were originally reference
16664    types *and* deduction succeeds in both directions, the template
16665    with the more cv-qualified argument wins for that pairing (if
16666    neither is more cv-qualified, they both are equal).  Unlike regular
16667    deduction, after all the arguments have been deduced in this way,
16668    we do *not* verify the deduced template argument values can be
16669    substituted into non-deduced contexts.
16670
16671    The logic can be a bit confusing here, because we look at deduce1 and
16672    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16673    can find template arguments for pat1 to make arg1 look like arg2, that
16674    means that arg2 is at least as specialized as arg1.  */
16675
16676 int
16677 more_specialized_fn (tree pat1, tree pat2, int len)
16678 {
16679   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16680   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16681   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16682   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16683   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16684   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16685   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16686   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16687   tree origs1, origs2;
16688   bool lose1 = false;
16689   bool lose2 = false;
16690
16691   /* Remove the this parameter from non-static member functions.  If
16692      one is a non-static member function and the other is not a static
16693      member function, remove the first parameter from that function
16694      also.  This situation occurs for operator functions where we
16695      locate both a member function (with this pointer) and non-member
16696      operator (with explicit first operand).  */
16697   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16698     {
16699       len--; /* LEN is the number of significant arguments for DECL1 */
16700       args1 = TREE_CHAIN (args1);
16701       if (!DECL_STATIC_FUNCTION_P (decl2))
16702         args2 = TREE_CHAIN (args2);
16703     }
16704   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16705     {
16706       args2 = TREE_CHAIN (args2);
16707       if (!DECL_STATIC_FUNCTION_P (decl1))
16708         {
16709           len--;
16710           args1 = TREE_CHAIN (args1);
16711         }
16712     }
16713
16714   /* If only one is a conversion operator, they are unordered.  */
16715   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16716     return 0;
16717
16718   /* Consider the return type for a conversion function */
16719   if (DECL_CONV_FN_P (decl1))
16720     {
16721       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16722       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16723       len++;
16724     }
16725
16726   processing_template_decl++;
16727
16728   origs1 = args1;
16729   origs2 = args2;
16730
16731   while (len--
16732          /* Stop when an ellipsis is seen.  */
16733          && args1 != NULL_TREE && args2 != NULL_TREE)
16734     {
16735       tree arg1 = TREE_VALUE (args1);
16736       tree arg2 = TREE_VALUE (args2);
16737       int deduce1, deduce2;
16738       int quals1 = -1;
16739       int quals2 = -1;
16740
16741       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16742           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16743         {
16744           /* When both arguments are pack expansions, we need only
16745              unify the patterns themselves.  */
16746           arg1 = PACK_EXPANSION_PATTERN (arg1);
16747           arg2 = PACK_EXPANSION_PATTERN (arg2);
16748
16749           /* This is the last comparison we need to do.  */
16750           len = 0;
16751         }
16752
16753       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16754         {
16755           arg1 = TREE_TYPE (arg1);
16756           quals1 = cp_type_quals (arg1);
16757         }
16758
16759       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16760         {
16761           arg2 = TREE_TYPE (arg2);
16762           quals2 = cp_type_quals (arg2);
16763         }
16764
16765       if ((quals1 < 0) != (quals2 < 0))
16766         {
16767           /* Only of the args is a reference, see if we should apply
16768              array/function pointer decay to it.  This is not part of
16769              DR214, but is, IMHO, consistent with the deduction rules
16770              for the function call itself, and with our earlier
16771              implementation of the underspecified partial ordering
16772              rules.  (nathan).  */
16773           if (quals1 >= 0)
16774             {
16775               switch (TREE_CODE (arg1))
16776                 {
16777                 case ARRAY_TYPE:
16778                   arg1 = TREE_TYPE (arg1);
16779                   /* FALLTHROUGH. */
16780                 case FUNCTION_TYPE:
16781                   arg1 = build_pointer_type (arg1);
16782                   break;
16783
16784                 default:
16785                   break;
16786                 }
16787             }
16788           else
16789             {
16790               switch (TREE_CODE (arg2))
16791                 {
16792                 case ARRAY_TYPE:
16793                   arg2 = TREE_TYPE (arg2);
16794                   /* FALLTHROUGH. */
16795                 case FUNCTION_TYPE:
16796                   arg2 = build_pointer_type (arg2);
16797                   break;
16798
16799                 default:
16800                   break;
16801                 }
16802             }
16803         }
16804
16805       arg1 = TYPE_MAIN_VARIANT (arg1);
16806       arg2 = TYPE_MAIN_VARIANT (arg2);
16807
16808       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16809         {
16810           int i, len2 = list_length (args2);
16811           tree parmvec = make_tree_vec (1);
16812           tree argvec = make_tree_vec (len2);
16813           tree ta = args2;
16814
16815           /* Setup the parameter vector, which contains only ARG1.  */
16816           TREE_VEC_ELT (parmvec, 0) = arg1;
16817
16818           /* Setup the argument vector, which contains the remaining
16819              arguments.  */
16820           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16821             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16822
16823           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16824                                            argvec, DEDUCE_EXACT,
16825                                            /*subr=*/true, /*explain_p=*/false)
16826                      == 0);
16827
16828           /* We cannot deduce in the other direction, because ARG1 is
16829              a pack expansion but ARG2 is not.  */
16830           deduce2 = 0;
16831         }
16832       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16833         {
16834           int i, len1 = list_length (args1);
16835           tree parmvec = make_tree_vec (1);
16836           tree argvec = make_tree_vec (len1);
16837           tree ta = args1;
16838
16839           /* Setup the parameter vector, which contains only ARG1.  */
16840           TREE_VEC_ELT (parmvec, 0) = arg2;
16841
16842           /* Setup the argument vector, which contains the remaining
16843              arguments.  */
16844           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16845             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16846
16847           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16848                                            argvec, DEDUCE_EXACT,
16849                                            /*subr=*/true, /*explain_p=*/false)
16850                      == 0);
16851
16852           /* We cannot deduce in the other direction, because ARG2 is
16853              a pack expansion but ARG1 is not.*/
16854           deduce1 = 0;
16855         }
16856
16857       else
16858         {
16859           /* The normal case, where neither argument is a pack
16860              expansion.  */
16861           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16862                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16863                      == 0);
16864           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16865                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16866                      == 0);
16867         }
16868
16869       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16870          arg2, then arg2 is not as specialized as arg1.  */
16871       if (!deduce1)
16872         lose2 = true;
16873       if (!deduce2)
16874         lose1 = true;
16875
16876       /* "If, for a given type, deduction succeeds in both directions
16877          (i.e., the types are identical after the transformations above)
16878          and if the type from the argument template is more cv-qualified
16879          than the type from the parameter template (as described above)
16880          that type is considered to be more specialized than the other. If
16881          neither type is more cv-qualified than the other then neither type
16882          is more specialized than the other."  */
16883
16884       if (deduce1 && deduce2
16885           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16886         {
16887           if ((quals1 & quals2) == quals2)
16888             lose2 = true;
16889           if ((quals1 & quals2) == quals1)
16890             lose1 = true;
16891         }
16892
16893       if (lose1 && lose2)
16894         /* We've failed to deduce something in either direction.
16895            These must be unordered.  */
16896         break;
16897
16898       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16899           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16900         /* We have already processed all of the arguments in our
16901            handing of the pack expansion type.  */
16902         len = 0;
16903
16904       args1 = TREE_CHAIN (args1);
16905       args2 = TREE_CHAIN (args2);
16906     }
16907
16908   /* "In most cases, all template parameters must have values in order for
16909      deduction to succeed, but for partial ordering purposes a template
16910      parameter may remain without a value provided it is not used in the
16911      types being used for partial ordering."
16912
16913      Thus, if we are missing any of the targs1 we need to substitute into
16914      origs1, then pat2 is not as specialized as pat1.  This can happen when
16915      there is a nondeduced context.  */
16916   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16917     lose2 = true;
16918   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16919     lose1 = true;
16920
16921   processing_template_decl--;
16922
16923   /* All things being equal, if the next argument is a pack expansion
16924      for one function but not for the other, prefer the
16925      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16926   if (lose1 == lose2
16927       && args1 && TREE_VALUE (args1)
16928       && args2 && TREE_VALUE (args2))
16929     {
16930       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16931       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16932     }
16933
16934   if (lose1 == lose2)
16935     return 0;
16936   else if (!lose1)
16937     return 1;
16938   else
16939     return -1;
16940 }
16941
16942 /* Determine which of two partial specializations is more specialized.
16943
16944    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16945    to the first partial specialization.  The TREE_VALUE is the
16946    innermost set of template parameters for the partial
16947    specialization.  PAT2 is similar, but for the second template.
16948
16949    Return 1 if the first partial specialization is more specialized;
16950    -1 if the second is more specialized; 0 if neither is more
16951    specialized.
16952
16953    See [temp.class.order] for information about determining which of
16954    two templates is more specialized.  */
16955
16956 static int
16957 more_specialized_class (tree pat1, tree pat2)
16958 {
16959   tree targs;
16960   tree tmpl1, tmpl2;
16961   int winner = 0;
16962   bool any_deductions = false;
16963
16964   tmpl1 = TREE_TYPE (pat1);
16965   tmpl2 = TREE_TYPE (pat2);
16966
16967   /* Just like what happens for functions, if we are ordering between
16968      different class template specializations, we may encounter dependent
16969      types in the arguments, and we need our dependency check functions
16970      to behave correctly.  */
16971   ++processing_template_decl;
16972   targs = get_class_bindings (TREE_VALUE (pat1),
16973                               CLASSTYPE_TI_ARGS (tmpl1),
16974                               CLASSTYPE_TI_ARGS (tmpl2));
16975   if (targs)
16976     {
16977       --winner;
16978       any_deductions = true;
16979     }
16980
16981   targs = get_class_bindings (TREE_VALUE (pat2),
16982                               CLASSTYPE_TI_ARGS (tmpl2),
16983                               CLASSTYPE_TI_ARGS (tmpl1));
16984   if (targs)
16985     {
16986       ++winner;
16987       any_deductions = true;
16988     }
16989   --processing_template_decl;
16990
16991   /* In the case of a tie where at least one of the class templates
16992      has a parameter pack at the end, the template with the most
16993      non-packed parameters wins.  */
16994   if (winner == 0
16995       && any_deductions
16996       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16997           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16998     {
16999       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
17000       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
17001       int len1 = TREE_VEC_LENGTH (args1);
17002       int len2 = TREE_VEC_LENGTH (args2);
17003
17004       /* We don't count the pack expansion at the end.  */
17005       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
17006         --len1;
17007       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
17008         --len2;
17009
17010       if (len1 > len2)
17011         return 1;
17012       else if (len1 < len2)
17013         return -1;
17014     }
17015
17016   return winner;
17017 }
17018
17019 /* Return the template arguments that will produce the function signature
17020    DECL from the function template FN, with the explicit template
17021    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17022    also match.  Return NULL_TREE if no satisfactory arguments could be
17023    found.  */
17024
17025 static tree
17026 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17027 {
17028   int ntparms = DECL_NTPARMS (fn);
17029   tree targs = make_tree_vec (ntparms);
17030   tree decl_type;
17031   tree decl_arg_types;
17032   tree *args;
17033   unsigned int nargs, ix;
17034   tree arg;
17035
17036   /* Substitute the explicit template arguments into the type of DECL.
17037      The call to fn_type_unification will handle substitution into the
17038      FN.  */
17039   decl_type = TREE_TYPE (decl);
17040   if (explicit_args && uses_template_parms (decl_type))
17041     {
17042       tree tmpl;
17043       tree converted_args;
17044
17045       if (DECL_TEMPLATE_INFO (decl))
17046         tmpl = DECL_TI_TEMPLATE (decl);
17047       else
17048         /* We can get here for some invalid specializations.  */
17049         return NULL_TREE;
17050
17051       converted_args
17052         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17053                                  explicit_args, NULL_TREE,
17054                                  tf_none,
17055                                  /*require_all_args=*/false,
17056                                  /*use_default_args=*/false);
17057       if (converted_args == error_mark_node)
17058         return NULL_TREE;
17059
17060       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17061       if (decl_type == error_mark_node)
17062         return NULL_TREE;
17063     }
17064
17065   /* Never do unification on the 'this' parameter.  */
17066   decl_arg_types = skip_artificial_parms_for (decl, 
17067                                               TYPE_ARG_TYPES (decl_type));
17068
17069   nargs = list_length (decl_arg_types);
17070   args = XALLOCAVEC (tree, nargs);
17071   for (arg = decl_arg_types, ix = 0;
17072        arg != NULL_TREE && arg != void_list_node;
17073        arg = TREE_CHAIN (arg), ++ix)
17074     args[ix] = TREE_VALUE (arg);
17075
17076   if (fn_type_unification (fn, explicit_args, targs,
17077                            args, ix,
17078                            (check_rettype || DECL_CONV_FN_P (fn)
17079                             ? TREE_TYPE (decl_type) : NULL_TREE),
17080                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17081     return NULL_TREE;
17082
17083   return targs;
17084 }
17085
17086 /* Return the innermost template arguments that, when applied to a
17087    template specialization whose innermost template parameters are
17088    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17089    ARGS.
17090
17091    For example, suppose we have:
17092
17093      template <class T, class U> struct S {};
17094      template <class T> struct S<T*, int> {};
17095
17096    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17097    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17098    int}.  The resulting vector will be {double}, indicating that `T'
17099    is bound to `double'.  */
17100
17101 static tree
17102 get_class_bindings (tree tparms, tree spec_args, tree args)
17103 {
17104   int i, ntparms = TREE_VEC_LENGTH (tparms);
17105   tree deduced_args;
17106   tree innermost_deduced_args;
17107
17108   innermost_deduced_args = make_tree_vec (ntparms);
17109   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17110     {
17111       deduced_args = copy_node (args);
17112       SET_TMPL_ARGS_LEVEL (deduced_args,
17113                            TMPL_ARGS_DEPTH (deduced_args),
17114                            innermost_deduced_args);
17115     }
17116   else
17117     deduced_args = innermost_deduced_args;
17118
17119   if (unify (tparms, deduced_args,
17120              INNERMOST_TEMPLATE_ARGS (spec_args),
17121              INNERMOST_TEMPLATE_ARGS (args),
17122              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17123     return NULL_TREE;
17124
17125   for (i =  0; i < ntparms; ++i)
17126     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17127       return NULL_TREE;
17128
17129   /* Verify that nondeduced template arguments agree with the type
17130      obtained from argument deduction.
17131
17132      For example:
17133
17134        struct A { typedef int X; };
17135        template <class T, class U> struct C {};
17136        template <class T> struct C<T, typename T::X> {};
17137
17138      Then with the instantiation `C<A, int>', we can deduce that
17139      `T' is `A' but unify () does not check whether `typename T::X'
17140      is `int'.  */
17141   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17142   if (spec_args == error_mark_node
17143       /* We only need to check the innermost arguments; the other
17144          arguments will always agree.  */
17145       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17146                               INNERMOST_TEMPLATE_ARGS (args)))
17147     return NULL_TREE;
17148
17149   /* Now that we have bindings for all of the template arguments,
17150      ensure that the arguments deduced for the template template
17151      parameters have compatible template parameter lists.  See the use
17152      of template_template_parm_bindings_ok_p in fn_type_unification
17153      for more information.  */
17154   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17155     return NULL_TREE;
17156
17157   return deduced_args;
17158 }
17159
17160 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17161    Return the TREE_LIST node with the most specialized template, if
17162    any.  If there is no most specialized template, the error_mark_node
17163    is returned.
17164
17165    Note that this function does not look at, or modify, the
17166    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17167    returned is one of the elements of INSTANTIATIONS, callers may
17168    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17169    and retrieve it from the value returned.  */
17170
17171 tree
17172 most_specialized_instantiation (tree templates)
17173 {
17174   tree fn, champ;
17175
17176   ++processing_template_decl;
17177
17178   champ = templates;
17179   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17180     {
17181       int fate = 0;
17182
17183       if (get_bindings (TREE_VALUE (champ),
17184                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17185                         NULL_TREE, /*check_ret=*/true))
17186         fate--;
17187
17188       if (get_bindings (TREE_VALUE (fn),
17189                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17190                         NULL_TREE, /*check_ret=*/true))
17191         fate++;
17192
17193       if (fate == -1)
17194         champ = fn;
17195       else if (!fate)
17196         {
17197           /* Equally specialized, move to next function.  If there
17198              is no next function, nothing's most specialized.  */
17199           fn = TREE_CHAIN (fn);
17200           champ = fn;
17201           if (!fn)
17202             break;
17203         }
17204     }
17205
17206   if (champ)
17207     /* Now verify that champ is better than everything earlier in the
17208        instantiation list.  */
17209     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17210       if (get_bindings (TREE_VALUE (champ),
17211                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17212                         NULL_TREE, /*check_ret=*/true)
17213           || !get_bindings (TREE_VALUE (fn),
17214                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17215                             NULL_TREE, /*check_ret=*/true))
17216         {
17217           champ = NULL_TREE;
17218           break;
17219         }
17220
17221   processing_template_decl--;
17222
17223   if (!champ)
17224     return error_mark_node;
17225
17226   return champ;
17227 }
17228
17229 /* If DECL is a specialization of some template, return the most
17230    general such template.  Otherwise, returns NULL_TREE.
17231
17232    For example, given:
17233
17234      template <class T> struct S { template <class U> void f(U); };
17235
17236    if TMPL is `template <class U> void S<int>::f(U)' this will return
17237    the full template.  This function will not trace past partial
17238    specializations, however.  For example, given in addition:
17239
17240      template <class T> struct S<T*> { template <class U> void f(U); };
17241
17242    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17243    `template <class T> template <class U> S<T*>::f(U)'.  */
17244
17245 tree
17246 most_general_template (tree decl)
17247 {
17248   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17249      an immediate specialization.  */
17250   if (TREE_CODE (decl) == FUNCTION_DECL)
17251     {
17252       if (DECL_TEMPLATE_INFO (decl)) {
17253         decl = DECL_TI_TEMPLATE (decl);
17254
17255         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17256            template friend.  */
17257         if (TREE_CODE (decl) != TEMPLATE_DECL)
17258           return NULL_TREE;
17259       } else
17260         return NULL_TREE;
17261     }
17262
17263   /* Look for more and more general templates.  */
17264   while (DECL_TEMPLATE_INFO (decl))
17265     {
17266       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17267          (See cp-tree.h for details.)  */
17268       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17269         break;
17270
17271       if (CLASS_TYPE_P (TREE_TYPE (decl))
17272           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17273         break;
17274
17275       /* Stop if we run into an explicitly specialized class template.  */
17276       if (!DECL_NAMESPACE_SCOPE_P (decl)
17277           && DECL_CONTEXT (decl)
17278           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17279         break;
17280
17281       decl = DECL_TI_TEMPLATE (decl);
17282     }
17283
17284   return decl;
17285 }
17286
17287 /* Return the most specialized of the class template partial
17288    specializations of TMPL which can produce TYPE, a specialization of
17289    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17290    a _TYPE node corresponding to the partial specialization, while the
17291    TREE_PURPOSE is the set of template arguments that must be
17292    substituted into the TREE_TYPE in order to generate TYPE.
17293
17294    If the choice of partial specialization is ambiguous, a diagnostic
17295    is issued, and the error_mark_node is returned.  If there are no
17296    partial specializations of TMPL matching TYPE, then NULL_TREE is
17297    returned.  */
17298
17299 static tree
17300 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17301 {
17302   tree list = NULL_TREE;
17303   tree t;
17304   tree champ;
17305   int fate;
17306   bool ambiguous_p;
17307   tree args;
17308   tree outer_args = NULL_TREE;
17309
17310   tmpl = most_general_template (tmpl);
17311   args = CLASSTYPE_TI_ARGS (type);
17312
17313   /* For determining which partial specialization to use, only the
17314      innermost args are interesting.  */
17315   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17316     {
17317       outer_args = strip_innermost_template_args (args, 1);
17318       args = INNERMOST_TEMPLATE_ARGS (args);
17319     }
17320
17321   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17322     {
17323       tree partial_spec_args;
17324       tree spec_args;
17325       tree parms = TREE_VALUE (t);
17326
17327       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17328
17329       ++processing_template_decl;
17330
17331       if (outer_args)
17332         {
17333           int i;
17334
17335           /* Discard the outer levels of args, and then substitute in the
17336              template args from the enclosing class.  */
17337           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17338           partial_spec_args = tsubst_template_args
17339             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17340
17341           /* PARMS already refers to just the innermost parms, but the
17342              template parms in partial_spec_args had their levels lowered
17343              by tsubst, so we need to do the same for the parm list.  We
17344              can't just tsubst the TREE_VEC itself, as tsubst wants to
17345              treat a TREE_VEC as an argument vector.  */
17346           parms = copy_node (parms);
17347           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17348             TREE_VEC_ELT (parms, i) =
17349               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17350
17351         }
17352
17353       partial_spec_args =
17354           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17355                                  add_to_template_args (outer_args,
17356                                                        partial_spec_args),
17357                                  tmpl, tf_none,
17358                                  /*require_all_args=*/true,
17359                                  /*use_default_args=*/true);
17360
17361       --processing_template_decl;
17362
17363       if (partial_spec_args == error_mark_node)
17364         return error_mark_node;
17365
17366       spec_args = get_class_bindings (parms,
17367                                       partial_spec_args,
17368                                       args);
17369       if (spec_args)
17370         {
17371           if (outer_args)
17372             spec_args = add_to_template_args (outer_args, spec_args);
17373           list = tree_cons (spec_args, TREE_VALUE (t), list);
17374           TREE_TYPE (list) = TREE_TYPE (t);
17375         }
17376     }
17377
17378   if (! list)
17379     return NULL_TREE;
17380
17381   ambiguous_p = false;
17382   t = list;
17383   champ = t;
17384   t = TREE_CHAIN (t);
17385   for (; t; t = TREE_CHAIN (t))
17386     {
17387       fate = more_specialized_class (champ, t);
17388       if (fate == 1)
17389         ;
17390       else
17391         {
17392           if (fate == 0)
17393             {
17394               t = TREE_CHAIN (t);
17395               if (! t)
17396                 {
17397                   ambiguous_p = true;
17398                   break;
17399                 }
17400             }
17401           champ = t;
17402         }
17403     }
17404
17405   if (!ambiguous_p)
17406     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17407       {
17408         fate = more_specialized_class (champ, t);
17409         if (fate != 1)
17410           {
17411             ambiguous_p = true;
17412             break;
17413           }
17414       }
17415
17416   if (ambiguous_p)
17417     {
17418       const char *str;
17419       char *spaces = NULL;
17420       if (!(complain & tf_error))
17421         return error_mark_node;
17422       error ("ambiguous class template instantiation for %q#T", type);
17423       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17424       for (t = list; t; t = TREE_CHAIN (t))
17425         {
17426           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17427           spaces = spaces ? spaces : get_spaces (str);
17428         }
17429       free (spaces);
17430       return error_mark_node;
17431     }
17432
17433   return champ;
17434 }
17435
17436 /* Explicitly instantiate DECL.  */
17437
17438 void
17439 do_decl_instantiation (tree decl, tree storage)
17440 {
17441   tree result = NULL_TREE;
17442   int extern_p = 0;
17443
17444   if (!decl || decl == error_mark_node)
17445     /* An error occurred, for which grokdeclarator has already issued
17446        an appropriate message.  */
17447     return;
17448   else if (! DECL_LANG_SPECIFIC (decl))
17449     {
17450       error ("explicit instantiation of non-template %q#D", decl);
17451       return;
17452     }
17453   else if (TREE_CODE (decl) == VAR_DECL)
17454     {
17455       /* There is an asymmetry here in the way VAR_DECLs and
17456          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17457          the latter, the DECL we get back will be marked as a
17458          template instantiation, and the appropriate
17459          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17460          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17461          should handle VAR_DECLs as it currently handles
17462          FUNCTION_DECLs.  */
17463       if (!DECL_CLASS_SCOPE_P (decl))
17464         {
17465           error ("%qD is not a static data member of a class template", decl);
17466           return;
17467         }
17468       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17469       if (!result || TREE_CODE (result) != VAR_DECL)
17470         {
17471           error ("no matching template for %qD found", decl);
17472           return;
17473         }
17474       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17475         {
17476           error ("type %qT for explicit instantiation %qD does not match "
17477                  "declared type %qT", TREE_TYPE (result), decl,
17478                  TREE_TYPE (decl));
17479           return;
17480         }
17481     }
17482   else if (TREE_CODE (decl) != FUNCTION_DECL)
17483     {
17484       error ("explicit instantiation of %q#D", decl);
17485       return;
17486     }
17487   else
17488     result = decl;
17489
17490   /* Check for various error cases.  Note that if the explicit
17491      instantiation is valid the RESULT will currently be marked as an
17492      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17493      until we get here.  */
17494
17495   if (DECL_TEMPLATE_SPECIALIZATION (result))
17496     {
17497       /* DR 259 [temp.spec].
17498
17499          Both an explicit instantiation and a declaration of an explicit
17500          specialization shall not appear in a program unless the explicit
17501          instantiation follows a declaration of the explicit specialization.
17502
17503          For a given set of template parameters, if an explicit
17504          instantiation of a template appears after a declaration of an
17505          explicit specialization for that template, the explicit
17506          instantiation has no effect.  */
17507       return;
17508     }
17509   else if (DECL_EXPLICIT_INSTANTIATION (result))
17510     {
17511       /* [temp.spec]
17512
17513          No program shall explicitly instantiate any template more
17514          than once.
17515
17516          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17517          the first instantiation was `extern' and the second is not,
17518          and EXTERN_P for the opposite case.  */
17519       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17520         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17521       /* If an "extern" explicit instantiation follows an ordinary
17522          explicit instantiation, the template is instantiated.  */
17523       if (extern_p)
17524         return;
17525     }
17526   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17527     {
17528       error ("no matching template for %qD found", result);
17529       return;
17530     }
17531   else if (!DECL_TEMPLATE_INFO (result))
17532     {
17533       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17534       return;
17535     }
17536
17537   if (storage == NULL_TREE)
17538     ;
17539   else if (storage == ridpointers[(int) RID_EXTERN])
17540     {
17541       if (!in_system_header && (cxx_dialect == cxx98))
17542         pedwarn (input_location, OPT_pedantic, 
17543                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17544                  "instantiations");
17545       extern_p = 1;
17546     }
17547   else
17548     error ("storage class %qD applied to template instantiation", storage);
17549
17550   check_explicit_instantiation_namespace (result);
17551   mark_decl_instantiated (result, extern_p);
17552   if (! extern_p)
17553     instantiate_decl (result, /*defer_ok=*/1,
17554                       /*expl_inst_class_mem_p=*/false);
17555 }
17556
17557 static void
17558 mark_class_instantiated (tree t, int extern_p)
17559 {
17560   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17561   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17562   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17563   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17564   if (! extern_p)
17565     {
17566       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17567       rest_of_type_compilation (t, 1);
17568     }
17569 }
17570
17571 /* Called from do_type_instantiation through binding_table_foreach to
17572    do recursive instantiation for the type bound in ENTRY.  */
17573 static void
17574 bt_instantiate_type_proc (binding_entry entry, void *data)
17575 {
17576   tree storage = *(tree *) data;
17577
17578   if (MAYBE_CLASS_TYPE_P (entry->type)
17579       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17580     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17581 }
17582
17583 /* Called from do_type_instantiation to instantiate a member
17584    (a member function or a static member variable) of an
17585    explicitly instantiated class template.  */
17586 static void
17587 instantiate_class_member (tree decl, int extern_p)
17588 {
17589   mark_decl_instantiated (decl, extern_p);
17590   if (! extern_p)
17591     instantiate_decl (decl, /*defer_ok=*/1,
17592                       /*expl_inst_class_mem_p=*/true);
17593 }
17594
17595 /* Perform an explicit instantiation of template class T.  STORAGE, if
17596    non-null, is the RID for extern, inline or static.  COMPLAIN is
17597    nonzero if this is called from the parser, zero if called recursively,
17598    since the standard is unclear (as detailed below).  */
17599
17600 void
17601 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17602 {
17603   int extern_p = 0;
17604   int nomem_p = 0;
17605   int static_p = 0;
17606   int previous_instantiation_extern_p = 0;
17607
17608   if (TREE_CODE (t) == TYPE_DECL)
17609     t = TREE_TYPE (t);
17610
17611   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17612     {
17613       error ("explicit instantiation of non-template type %qT", t);
17614       return;
17615     }
17616
17617   complete_type (t);
17618
17619   if (!COMPLETE_TYPE_P (t))
17620     {
17621       if (complain & tf_error)
17622         error ("explicit instantiation of %q#T before definition of template",
17623                t);
17624       return;
17625     }
17626
17627   if (storage != NULL_TREE)
17628     {
17629       if (!in_system_header)
17630         {
17631           if (storage == ridpointers[(int) RID_EXTERN])
17632             {
17633               if (cxx_dialect == cxx98)
17634                 pedwarn (input_location, OPT_pedantic, 
17635                          "ISO C++ 1998 forbids the use of %<extern%> on "
17636                          "explicit instantiations");
17637             }
17638           else
17639             pedwarn (input_location, OPT_pedantic, 
17640                      "ISO C++ forbids the use of %qE"
17641                      " on explicit instantiations", storage);
17642         }
17643
17644       if (storage == ridpointers[(int) RID_INLINE])
17645         nomem_p = 1;
17646       else if (storage == ridpointers[(int) RID_EXTERN])
17647         extern_p = 1;
17648       else if (storage == ridpointers[(int) RID_STATIC])
17649         static_p = 1;
17650       else
17651         {
17652           error ("storage class %qD applied to template instantiation",
17653                  storage);
17654           extern_p = 0;
17655         }
17656     }
17657
17658   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17659     {
17660       /* DR 259 [temp.spec].
17661
17662          Both an explicit instantiation and a declaration of an explicit
17663          specialization shall not appear in a program unless the explicit
17664          instantiation follows a declaration of the explicit specialization.
17665
17666          For a given set of template parameters, if an explicit
17667          instantiation of a template appears after a declaration of an
17668          explicit specialization for that template, the explicit
17669          instantiation has no effect.  */
17670       return;
17671     }
17672   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17673     {
17674       /* [temp.spec]
17675
17676          No program shall explicitly instantiate any template more
17677          than once.
17678
17679          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17680          instantiation was `extern'.  If EXTERN_P then the second is.
17681          These cases are OK.  */
17682       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17683
17684       if (!previous_instantiation_extern_p && !extern_p
17685           && (complain & tf_error))
17686         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17687
17688       /* If we've already instantiated the template, just return now.  */
17689       if (!CLASSTYPE_INTERFACE_ONLY (t))
17690         return;
17691     }
17692
17693   check_explicit_instantiation_namespace (TYPE_NAME (t));
17694   mark_class_instantiated (t, extern_p);
17695
17696   if (nomem_p)
17697     return;
17698
17699   {
17700     tree tmp;
17701
17702     /* In contrast to implicit instantiation, where only the
17703        declarations, and not the definitions, of members are
17704        instantiated, we have here:
17705
17706          [temp.explicit]
17707
17708          The explicit instantiation of a class template specialization
17709          implies the instantiation of all of its members not
17710          previously explicitly specialized in the translation unit
17711          containing the explicit instantiation.
17712
17713        Of course, we can't instantiate member template classes, since
17714        we don't have any arguments for them.  Note that the standard
17715        is unclear on whether the instantiation of the members are
17716        *explicit* instantiations or not.  However, the most natural
17717        interpretation is that it should be an explicit instantiation.  */
17718
17719     if (! static_p)
17720       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17721         if (TREE_CODE (tmp) == FUNCTION_DECL
17722             && DECL_TEMPLATE_INSTANTIATION (tmp))
17723           instantiate_class_member (tmp, extern_p);
17724
17725     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17726       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17727         instantiate_class_member (tmp, extern_p);
17728
17729     if (CLASSTYPE_NESTED_UTDS (t))
17730       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17731                              bt_instantiate_type_proc, &storage);
17732   }
17733 }
17734
17735 /* Given a function DECL, which is a specialization of TMPL, modify
17736    DECL to be a re-instantiation of TMPL with the same template
17737    arguments.  TMPL should be the template into which tsubst'ing
17738    should occur for DECL, not the most general template.
17739
17740    One reason for doing this is a scenario like this:
17741
17742      template <class T>
17743      void f(const T&, int i);
17744
17745      void g() { f(3, 7); }
17746
17747      template <class T>
17748      void f(const T& t, const int i) { }
17749
17750    Note that when the template is first instantiated, with
17751    instantiate_template, the resulting DECL will have no name for the
17752    first parameter, and the wrong type for the second.  So, when we go
17753    to instantiate the DECL, we regenerate it.  */
17754
17755 static void
17756 regenerate_decl_from_template (tree decl, tree tmpl)
17757 {
17758   /* The arguments used to instantiate DECL, from the most general
17759      template.  */
17760   tree args;
17761   tree code_pattern;
17762
17763   args = DECL_TI_ARGS (decl);
17764   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17765
17766   /* Make sure that we can see identifiers, and compute access
17767      correctly.  */
17768   push_access_scope (decl);
17769
17770   if (TREE_CODE (decl) == FUNCTION_DECL)
17771     {
17772       tree decl_parm;
17773       tree pattern_parm;
17774       tree specs;
17775       int args_depth;
17776       int parms_depth;
17777
17778       args_depth = TMPL_ARGS_DEPTH (args);
17779       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17780       if (args_depth > parms_depth)
17781         args = get_innermost_template_args (args, parms_depth);
17782
17783       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17784                                               args, tf_error, NULL_TREE,
17785                                               /*defer_ok*/false);
17786       if (specs && specs != error_mark_node)
17787         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17788                                                     specs);
17789
17790       /* Merge parameter declarations.  */
17791       decl_parm = skip_artificial_parms_for (decl,
17792                                              DECL_ARGUMENTS (decl));
17793       pattern_parm
17794         = skip_artificial_parms_for (code_pattern,
17795                                      DECL_ARGUMENTS (code_pattern));
17796       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17797         {
17798           tree parm_type;
17799           tree attributes;
17800           
17801           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17802             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17803           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17804                               NULL_TREE);
17805           parm_type = type_decays_to (parm_type);
17806           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17807             TREE_TYPE (decl_parm) = parm_type;
17808           attributes = DECL_ATTRIBUTES (pattern_parm);
17809           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17810             {
17811               DECL_ATTRIBUTES (decl_parm) = attributes;
17812               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17813             }
17814           decl_parm = DECL_CHAIN (decl_parm);
17815           pattern_parm = DECL_CHAIN (pattern_parm);
17816         }
17817       /* Merge any parameters that match with the function parameter
17818          pack.  */
17819       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17820         {
17821           int i, len;
17822           tree expanded_types;
17823           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17824              the parameters in this function parameter pack.  */
17825           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17826                                                  args, tf_error, NULL_TREE);
17827           len = TREE_VEC_LENGTH (expanded_types);
17828           for (i = 0; i < len; i++)
17829             {
17830               tree parm_type;
17831               tree attributes;
17832           
17833               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17834                 /* Rename the parameter to include the index.  */
17835                 DECL_NAME (decl_parm) = 
17836                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17837               parm_type = TREE_VEC_ELT (expanded_types, i);
17838               parm_type = type_decays_to (parm_type);
17839               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17840                 TREE_TYPE (decl_parm) = parm_type;
17841               attributes = DECL_ATTRIBUTES (pattern_parm);
17842               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17843                 {
17844                   DECL_ATTRIBUTES (decl_parm) = attributes;
17845                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17846                 }
17847               decl_parm = DECL_CHAIN (decl_parm);
17848             }
17849         }
17850       /* Merge additional specifiers from the CODE_PATTERN.  */
17851       if (DECL_DECLARED_INLINE_P (code_pattern)
17852           && !DECL_DECLARED_INLINE_P (decl))
17853         DECL_DECLARED_INLINE_P (decl) = 1;
17854     }
17855   else if (TREE_CODE (decl) == VAR_DECL)
17856     {
17857       DECL_INITIAL (decl) =
17858         tsubst_expr (DECL_INITIAL (code_pattern), args,
17859                      tf_error, DECL_TI_TEMPLATE (decl),
17860                      /*integral_constant_expression_p=*/false);
17861       if (VAR_HAD_UNKNOWN_BOUND (decl))
17862         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17863                                    tf_error, DECL_TI_TEMPLATE (decl));
17864     }
17865   else
17866     gcc_unreachable ();
17867
17868   pop_access_scope (decl);
17869 }
17870
17871 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17872    substituted to get DECL.  */
17873
17874 tree
17875 template_for_substitution (tree decl)
17876 {
17877   tree tmpl = DECL_TI_TEMPLATE (decl);
17878
17879   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17880      for the instantiation.  This is not always the most general
17881      template.  Consider, for example:
17882
17883         template <class T>
17884         struct S { template <class U> void f();
17885                    template <> void f<int>(); };
17886
17887      and an instantiation of S<double>::f<int>.  We want TD to be the
17888      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17889   while (/* An instantiation cannot have a definition, so we need a
17890             more general template.  */
17891          DECL_TEMPLATE_INSTANTIATION (tmpl)
17892            /* We must also deal with friend templates.  Given:
17893
17894                 template <class T> struct S {
17895                   template <class U> friend void f() {};
17896                 };
17897
17898               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17899               so far as the language is concerned, but that's still
17900               where we get the pattern for the instantiation from.  On
17901               other hand, if the definition comes outside the class, say:
17902
17903                 template <class T> struct S {
17904                   template <class U> friend void f();
17905                 };
17906                 template <class U> friend void f() {}
17907
17908               we don't need to look any further.  That's what the check for
17909               DECL_INITIAL is for.  */
17910           || (TREE_CODE (decl) == FUNCTION_DECL
17911               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17912               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17913     {
17914       /* The present template, TD, should not be a definition.  If it
17915          were a definition, we should be using it!  Note that we
17916          cannot restructure the loop to just keep going until we find
17917          a template with a definition, since that might go too far if
17918          a specialization was declared, but not defined.  */
17919       gcc_assert (TREE_CODE (decl) != VAR_DECL
17920                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17921
17922       /* Fetch the more general template.  */
17923       tmpl = DECL_TI_TEMPLATE (tmpl);
17924     }
17925
17926   return tmpl;
17927 }
17928
17929 /* Returns true if we need to instantiate this template instance even if we
17930    know we aren't going to emit it..  */
17931
17932 bool
17933 always_instantiate_p (tree decl)
17934 {
17935   /* We always instantiate inline functions so that we can inline them.  An
17936      explicit instantiation declaration prohibits implicit instantiation of
17937      non-inline functions.  With high levels of optimization, we would
17938      normally inline non-inline functions -- but we're not allowed to do
17939      that for "extern template" functions.  Therefore, we check
17940      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17941   return ((TREE_CODE (decl) == FUNCTION_DECL
17942            && DECL_DECLARED_INLINE_P (decl))
17943           /* And we need to instantiate static data members so that
17944              their initializers are available in integral constant
17945              expressions.  */
17946           || (TREE_CODE (decl) == VAR_DECL
17947               && decl_maybe_constant_var_p (decl)));
17948 }
17949
17950 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17951    instantiate it now, modifying TREE_TYPE (fn).  */
17952
17953 void
17954 maybe_instantiate_noexcept (tree fn)
17955 {
17956   tree fntype, spec, noex, clone;
17957
17958   if (DECL_CLONED_FUNCTION_P (fn))
17959     fn = DECL_CLONED_FUNCTION (fn);
17960   fntype = TREE_TYPE (fn);
17961   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17962
17963   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17964     return;
17965
17966   noex = TREE_PURPOSE (spec);
17967
17968   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17969     {
17970       push_tinst_level (fn);
17971       push_access_scope (fn);
17972       input_location = DECL_SOURCE_LOCATION (fn);
17973       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17974                                     DEFERRED_NOEXCEPT_ARGS (noex),
17975                                     tf_warning_or_error, fn, /*function_p=*/false,
17976                                     /*integral_constant_expression_p=*/true);
17977       pop_access_scope (fn);
17978       pop_tinst_level ();
17979       spec = build_noexcept_spec (noex, tf_warning_or_error);
17980       if (spec == error_mark_node)
17981         spec = noexcept_false_spec;
17982     }
17983   else
17984     {
17985       /* This is an implicitly declared function, so NOEX is a list of
17986          other functions to evaluate and merge.  */
17987       tree elt;
17988       spec = noexcept_true_spec;
17989       for (elt = noex; elt; elt = OVL_NEXT (elt))
17990         {
17991           tree fn = OVL_CURRENT (elt);
17992           tree subspec;
17993           maybe_instantiate_noexcept (fn);
17994           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17995           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17996         }
17997     }
17998
17999   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
18000
18001   FOR_EACH_CLONE (clone, fn)
18002     {
18003       if (TREE_TYPE (clone) == fntype)
18004         TREE_TYPE (clone) = TREE_TYPE (fn);
18005       else
18006         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
18007     }
18008 }
18009
18010 /* Produce the definition of D, a _DECL generated from a template.  If
18011    DEFER_OK is nonzero, then we don't have to actually do the
18012    instantiation now; we just have to do it sometime.  Normally it is
18013    an error if this is an explicit instantiation but D is undefined.
18014    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
18015    explicitly instantiated class template.  */
18016
18017 tree
18018 instantiate_decl (tree d, int defer_ok,
18019                   bool expl_inst_class_mem_p)
18020 {
18021   tree tmpl = DECL_TI_TEMPLATE (d);
18022   tree gen_args;
18023   tree args;
18024   tree td;
18025   tree code_pattern;
18026   tree spec;
18027   tree gen_tmpl;
18028   bool pattern_defined;
18029   int need_push;
18030   location_t saved_loc = input_location;
18031   bool external_p;
18032
18033   /* This function should only be used to instantiate templates for
18034      functions and static member variables.  */
18035   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18036               || TREE_CODE (d) == VAR_DECL);
18037
18038   /* Variables are never deferred; if instantiation is required, they
18039      are instantiated right away.  That allows for better code in the
18040      case that an expression refers to the value of the variable --
18041      if the variable has a constant value the referring expression can
18042      take advantage of that fact.  */
18043   if (TREE_CODE (d) == VAR_DECL
18044       || DECL_DECLARED_CONSTEXPR_P (d))
18045     defer_ok = 0;
18046
18047   /* Don't instantiate cloned functions.  Instead, instantiate the
18048      functions they cloned.  */
18049   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18050     d = DECL_CLONED_FUNCTION (d);
18051
18052   if (DECL_TEMPLATE_INSTANTIATED (d)
18053       || (TREE_CODE (d) == FUNCTION_DECL
18054           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
18055       || DECL_TEMPLATE_SPECIALIZATION (d))
18056     /* D has already been instantiated or explicitly specialized, so
18057        there's nothing for us to do here.
18058
18059        It might seem reasonable to check whether or not D is an explicit
18060        instantiation, and, if so, stop here.  But when an explicit
18061        instantiation is deferred until the end of the compilation,
18062        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18063        the instantiation.  */
18064     return d;
18065
18066   /* Check to see whether we know that this template will be
18067      instantiated in some other file, as with "extern template"
18068      extension.  */
18069   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18070
18071   /* In general, we do not instantiate such templates.  */
18072   if (external_p && !always_instantiate_p (d))
18073     return d;
18074
18075   gen_tmpl = most_general_template (tmpl);
18076   gen_args = DECL_TI_ARGS (d);
18077
18078   if (tmpl != gen_tmpl)
18079     /* We should already have the extra args.  */
18080     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18081                 == TMPL_ARGS_DEPTH (gen_args));
18082   /* And what's in the hash table should match D.  */
18083   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18084               || spec == NULL_TREE);
18085
18086   /* This needs to happen before any tsubsting.  */
18087   if (! push_tinst_level (d))
18088     return d;
18089
18090   timevar_push (TV_TEMPLATE_INST);
18091
18092   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18093      for the instantiation.  */
18094   td = template_for_substitution (d);
18095   code_pattern = DECL_TEMPLATE_RESULT (td);
18096
18097   /* We should never be trying to instantiate a member of a class
18098      template or partial specialization.  */
18099   gcc_assert (d != code_pattern);
18100
18101   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18102       || DECL_TEMPLATE_SPECIALIZATION (td))
18103     /* In the case of a friend template whose definition is provided
18104        outside the class, we may have too many arguments.  Drop the
18105        ones we don't need.  The same is true for specializations.  */
18106     args = get_innermost_template_args
18107       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18108   else
18109     args = gen_args;
18110
18111   if (TREE_CODE (d) == FUNCTION_DECL)
18112     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18113                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18114   else
18115     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18116
18117   /* We may be in the middle of deferred access check.  Disable it now.  */
18118   push_deferring_access_checks (dk_no_deferred);
18119
18120   /* Unless an explicit instantiation directive has already determined
18121      the linkage of D, remember that a definition is available for
18122      this entity.  */
18123   if (pattern_defined
18124       && !DECL_INTERFACE_KNOWN (d)
18125       && !DECL_NOT_REALLY_EXTERN (d))
18126     mark_definable (d);
18127
18128   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18129   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18130   input_location = DECL_SOURCE_LOCATION (d);
18131
18132   /* If D is a member of an explicitly instantiated class template,
18133      and no definition is available, treat it like an implicit
18134      instantiation.  */
18135   if (!pattern_defined && expl_inst_class_mem_p
18136       && DECL_EXPLICIT_INSTANTIATION (d))
18137     {
18138       /* Leave linkage flags alone on instantiations with anonymous
18139          visibility.  */
18140       if (TREE_PUBLIC (d))
18141         {
18142           DECL_NOT_REALLY_EXTERN (d) = 0;
18143           DECL_INTERFACE_KNOWN (d) = 0;
18144         }
18145       SET_DECL_IMPLICIT_INSTANTIATION (d);
18146     }
18147
18148   if (TREE_CODE (d) == FUNCTION_DECL)
18149     maybe_instantiate_noexcept (d);
18150
18151   /* Recheck the substitutions to obtain any warning messages
18152      about ignoring cv qualifiers.  Don't do this for artificial decls,
18153      as it breaks the context-sensitive substitution for lambda op(). */
18154   if (!defer_ok && !DECL_ARTIFICIAL (d))
18155     {
18156       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18157       tree type = TREE_TYPE (gen);
18158
18159       /* Make sure that we can see identifiers, and compute access
18160          correctly.  D is already the target FUNCTION_DECL with the
18161          right context.  */
18162       push_access_scope (d);
18163
18164       if (TREE_CODE (gen) == FUNCTION_DECL)
18165         {
18166           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18167           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18168                                           d, /*defer_ok*/true);
18169           /* Don't simply tsubst the function type, as that will give
18170              duplicate warnings about poor parameter qualifications.
18171              The function arguments are the same as the decl_arguments
18172              without the top level cv qualifiers.  */
18173           type = TREE_TYPE (type);
18174         }
18175       tsubst (type, gen_args, tf_warning_or_error, d);
18176
18177       pop_access_scope (d);
18178     }
18179
18180   /* Defer all other templates, unless we have been explicitly
18181      forbidden from doing so.  */
18182   if (/* If there is no definition, we cannot instantiate the
18183          template.  */
18184       ! pattern_defined
18185       /* If it's OK to postpone instantiation, do so.  */
18186       || defer_ok
18187       /* If this is a static data member that will be defined
18188          elsewhere, we don't want to instantiate the entire data
18189          member, but we do want to instantiate the initializer so that
18190          we can substitute that elsewhere.  */
18191       || (external_p && TREE_CODE (d) == VAR_DECL))
18192     {
18193       /* The definition of the static data member is now required so
18194          we must substitute the initializer.  */
18195       if (TREE_CODE (d) == VAR_DECL
18196           && !DECL_INITIAL (d)
18197           && DECL_INITIAL (code_pattern))
18198         {
18199           tree ns;
18200           tree init;
18201           bool const_init = false;
18202
18203           ns = decl_namespace_context (d);
18204           push_nested_namespace (ns);
18205           push_nested_class (DECL_CONTEXT (d));
18206           init = tsubst_expr (DECL_INITIAL (code_pattern),
18207                               args,
18208                               tf_warning_or_error, NULL_TREE,
18209                               /*integral_constant_expression_p=*/false);
18210           /* Make sure the initializer is still constant, in case of
18211              circular dependency (template/instantiate6.C). */
18212           const_init
18213             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18214           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18215                           /*asmspec_tree=*/NULL_TREE,
18216                           LOOKUP_ONLYCONVERTING);
18217           pop_nested_class ();
18218           pop_nested_namespace (ns);
18219         }
18220
18221       /* We restore the source position here because it's used by
18222          add_pending_template.  */
18223       input_location = saved_loc;
18224
18225       if (at_eof && !pattern_defined
18226           && DECL_EXPLICIT_INSTANTIATION (d)
18227           && DECL_NOT_REALLY_EXTERN (d))
18228         /* [temp.explicit]
18229
18230            The definition of a non-exported function template, a
18231            non-exported member function template, or a non-exported
18232            member function or static data member of a class template
18233            shall be present in every translation unit in which it is
18234            explicitly instantiated.  */
18235         permerror (input_location,  "explicit instantiation of %qD "
18236                    "but no definition available", d);
18237
18238       /* If we're in unevaluated context, we just wanted to get the
18239          constant value; this isn't an odr use, so don't queue
18240          a full instantiation.  */
18241       if (cp_unevaluated_operand != 0)
18242         goto out;
18243       /* ??? Historically, we have instantiated inline functions, even
18244          when marked as "extern template".  */
18245       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18246         add_pending_template (d);
18247       goto out;
18248     }
18249   /* Tell the repository that D is available in this translation unit
18250      -- and see if it is supposed to be instantiated here.  */
18251   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18252     {
18253       /* In a PCH file, despite the fact that the repository hasn't
18254          requested instantiation in the PCH it is still possible that
18255          an instantiation will be required in a file that includes the
18256          PCH.  */
18257       if (pch_file)
18258         add_pending_template (d);
18259       /* Instantiate inline functions so that the inliner can do its
18260          job, even though we'll not be emitting a copy of this
18261          function.  */
18262       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18263         goto out;
18264     }
18265
18266   need_push = !cfun || !global_bindings_p ();
18267   if (need_push)
18268     push_to_top_level ();
18269
18270   /* Mark D as instantiated so that recursive calls to
18271      instantiate_decl do not try to instantiate it again.  */
18272   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18273
18274   /* Regenerate the declaration in case the template has been modified
18275      by a subsequent redeclaration.  */
18276   regenerate_decl_from_template (d, td);
18277
18278   /* We already set the file and line above.  Reset them now in case
18279      they changed as a result of calling regenerate_decl_from_template.  */
18280   input_location = DECL_SOURCE_LOCATION (d);
18281
18282   if (TREE_CODE (d) == VAR_DECL)
18283     {
18284       tree init;
18285       bool const_init = false;
18286
18287       /* Clear out DECL_RTL; whatever was there before may not be right
18288          since we've reset the type of the declaration.  */
18289       SET_DECL_RTL (d, NULL);
18290       DECL_IN_AGGR_P (d) = 0;
18291
18292       /* The initializer is placed in DECL_INITIAL by
18293          regenerate_decl_from_template so we don't need to
18294          push/pop_access_scope again here.  Pull it out so that
18295          cp_finish_decl can process it.  */
18296       init = DECL_INITIAL (d);
18297       DECL_INITIAL (d) = NULL_TREE;
18298       DECL_INITIALIZED_P (d) = 0;
18299
18300       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18301          initializer.  That function will defer actual emission until
18302          we have a chance to determine linkage.  */
18303       DECL_EXTERNAL (d) = 0;
18304
18305       /* Enter the scope of D so that access-checking works correctly.  */
18306       push_nested_class (DECL_CONTEXT (d));
18307       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18308       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18309       pop_nested_class ();
18310     }
18311   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18312     synthesize_method (d);
18313   else if (TREE_CODE (d) == FUNCTION_DECL)
18314     {
18315       htab_t saved_local_specializations;
18316       tree subst_decl;
18317       tree tmpl_parm;
18318       tree spec_parm;
18319
18320       /* Save away the current list, in case we are instantiating one
18321          template from within the body of another.  */
18322       saved_local_specializations = local_specializations;
18323
18324       /* Set up the list of local specializations.  */
18325       local_specializations = htab_create (37,
18326                                            hash_local_specialization,
18327                                            eq_local_specializations,
18328                                            NULL);
18329
18330       /* Set up context.  */
18331       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18332
18333       /* Create substitution entries for the parameters.  */
18334       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18335       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18336       spec_parm = DECL_ARGUMENTS (d);
18337       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18338         {
18339           register_local_specialization (spec_parm, tmpl_parm);
18340           spec_parm = skip_artificial_parms_for (d, spec_parm);
18341           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18342         }
18343       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18344         {
18345           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18346             {
18347               register_local_specialization (spec_parm, tmpl_parm);
18348               spec_parm = DECL_CHAIN (spec_parm);
18349             }
18350           else
18351             {
18352               /* Register the (value) argument pack as a specialization of
18353                  TMPL_PARM, then move on.  */
18354               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18355               register_local_specialization (argpack, tmpl_parm);
18356             }
18357         }
18358       gcc_assert (!spec_parm);
18359
18360       /* Substitute into the body of the function.  */
18361       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18362                    tf_warning_or_error, tmpl,
18363                    /*integral_constant_expression_p=*/false);
18364
18365       /* Set the current input_location to the end of the function
18366          so that finish_function knows where we are.  */
18367       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18368
18369       /* We don't need the local specializations any more.  */
18370       htab_delete (local_specializations);
18371       local_specializations = saved_local_specializations;
18372
18373       /* Finish the function.  */
18374       d = finish_function (0);
18375       expand_or_defer_fn (d);
18376     }
18377
18378   /* We're not deferring instantiation any more.  */
18379   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18380
18381   if (need_push)
18382     pop_from_top_level ();
18383
18384 out:
18385   input_location = saved_loc;
18386   pop_deferring_access_checks ();
18387   pop_tinst_level ();
18388
18389   timevar_pop (TV_TEMPLATE_INST);
18390
18391   return d;
18392 }
18393
18394 /* Run through the list of templates that we wish we could
18395    instantiate, and instantiate any we can.  RETRIES is the
18396    number of times we retry pending template instantiation.  */
18397
18398 void
18399 instantiate_pending_templates (int retries)
18400 {
18401   int reconsider;
18402   location_t saved_loc = input_location;
18403
18404   /* Instantiating templates may trigger vtable generation.  This in turn
18405      may require further template instantiations.  We place a limit here
18406      to avoid infinite loop.  */
18407   if (pending_templates && retries >= max_tinst_depth)
18408     {
18409       tree decl = pending_templates->tinst->decl;
18410
18411       error ("template instantiation depth exceeds maximum of %d"
18412              " instantiating %q+D, possibly from virtual table generation"
18413              " (use -ftemplate-depth= to increase the maximum)",
18414              max_tinst_depth, decl);
18415       if (TREE_CODE (decl) == FUNCTION_DECL)
18416         /* Pretend that we defined it.  */
18417         DECL_INITIAL (decl) = error_mark_node;
18418       return;
18419     }
18420
18421   do
18422     {
18423       struct pending_template **t = &pending_templates;
18424       struct pending_template *last = NULL;
18425       reconsider = 0;
18426       while (*t)
18427         {
18428           tree instantiation = reopen_tinst_level ((*t)->tinst);
18429           bool complete = false;
18430
18431           if (TYPE_P (instantiation))
18432             {
18433               tree fn;
18434
18435               if (!COMPLETE_TYPE_P (instantiation))
18436                 {
18437                   instantiate_class_template (instantiation);
18438                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18439                     for (fn = TYPE_METHODS (instantiation);
18440                          fn;
18441                          fn = TREE_CHAIN (fn))
18442                       if (! DECL_ARTIFICIAL (fn))
18443                         instantiate_decl (fn,
18444                                           /*defer_ok=*/0,
18445                                           /*expl_inst_class_mem_p=*/false);
18446                   if (COMPLETE_TYPE_P (instantiation))
18447                     reconsider = 1;
18448                 }
18449
18450               complete = COMPLETE_TYPE_P (instantiation);
18451             }
18452           else
18453             {
18454               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18455                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18456                 {
18457                   instantiation
18458                     = instantiate_decl (instantiation,
18459                                         /*defer_ok=*/0,
18460                                         /*expl_inst_class_mem_p=*/false);
18461                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18462                     reconsider = 1;
18463                 }
18464
18465               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18466                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18467             }
18468
18469           if (complete)
18470             /* If INSTANTIATION has been instantiated, then we don't
18471                need to consider it again in the future.  */
18472             *t = (*t)->next;
18473           else
18474             {
18475               last = *t;
18476               t = &(*t)->next;
18477             }
18478           tinst_depth = 0;
18479           current_tinst_level = NULL;
18480         }
18481       last_pending_template = last;
18482     }
18483   while (reconsider);
18484
18485   input_location = saved_loc;
18486 }
18487
18488 /* Substitute ARGVEC into T, which is a list of initializers for
18489    either base class or a non-static data member.  The TREE_PURPOSEs
18490    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18491    instantiate_decl.  */
18492
18493 static tree
18494 tsubst_initializer_list (tree t, tree argvec)
18495 {
18496   tree inits = NULL_TREE;
18497
18498   for (; t; t = TREE_CHAIN (t))
18499     {
18500       tree decl;
18501       tree init;
18502       tree expanded_bases = NULL_TREE;
18503       tree expanded_arguments = NULL_TREE;
18504       int i, len = 1;
18505
18506       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18507         {
18508           tree expr;
18509           tree arg;
18510
18511           /* Expand the base class expansion type into separate base
18512              classes.  */
18513           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18514                                                  tf_warning_or_error,
18515                                                  NULL_TREE);
18516           if (expanded_bases == error_mark_node)
18517             continue;
18518           
18519           /* We'll be building separate TREE_LISTs of arguments for
18520              each base.  */
18521           len = TREE_VEC_LENGTH (expanded_bases);
18522           expanded_arguments = make_tree_vec (len);
18523           for (i = 0; i < len; i++)
18524             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18525
18526           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18527              expand each argument in the TREE_VALUE of t.  */
18528           expr = make_node (EXPR_PACK_EXPANSION);
18529           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18530             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18531
18532           if (TREE_VALUE (t) == void_type_node)
18533             /* VOID_TYPE_NODE is used to indicate
18534                value-initialization.  */
18535             {
18536               for (i = 0; i < len; i++)
18537                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18538             }
18539           else
18540             {
18541               /* Substitute parameter packs into each argument in the
18542                  TREE_LIST.  */
18543               in_base_initializer = 1;
18544               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18545                 {
18546                   tree expanded_exprs;
18547
18548                   /* Expand the argument.  */
18549                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18550                   expanded_exprs 
18551                     = tsubst_pack_expansion (expr, argvec,
18552                                              tf_warning_or_error,
18553                                              NULL_TREE);
18554                   if (expanded_exprs == error_mark_node)
18555                     continue;
18556
18557                   /* Prepend each of the expanded expressions to the
18558                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18559                   for (i = 0; i < len; i++)
18560                     {
18561                       TREE_VEC_ELT (expanded_arguments, i) = 
18562                         tree_cons (NULL_TREE, 
18563                                    TREE_VEC_ELT (expanded_exprs, i),
18564                                    TREE_VEC_ELT (expanded_arguments, i));
18565                     }
18566                 }
18567               in_base_initializer = 0;
18568
18569               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18570                  since we built them backwards.  */
18571               for (i = 0; i < len; i++)
18572                 {
18573                   TREE_VEC_ELT (expanded_arguments, i) = 
18574                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18575                 }
18576             }
18577         }
18578
18579       for (i = 0; i < len; ++i)
18580         {
18581           if (expanded_bases)
18582             {
18583               decl = TREE_VEC_ELT (expanded_bases, i);
18584               decl = expand_member_init (decl);
18585               init = TREE_VEC_ELT (expanded_arguments, i);
18586             }
18587           else
18588             {
18589               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18590                                   tf_warning_or_error, NULL_TREE);
18591
18592               decl = expand_member_init (decl);
18593               if (decl && !DECL_P (decl))
18594                 in_base_initializer = 1;
18595
18596               init = TREE_VALUE (t);
18597               if (init != void_type_node)
18598                 init = tsubst_expr (init, argvec,
18599                                     tf_warning_or_error, NULL_TREE,
18600                                     /*integral_constant_expression_p=*/false);
18601               in_base_initializer = 0;
18602             }
18603
18604           if (decl)
18605             {
18606               init = build_tree_list (decl, init);
18607               TREE_CHAIN (init) = inits;
18608               inits = init;
18609             }
18610         }
18611     }
18612   return inits;
18613 }
18614
18615 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18616
18617 static void
18618 set_current_access_from_decl (tree decl)
18619 {
18620   if (TREE_PRIVATE (decl))
18621     current_access_specifier = access_private_node;
18622   else if (TREE_PROTECTED (decl))
18623     current_access_specifier = access_protected_node;
18624   else
18625     current_access_specifier = access_public_node;
18626 }
18627
18628 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18629    is the instantiation (which should have been created with
18630    start_enum) and ARGS are the template arguments to use.  */
18631
18632 static void
18633 tsubst_enum (tree tag, tree newtag, tree args)
18634 {
18635   tree e;
18636
18637   if (SCOPED_ENUM_P (newtag))
18638     begin_scope (sk_scoped_enum, newtag);
18639
18640   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18641     {
18642       tree value;
18643       tree decl;
18644
18645       decl = TREE_VALUE (e);
18646       /* Note that in a template enum, the TREE_VALUE is the
18647          CONST_DECL, not the corresponding INTEGER_CST.  */
18648       value = tsubst_expr (DECL_INITIAL (decl),
18649                            args, tf_warning_or_error, NULL_TREE,
18650                            /*integral_constant_expression_p=*/true);
18651
18652       /* Give this enumeration constant the correct access.  */
18653       set_current_access_from_decl (decl);
18654
18655       /* Actually build the enumerator itself.  */
18656       build_enumerator
18657         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18658     }
18659
18660   if (SCOPED_ENUM_P (newtag))
18661     finish_scope ();
18662
18663   finish_enum_value_list (newtag);
18664   finish_enum (newtag);
18665
18666   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18667     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18668 }
18669
18670 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18671    its type -- but without substituting the innermost set of template
18672    arguments.  So, innermost set of template parameters will appear in
18673    the type.  */
18674
18675 tree
18676 get_mostly_instantiated_function_type (tree decl)
18677 {
18678   tree fn_type;
18679   tree tmpl;
18680   tree targs;
18681   tree tparms;
18682   int parm_depth;
18683
18684   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18685   targs = DECL_TI_ARGS (decl);
18686   tparms = DECL_TEMPLATE_PARMS (tmpl);
18687   parm_depth = TMPL_PARMS_DEPTH (tparms);
18688
18689   /* There should be as many levels of arguments as there are levels
18690      of parameters.  */
18691   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18692
18693   fn_type = TREE_TYPE (tmpl);
18694
18695   if (parm_depth == 1)
18696     /* No substitution is necessary.  */
18697     ;
18698   else
18699     {
18700       int i;
18701       tree partial_args;
18702
18703       /* Replace the innermost level of the TARGS with NULL_TREEs to
18704          let tsubst know not to substitute for those parameters.  */
18705       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18706       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18707         SET_TMPL_ARGS_LEVEL (partial_args, i,
18708                              TMPL_ARGS_LEVEL (targs, i));
18709       SET_TMPL_ARGS_LEVEL (partial_args,
18710                            TMPL_ARGS_DEPTH (targs),
18711                            make_tree_vec (DECL_NTPARMS (tmpl)));
18712
18713       /* Make sure that we can see identifiers, and compute access
18714          correctly.  */
18715       push_access_scope (decl);
18716
18717       ++processing_template_decl;
18718       /* Now, do the (partial) substitution to figure out the
18719          appropriate function type.  */
18720       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18721       --processing_template_decl;
18722
18723       /* Substitute into the template parameters to obtain the real
18724          innermost set of parameters.  This step is important if the
18725          innermost set of template parameters contains value
18726          parameters whose types depend on outer template parameters.  */
18727       TREE_VEC_LENGTH (partial_args)--;
18728       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18729
18730       pop_access_scope (decl);
18731     }
18732
18733   return fn_type;
18734 }
18735
18736 /* Return truthvalue if we're processing a template different from
18737    the last one involved in diagnostics.  */
18738 int
18739 problematic_instantiation_changed (void)
18740 {
18741   return current_tinst_level != last_error_tinst_level;
18742 }
18743
18744 /* Remember current template involved in diagnostics.  */
18745 void
18746 record_last_problematic_instantiation (void)
18747 {
18748   last_error_tinst_level = current_tinst_level;
18749 }
18750
18751 struct tinst_level *
18752 current_instantiation (void)
18753 {
18754   return current_tinst_level;
18755 }
18756
18757 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18758    type. Return zero for ok, nonzero for disallowed. Issue error and
18759    warning messages under control of COMPLAIN.  */
18760
18761 static int
18762 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18763 {
18764   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18765     return 0;
18766   else if (POINTER_TYPE_P (type))
18767     return 0;
18768   else if (TYPE_PTR_TO_MEMBER_P (type))
18769     return 0;
18770   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18771     return 0;
18772   else if (TREE_CODE (type) == TYPENAME_TYPE)
18773     return 0;
18774   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18775     return 0;
18776   else if (TREE_CODE (type) == NULLPTR_TYPE)
18777     return 0;
18778
18779   if (complain & tf_error)
18780     error ("%q#T is not a valid type for a template constant parameter", type);
18781   return 1;
18782 }
18783
18784 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18785    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18786
18787 static bool
18788 dependent_type_p_r (tree type)
18789 {
18790   tree scope;
18791
18792   /* [temp.dep.type]
18793
18794      A type is dependent if it is:
18795
18796      -- a template parameter. Template template parameters are types
18797         for us (since TYPE_P holds true for them) so we handle
18798         them here.  */
18799   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18800       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18801     return true;
18802   /* -- a qualified-id with a nested-name-specifier which contains a
18803         class-name that names a dependent type or whose unqualified-id
18804         names a dependent type.  */
18805   if (TREE_CODE (type) == TYPENAME_TYPE)
18806     return true;
18807   /* -- a cv-qualified type where the cv-unqualified type is
18808         dependent.  */
18809   type = TYPE_MAIN_VARIANT (type);
18810   /* -- a compound type constructed from any dependent type.  */
18811   if (TYPE_PTR_TO_MEMBER_P (type))
18812     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18813             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18814                                            (type)));
18815   else if (TREE_CODE (type) == POINTER_TYPE
18816            || TREE_CODE (type) == REFERENCE_TYPE)
18817     return dependent_type_p (TREE_TYPE (type));
18818   else if (TREE_CODE (type) == FUNCTION_TYPE
18819            || TREE_CODE (type) == METHOD_TYPE)
18820     {
18821       tree arg_type;
18822
18823       if (dependent_type_p (TREE_TYPE (type)))
18824         return true;
18825       for (arg_type = TYPE_ARG_TYPES (type);
18826            arg_type;
18827            arg_type = TREE_CHAIN (arg_type))
18828         if (dependent_type_p (TREE_VALUE (arg_type)))
18829           return true;
18830       return false;
18831     }
18832   /* -- an array type constructed from any dependent type or whose
18833         size is specified by a constant expression that is
18834         value-dependent.
18835
18836         We checked for type- and value-dependence of the bounds in
18837         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18838   if (TREE_CODE (type) == ARRAY_TYPE)
18839     {
18840       if (TYPE_DOMAIN (type)
18841           && dependent_type_p (TYPE_DOMAIN (type)))
18842         return true;
18843       return dependent_type_p (TREE_TYPE (type));
18844     }
18845
18846   /* -- a template-id in which either the template name is a template
18847      parameter ...  */
18848   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18849     return true;
18850   /* ... or any of the template arguments is a dependent type or
18851         an expression that is type-dependent or value-dependent.  */
18852   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18853            && (any_dependent_template_arguments_p
18854                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18855     return true;
18856
18857   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18858      dependent; if the argument of the `typeof' expression is not
18859      type-dependent, then it should already been have resolved.  */
18860   if (TREE_CODE (type) == TYPEOF_TYPE
18861       || TREE_CODE (type) == DECLTYPE_TYPE
18862       || TREE_CODE (type) == UNDERLYING_TYPE)
18863     return true;
18864
18865   /* A template argument pack is dependent if any of its packed
18866      arguments are.  */
18867   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18868     {
18869       tree args = ARGUMENT_PACK_ARGS (type);
18870       int i, len = TREE_VEC_LENGTH (args);
18871       for (i = 0; i < len; ++i)
18872         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18873           return true;
18874     }
18875
18876   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18877      be template parameters.  */
18878   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18879     return true;
18880
18881   /* The standard does not specifically mention types that are local
18882      to template functions or local classes, but they should be
18883      considered dependent too.  For example:
18884
18885        template <int I> void f() {
18886          enum E { a = I };
18887          S<sizeof (E)> s;
18888        }
18889
18890      The size of `E' cannot be known until the value of `I' has been
18891      determined.  Therefore, `E' must be considered dependent.  */
18892   scope = TYPE_CONTEXT (type);
18893   if (scope && TYPE_P (scope))
18894     return dependent_type_p (scope);
18895   /* Don't use type_dependent_expression_p here, as it can lead
18896      to infinite recursion trying to determine whether a lambda
18897      nested in a lambda is dependent (c++/47687).  */
18898   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18899            && DECL_LANG_SPECIFIC (scope)
18900            && DECL_TEMPLATE_INFO (scope)
18901            && (any_dependent_template_arguments_p
18902                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18903     return true;
18904
18905   /* Other types are non-dependent.  */
18906   return false;
18907 }
18908
18909 /* Returns TRUE if TYPE is dependent, in the sense of
18910    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18911
18912 bool
18913 dependent_type_p (tree type)
18914 {
18915   /* If there are no template parameters in scope, then there can't be
18916      any dependent types.  */
18917   if (!processing_template_decl)
18918     {
18919       /* If we are not processing a template, then nobody should be
18920          providing us with a dependent type.  */
18921       gcc_assert (type);
18922       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18923       return false;
18924     }
18925
18926   /* If the type is NULL, we have not computed a type for the entity
18927      in question; in that case, the type is dependent.  */
18928   if (!type)
18929     return true;
18930
18931   /* Erroneous types can be considered non-dependent.  */
18932   if (type == error_mark_node)
18933     return false;
18934
18935   /* If we have not already computed the appropriate value for TYPE,
18936      do so now.  */
18937   if (!TYPE_DEPENDENT_P_VALID (type))
18938     {
18939       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18940       TYPE_DEPENDENT_P_VALID (type) = 1;
18941     }
18942
18943   return TYPE_DEPENDENT_P (type);
18944 }
18945
18946 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18947    lookup.  In other words, a dependent type that is not the current
18948    instantiation.  */
18949
18950 bool
18951 dependent_scope_p (tree scope)
18952 {
18953   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18954           && !currently_open_class (scope));
18955 }
18956
18957 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18958    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18959    expression.  */
18960
18961 /* Note that this predicate is not appropriate for general expressions;
18962    only constant expressions (that satisfy potential_constant_expression)
18963    can be tested for value dependence.
18964
18965    We should really also have a predicate for "instantiation-dependent".
18966
18967    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18968      (what about instantiation-dependent constant-expressions?)
18969    is_late_template_attribute: defer if instantiation-dependent.
18970    compute_array_index_type: proceed if constant and not t- or v-dependent
18971      if instantiation-dependent, need to remember full expression
18972    uses_template_parms: FIXME - need to audit callers
18973    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18974    dependent_type_p [array_type]: dependent if index type is dependent
18975      (or non-constant?)
18976    static_assert - instantiation-dependent */
18977
18978 bool
18979 value_dependent_expression_p (tree expression)
18980 {
18981   if (!processing_template_decl)
18982     return false;
18983
18984   /* A name declared with a dependent type.  */
18985   if (DECL_P (expression) && type_dependent_expression_p (expression))
18986     return true;
18987
18988   switch (TREE_CODE (expression))
18989     {
18990     case IDENTIFIER_NODE:
18991       /* A name that has not been looked up -- must be dependent.  */
18992       return true;
18993
18994     case TEMPLATE_PARM_INDEX:
18995       /* A non-type template parm.  */
18996       return true;
18997
18998     case CONST_DECL:
18999       /* A non-type template parm.  */
19000       if (DECL_TEMPLATE_PARM_P (expression))
19001         return true;
19002       return value_dependent_expression_p (DECL_INITIAL (expression));
19003
19004     case VAR_DECL:
19005        /* A constant with literal type and is initialized
19006           with an expression that is value-dependent.  */
19007       if (DECL_INITIAL (expression)
19008           && decl_constant_var_p (expression)
19009           && value_dependent_expression_p (DECL_INITIAL (expression)))
19010         return true;
19011       return false;
19012
19013     case DYNAMIC_CAST_EXPR:
19014     case STATIC_CAST_EXPR:
19015     case CONST_CAST_EXPR:
19016     case REINTERPRET_CAST_EXPR:
19017     case CAST_EXPR:
19018       /* These expressions are value-dependent if the type to which
19019          the cast occurs is dependent or the expression being casted
19020          is value-dependent.  */
19021       {
19022         tree type = TREE_TYPE (expression);
19023
19024         if (dependent_type_p (type))
19025           return true;
19026
19027         /* A functional cast has a list of operands.  */
19028         expression = TREE_OPERAND (expression, 0);
19029         if (!expression)
19030           {
19031             /* If there are no operands, it must be an expression such
19032                as "int()". This should not happen for aggregate types
19033                because it would form non-constant expressions.  */
19034             gcc_assert (cxx_dialect >= cxx0x
19035                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19036
19037             return false;
19038           }
19039
19040         if (TREE_CODE (expression) == TREE_LIST)
19041           return any_value_dependent_elements_p (expression);
19042
19043         return value_dependent_expression_p (expression);
19044       }
19045
19046     case SIZEOF_EXPR:
19047     case ALIGNOF_EXPR:
19048     case TYPEID_EXPR:
19049       /* A `sizeof' expression is value-dependent if the operand is
19050          type-dependent or is a pack expansion.  */
19051       expression = TREE_OPERAND (expression, 0);
19052       if (PACK_EXPANSION_P (expression))
19053         return true;
19054       else if (TYPE_P (expression))
19055         return dependent_type_p (expression);
19056       return type_dependent_expression_p (expression);
19057
19058     case AT_ENCODE_EXPR:
19059       /* An 'encode' expression is value-dependent if the operand is
19060          type-dependent.  */
19061       expression = TREE_OPERAND (expression, 0);
19062       return dependent_type_p (expression);
19063
19064     case NOEXCEPT_EXPR:
19065       expression = TREE_OPERAND (expression, 0);
19066       return type_dependent_expression_p (expression);
19067
19068     case SCOPE_REF:
19069       {
19070         tree name = TREE_OPERAND (expression, 1);
19071         return value_dependent_expression_p (name);
19072       }
19073
19074     case COMPONENT_REF:
19075       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19076               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19077
19078     case NONTYPE_ARGUMENT_PACK:
19079       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19080          is value-dependent.  */
19081       {
19082         tree values = ARGUMENT_PACK_ARGS (expression);
19083         int i, len = TREE_VEC_LENGTH (values);
19084         
19085         for (i = 0; i < len; ++i)
19086           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19087             return true;
19088         
19089         return false;
19090       }
19091
19092     case TRAIT_EXPR:
19093       {
19094         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19095         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19096                 || (type2 ? dependent_type_p (type2) : false));
19097       }
19098
19099     case MODOP_EXPR:
19100       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19101               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19102
19103     case ARRAY_REF:
19104       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19105               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19106
19107     case ADDR_EXPR:
19108       {
19109         tree op = TREE_OPERAND (expression, 0);
19110         return (value_dependent_expression_p (op)
19111                 || has_value_dependent_address (op));
19112       }
19113
19114     case CALL_EXPR:
19115       {
19116         tree fn = get_callee_fndecl (expression);
19117         int i, nargs;
19118         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19119           return true;
19120         nargs = call_expr_nargs (expression);
19121         for (i = 0; i < nargs; ++i)
19122           {
19123             tree op = CALL_EXPR_ARG (expression, i);
19124             /* In a call to a constexpr member function, look through the
19125                implicit ADDR_EXPR on the object argument so that it doesn't
19126                cause the call to be considered value-dependent.  We also
19127                look through it in potential_constant_expression.  */
19128             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19129                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19130                 && TREE_CODE (op) == ADDR_EXPR)
19131               op = TREE_OPERAND (op, 0);
19132             if (value_dependent_expression_p (op))
19133               return true;
19134           }
19135         return false;
19136       }
19137
19138     case TEMPLATE_ID_EXPR:
19139       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19140          type-dependent.  */
19141       return type_dependent_expression_p (expression);
19142
19143     case CONSTRUCTOR:
19144       {
19145         unsigned ix;
19146         tree val;
19147         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19148           if (value_dependent_expression_p (val))
19149             return true;
19150         return false;
19151       }
19152
19153     default:
19154       /* A constant expression is value-dependent if any subexpression is
19155          value-dependent.  */
19156       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19157         {
19158         case tcc_reference:
19159         case tcc_unary:
19160         case tcc_comparison:
19161         case tcc_binary:
19162         case tcc_expression:
19163         case tcc_vl_exp:
19164           {
19165             int i, len = cp_tree_operand_length (expression);
19166
19167             for (i = 0; i < len; i++)
19168               {
19169                 tree t = TREE_OPERAND (expression, i);
19170
19171                 /* In some cases, some of the operands may be missing.l
19172                    (For example, in the case of PREDECREMENT_EXPR, the
19173                    amount to increment by may be missing.)  That doesn't
19174                    make the expression dependent.  */
19175                 if (t && value_dependent_expression_p (t))
19176                   return true;
19177               }
19178           }
19179           break;
19180         default:
19181           break;
19182         }
19183       break;
19184     }
19185
19186   /* The expression is not value-dependent.  */
19187   return false;
19188 }
19189
19190 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19191    [temp.dep.expr].  Note that an expression with no type is
19192    considered dependent.  Other parts of the compiler arrange for an
19193    expression with type-dependent subexpressions to have no type, so
19194    this function doesn't have to be fully recursive.  */
19195
19196 bool
19197 type_dependent_expression_p (tree expression)
19198 {
19199   if (!processing_template_decl)
19200     return false;
19201
19202   if (expression == error_mark_node)
19203     return false;
19204
19205   /* An unresolved name is always dependent.  */
19206   if (TREE_CODE (expression) == IDENTIFIER_NODE
19207       || TREE_CODE (expression) == USING_DECL)
19208     return true;
19209
19210   /* Some expression forms are never type-dependent.  */
19211   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19212       || TREE_CODE (expression) == SIZEOF_EXPR
19213       || TREE_CODE (expression) == ALIGNOF_EXPR
19214       || TREE_CODE (expression) == AT_ENCODE_EXPR
19215       || TREE_CODE (expression) == NOEXCEPT_EXPR
19216       || TREE_CODE (expression) == TRAIT_EXPR
19217       || TREE_CODE (expression) == TYPEID_EXPR
19218       || TREE_CODE (expression) == DELETE_EXPR
19219       || TREE_CODE (expression) == VEC_DELETE_EXPR
19220       || TREE_CODE (expression) == THROW_EXPR)
19221     return false;
19222
19223   /* The types of these expressions depends only on the type to which
19224      the cast occurs.  */
19225   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19226       || TREE_CODE (expression) == STATIC_CAST_EXPR
19227       || TREE_CODE (expression) == CONST_CAST_EXPR
19228       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19229       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19230       || TREE_CODE (expression) == CAST_EXPR)
19231     return dependent_type_p (TREE_TYPE (expression));
19232
19233   /* The types of these expressions depends only on the type created
19234      by the expression.  */
19235   if (TREE_CODE (expression) == NEW_EXPR
19236       || TREE_CODE (expression) == VEC_NEW_EXPR)
19237     {
19238       /* For NEW_EXPR tree nodes created inside a template, either
19239          the object type itself or a TREE_LIST may appear as the
19240          operand 1.  */
19241       tree type = TREE_OPERAND (expression, 1);
19242       if (TREE_CODE (type) == TREE_LIST)
19243         /* This is an array type.  We need to check array dimensions
19244            as well.  */
19245         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19246                || value_dependent_expression_p
19247                     (TREE_OPERAND (TREE_VALUE (type), 1));
19248       else
19249         return dependent_type_p (type);
19250     }
19251
19252   if (TREE_CODE (expression) == SCOPE_REF)
19253     {
19254       tree scope = TREE_OPERAND (expression, 0);
19255       tree name = TREE_OPERAND (expression, 1);
19256
19257       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19258          contains an identifier associated by name lookup with one or more
19259          declarations declared with a dependent type, or...a
19260          nested-name-specifier or qualified-id that names a member of an
19261          unknown specialization.  */
19262       return (type_dependent_expression_p (name)
19263               || dependent_scope_p (scope));
19264     }
19265
19266   if (TREE_CODE (expression) == FUNCTION_DECL
19267       && DECL_LANG_SPECIFIC (expression)
19268       && DECL_TEMPLATE_INFO (expression)
19269       && (any_dependent_template_arguments_p
19270           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19271     return true;
19272
19273   if (TREE_CODE (expression) == TEMPLATE_DECL
19274       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19275     return false;
19276
19277   if (TREE_CODE (expression) == STMT_EXPR)
19278     expression = stmt_expr_value_expr (expression);
19279
19280   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19281     {
19282       tree elt;
19283       unsigned i;
19284
19285       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19286         {
19287           if (type_dependent_expression_p (elt))
19288             return true;
19289         }
19290       return false;
19291     }
19292
19293   /* A static data member of the current instantiation with incomplete
19294      array type is type-dependent, as the definition and specializations
19295      can have different bounds.  */
19296   if (TREE_CODE (expression) == VAR_DECL
19297       && DECL_CLASS_SCOPE_P (expression)
19298       && dependent_type_p (DECL_CONTEXT (expression))
19299       && VAR_HAD_UNKNOWN_BOUND (expression))
19300     return true;
19301
19302   if (TREE_TYPE (expression) == unknown_type_node)
19303     {
19304       if (TREE_CODE (expression) == ADDR_EXPR)
19305         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19306       if (TREE_CODE (expression) == COMPONENT_REF
19307           || TREE_CODE (expression) == OFFSET_REF)
19308         {
19309           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19310             return true;
19311           expression = TREE_OPERAND (expression, 1);
19312           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19313             return false;
19314         }
19315       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19316       if (TREE_CODE (expression) == SCOPE_REF)
19317         return false;
19318
19319       if (BASELINK_P (expression))
19320         expression = BASELINK_FUNCTIONS (expression);
19321
19322       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19323         {
19324           if (any_dependent_template_arguments_p
19325               (TREE_OPERAND (expression, 1)))
19326             return true;
19327           expression = TREE_OPERAND (expression, 0);
19328         }
19329       gcc_assert (TREE_CODE (expression) == OVERLOAD
19330                   || TREE_CODE (expression) == FUNCTION_DECL);
19331
19332       while (expression)
19333         {
19334           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19335             return true;
19336           expression = OVL_NEXT (expression);
19337         }
19338       return false;
19339     }
19340
19341   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19342
19343   return (dependent_type_p (TREE_TYPE (expression)));
19344 }
19345
19346 /* Like type_dependent_expression_p, but it also works while not processing
19347    a template definition, i.e. during substitution or mangling.  */
19348
19349 bool
19350 type_dependent_expression_p_push (tree expr)
19351 {
19352   bool b;
19353   ++processing_template_decl;
19354   b = type_dependent_expression_p (expr);
19355   --processing_template_decl;
19356   return b;
19357 }
19358
19359 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19360
19361 bool
19362 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19363 {
19364   unsigned int i;
19365   tree arg;
19366
19367   FOR_EACH_VEC_ELT (tree, args, i, arg)
19368     {
19369       if (type_dependent_expression_p (arg))
19370         return true;
19371     }
19372   return false;
19373 }
19374
19375 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19376    expressions) contains any type-dependent expressions.  */
19377
19378 bool
19379 any_type_dependent_elements_p (const_tree list)
19380 {
19381   for (; list; list = TREE_CHAIN (list))
19382     if (value_dependent_expression_p (TREE_VALUE (list)))
19383       return true;
19384
19385   return false;
19386 }
19387
19388 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19389    expressions) contains any value-dependent expressions.  */
19390
19391 bool
19392 any_value_dependent_elements_p (const_tree list)
19393 {
19394   for (; list; list = TREE_CHAIN (list))
19395     if (value_dependent_expression_p (TREE_VALUE (list)))
19396       return true;
19397
19398   return false;
19399 }
19400
19401 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19402
19403 bool
19404 dependent_template_arg_p (tree arg)
19405 {
19406   if (!processing_template_decl)
19407     return false;
19408
19409   /* Assume a template argument that was wrongly written by the user
19410      is dependent. This is consistent with what
19411      any_dependent_template_arguments_p [that calls this function]
19412      does.  */
19413   if (!arg || arg == error_mark_node)
19414     return true;
19415
19416   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19417     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19418
19419   if (TREE_CODE (arg) == TEMPLATE_DECL
19420       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19421     return dependent_template_p (arg);
19422   else if (ARGUMENT_PACK_P (arg))
19423     {
19424       tree args = ARGUMENT_PACK_ARGS (arg);
19425       int i, len = TREE_VEC_LENGTH (args);
19426       for (i = 0; i < len; ++i)
19427         {
19428           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19429             return true;
19430         }
19431
19432       return false;
19433     }
19434   else if (TYPE_P (arg))
19435     return dependent_type_p (arg);
19436   else
19437     return (type_dependent_expression_p (arg)
19438             || value_dependent_expression_p (arg));
19439 }
19440
19441 /* Returns true if ARGS (a collection of template arguments) contains
19442    any types that require structural equality testing.  */
19443
19444 bool
19445 any_template_arguments_need_structural_equality_p (tree args)
19446 {
19447   int i;
19448   int j;
19449
19450   if (!args)
19451     return false;
19452   if (args == error_mark_node)
19453     return true;
19454
19455   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19456     {
19457       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19458       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19459         {
19460           tree arg = TREE_VEC_ELT (level, j);
19461           tree packed_args = NULL_TREE;
19462           int k, len = 1;
19463
19464           if (ARGUMENT_PACK_P (arg))
19465             {
19466               /* Look inside the argument pack.  */
19467               packed_args = ARGUMENT_PACK_ARGS (arg);
19468               len = TREE_VEC_LENGTH (packed_args);
19469             }
19470
19471           for (k = 0; k < len; ++k)
19472             {
19473               if (packed_args)
19474                 arg = TREE_VEC_ELT (packed_args, k);
19475
19476               if (error_operand_p (arg))
19477                 return true;
19478               else if (TREE_CODE (arg) == TEMPLATE_DECL
19479                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19480                 continue;
19481               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19482                 return true;
19483               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19484                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19485                 return true;
19486             }
19487         }
19488     }
19489
19490   return false;
19491 }
19492
19493 /* Returns true if ARGS (a collection of template arguments) contains
19494    any dependent arguments.  */
19495
19496 bool
19497 any_dependent_template_arguments_p (const_tree args)
19498 {
19499   int i;
19500   int j;
19501
19502   if (!args)
19503     return false;
19504   if (args == error_mark_node)
19505     return true;
19506
19507   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19508     {
19509       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19510       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19511         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19512           return true;
19513     }
19514
19515   return false;
19516 }
19517
19518 /* Returns TRUE if the template TMPL is dependent.  */
19519
19520 bool
19521 dependent_template_p (tree tmpl)
19522 {
19523   if (TREE_CODE (tmpl) == OVERLOAD)
19524     {
19525       while (tmpl)
19526         {
19527           if (dependent_template_p (OVL_CURRENT (tmpl)))
19528             return true;
19529           tmpl = OVL_NEXT (tmpl);
19530         }
19531       return false;
19532     }
19533
19534   /* Template template parameters are dependent.  */
19535   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19536       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19537     return true;
19538   /* So are names that have not been looked up.  */
19539   if (TREE_CODE (tmpl) == SCOPE_REF
19540       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19541     return true;
19542   /* So are member templates of dependent classes.  */
19543   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19544     return dependent_type_p (DECL_CONTEXT (tmpl));
19545   return false;
19546 }
19547
19548 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19549
19550 bool
19551 dependent_template_id_p (tree tmpl, tree args)
19552 {
19553   return (dependent_template_p (tmpl)
19554           || any_dependent_template_arguments_p (args));
19555 }
19556
19557 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19558    is dependent.  */
19559
19560 bool
19561 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19562 {
19563   int i;
19564
19565   if (!processing_template_decl)
19566     return false;
19567
19568   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19569     {
19570       tree decl = TREE_VEC_ELT (declv, i);
19571       tree init = TREE_VEC_ELT (initv, i);
19572       tree cond = TREE_VEC_ELT (condv, i);
19573       tree incr = TREE_VEC_ELT (incrv, i);
19574
19575       if (type_dependent_expression_p (decl))
19576         return true;
19577
19578       if (init && type_dependent_expression_p (init))
19579         return true;
19580
19581       if (type_dependent_expression_p (cond))
19582         return true;
19583
19584       if (COMPARISON_CLASS_P (cond)
19585           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19586               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19587         return true;
19588
19589       if (TREE_CODE (incr) == MODOP_EXPR)
19590         {
19591           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19592               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19593             return true;
19594         }
19595       else if (type_dependent_expression_p (incr))
19596         return true;
19597       else if (TREE_CODE (incr) == MODIFY_EXPR)
19598         {
19599           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19600             return true;
19601           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19602             {
19603               tree t = TREE_OPERAND (incr, 1);
19604               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19605                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19606                 return true;
19607             }
19608         }
19609     }
19610
19611   return false;
19612 }
19613
19614 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19615    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19616    no such TYPE can be found.  Note that this function peers inside
19617    uninstantiated templates and therefore should be used only in
19618    extremely limited situations.  ONLY_CURRENT_P restricts this
19619    peering to the currently open classes hierarchy (which is required
19620    when comparing types).  */
19621
19622 tree
19623 resolve_typename_type (tree type, bool only_current_p)
19624 {
19625   tree scope;
19626   tree name;
19627   tree decl;
19628   int quals;
19629   tree pushed_scope;
19630   tree result;
19631
19632   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19633
19634   scope = TYPE_CONTEXT (type);
19635   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19636      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19637      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19638      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19639      identifier  of the TYPENAME_TYPE anymore.
19640      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19641      TYPENAME_TYPE instead, we avoid messing up with a possible
19642      typedef variant case.  */
19643   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19644
19645   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19646      it first before we can figure out what NAME refers to.  */
19647   if (TREE_CODE (scope) == TYPENAME_TYPE)
19648     scope = resolve_typename_type (scope, only_current_p);
19649   /* If we don't know what SCOPE refers to, then we cannot resolve the
19650      TYPENAME_TYPE.  */
19651   if (TREE_CODE (scope) == TYPENAME_TYPE)
19652     return type;
19653   /* If the SCOPE is a template type parameter, we have no way of
19654      resolving the name.  */
19655   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19656     return type;
19657   /* If the SCOPE is not the current instantiation, there's no reason
19658      to look inside it.  */
19659   if (only_current_p && !currently_open_class (scope))
19660     return type;
19661   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19662   if (typedef_variant_p (type))
19663     return type;
19664   /* If SCOPE isn't the template itself, it will not have a valid
19665      TYPE_FIELDS list.  */
19666   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19667     /* scope is either the template itself or a compatible instantiation
19668        like X<T>, so look up the name in the original template.  */
19669     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19670   else
19671     /* scope is a partial instantiation, so we can't do the lookup or we
19672        will lose the template arguments.  */
19673     return type;
19674   /* Enter the SCOPE so that name lookup will be resolved as if we
19675      were in the class definition.  In particular, SCOPE will no
19676      longer be considered a dependent type.  */
19677   pushed_scope = push_scope (scope);
19678   /* Look up the declaration.  */
19679   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19680
19681   result = NULL_TREE;
19682   
19683   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19684      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19685   if (!decl)
19686     /*nop*/;
19687   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19688            && TREE_CODE (decl) == TYPE_DECL)
19689     {
19690       result = TREE_TYPE (decl);
19691       if (result == error_mark_node)
19692         result = NULL_TREE;
19693     }
19694   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19695            && DECL_CLASS_TEMPLATE_P (decl))
19696     {
19697       tree tmpl;
19698       tree args;
19699       /* Obtain the template and the arguments.  */
19700       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19701       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19702       /* Instantiate the template.  */
19703       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19704                                       /*entering_scope=*/0,
19705                                       tf_error | tf_user);
19706       if (result == error_mark_node)
19707         result = NULL_TREE;
19708     }
19709   
19710   /* Leave the SCOPE.  */
19711   if (pushed_scope)
19712     pop_scope (pushed_scope);
19713
19714   /* If we failed to resolve it, return the original typename.  */
19715   if (!result)
19716     return type;
19717   
19718   /* If lookup found a typename type, resolve that too.  */
19719   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19720     {
19721       /* Ill-formed programs can cause infinite recursion here, so we
19722          must catch that.  */
19723       TYPENAME_IS_RESOLVING_P (type) = 1;
19724       result = resolve_typename_type (result, only_current_p);
19725       TYPENAME_IS_RESOLVING_P (type) = 0;
19726     }
19727   
19728   /* Qualify the resulting type.  */
19729   quals = cp_type_quals (type);
19730   if (quals)
19731     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19732
19733   return result;
19734 }
19735
19736 /* EXPR is an expression which is not type-dependent.  Return a proxy
19737    for EXPR that can be used to compute the types of larger
19738    expressions containing EXPR.  */
19739
19740 tree
19741 build_non_dependent_expr (tree expr)
19742 {
19743   tree inner_expr;
19744
19745 #ifdef ENABLE_CHECKING
19746   /* Try to get a constant value for all non-type-dependent expressions in
19747       order to expose bugs in *_dependent_expression_p and constexpr.  */
19748   if (cxx_dialect >= cxx0x)
19749     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19750 #endif
19751
19752   /* Preserve OVERLOADs; the functions must be available to resolve
19753      types.  */
19754   inner_expr = expr;
19755   if (TREE_CODE (inner_expr) == STMT_EXPR)
19756     inner_expr = stmt_expr_value_expr (inner_expr);
19757   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19758     inner_expr = TREE_OPERAND (inner_expr, 0);
19759   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19760     inner_expr = TREE_OPERAND (inner_expr, 1);
19761   if (is_overloaded_fn (inner_expr)
19762       || TREE_CODE (inner_expr) == OFFSET_REF)
19763     return expr;
19764   /* There is no need to return a proxy for a variable.  */
19765   if (TREE_CODE (expr) == VAR_DECL)
19766     return expr;
19767   /* Preserve string constants; conversions from string constants to
19768      "char *" are allowed, even though normally a "const char *"
19769      cannot be used to initialize a "char *".  */
19770   if (TREE_CODE (expr) == STRING_CST)
19771     return expr;
19772   /* Preserve arithmetic constants, as an optimization -- there is no
19773      reason to create a new node.  */
19774   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19775     return expr;
19776   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19777      There is at least one place where we want to know that a
19778      particular expression is a throw-expression: when checking a ?:
19779      expression, there are special rules if the second or third
19780      argument is a throw-expression.  */
19781   if (TREE_CODE (expr) == THROW_EXPR)
19782     return expr;
19783
19784   /* Don't wrap an initializer list, we need to be able to look inside.  */
19785   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19786     return expr;
19787
19788   if (TREE_CODE (expr) == COND_EXPR)
19789     return build3 (COND_EXPR,
19790                    TREE_TYPE (expr),
19791                    TREE_OPERAND (expr, 0),
19792                    (TREE_OPERAND (expr, 1)
19793                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19794                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19795                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19796   if (TREE_CODE (expr) == COMPOUND_EXPR
19797       && !COMPOUND_EXPR_OVERLOADED (expr))
19798     return build2 (COMPOUND_EXPR,
19799                    TREE_TYPE (expr),
19800                    TREE_OPERAND (expr, 0),
19801                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19802
19803   /* If the type is unknown, it can't really be non-dependent */
19804   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19805
19806   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19807   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19808 }
19809
19810 /* ARGS is a vector of expressions as arguments to a function call.
19811    Replace the arguments with equivalent non-dependent expressions.
19812    This modifies ARGS in place.  */
19813
19814 void
19815 make_args_non_dependent (VEC(tree,gc) *args)
19816 {
19817   unsigned int ix;
19818   tree arg;
19819
19820   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19821     {
19822       tree newarg = build_non_dependent_expr (arg);
19823       if (newarg != arg)
19824         VEC_replace (tree, args, ix, newarg);
19825     }
19826 }
19827
19828 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19829    with a level one deeper than the actual template parms.  */
19830
19831 tree
19832 make_auto (void)
19833 {
19834   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19835   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19836                                TYPE_DECL, get_identifier ("auto"), au);
19837   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19838   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19839     (0, processing_template_decl + 1, processing_template_decl + 1,
19840      0, TYPE_NAME (au), NULL_TREE);
19841   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19842   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19843   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19844
19845   return au;
19846 }
19847
19848 /* Given type ARG, return std::initializer_list<ARG>.  */
19849
19850 static tree
19851 listify (tree arg)
19852 {
19853   tree std_init_list = namespace_binding
19854     (get_identifier ("initializer_list"), std_node);
19855   tree argvec;
19856   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19857     {    
19858       error ("deducing from brace-enclosed initializer list requires "
19859              "#include <initializer_list>");
19860       return error_mark_node;
19861     }
19862   argvec = make_tree_vec (1);
19863   TREE_VEC_ELT (argvec, 0) = arg;
19864   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19865                                 NULL_TREE, 0, tf_warning_or_error);
19866 }
19867
19868 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19869
19870 static tree
19871 listify_autos (tree type, tree auto_node)
19872 {
19873   tree init_auto = listify (auto_node);
19874   tree argvec = make_tree_vec (1);
19875   TREE_VEC_ELT (argvec, 0) = init_auto;
19876   if (processing_template_decl)
19877     argvec = add_to_template_args (current_template_args (), argvec);
19878   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19879 }
19880
19881 /* walk_tree helper for do_auto_deduction.  */
19882
19883 static tree
19884 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19885                  void *type)
19886 {
19887   /* Is this a variable with the type we're looking for?  */
19888   if (DECL_P (*tp)
19889       && TREE_TYPE (*tp) == type)
19890     return *tp;
19891   else
19892     return NULL_TREE;
19893 }
19894
19895 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19896    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19897
19898 tree
19899 do_auto_deduction (tree type, tree init, tree auto_node)
19900 {
19901   tree parms, tparms, targs;
19902   tree args[1];
19903   tree decl;
19904   int val;
19905
19906   if (processing_template_decl
19907       && (TREE_TYPE (init) == NULL_TREE
19908           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19909     /* Not enough information to try this yet.  */
19910     return type;
19911
19912   /* The name of the object being declared shall not appear in the
19913      initializer expression.  */
19914   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19915   if (decl)
19916     {
19917       error ("variable %q#D with %<auto%> type used in its own "
19918              "initializer", decl);
19919       return error_mark_node;
19920     }
19921
19922   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19923      with either a new invented type template parameter U or, if the
19924      initializer is a braced-init-list (8.5.4), with
19925      std::initializer_list<U>.  */
19926   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19927     type = listify_autos (type, auto_node);
19928
19929   init = resolve_nondeduced_context (init);
19930
19931   parms = build_tree_list (NULL_TREE, type);
19932   args[0] = init;
19933   tparms = make_tree_vec (1);
19934   targs = make_tree_vec (1);
19935   TREE_VEC_ELT (tparms, 0)
19936     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19937   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19938                                DEDUCE_CALL, LOOKUP_NORMAL,
19939                                /*explain_p=*/false);
19940   if (val > 0)
19941     {
19942       if (processing_template_decl)
19943         /* Try again at instantiation time.  */
19944         return type;
19945       if (type && type != error_mark_node)
19946         /* If type is error_mark_node a diagnostic must have been
19947            emitted by now.  Also, having a mention to '<type error>'
19948            in the diagnostic is not really useful to the user.  */
19949         error ("unable to deduce %qT from %qE", type, init);
19950       return error_mark_node;
19951     }
19952
19953   /* If the list of declarators contains more than one declarator, the type
19954      of each declared variable is determined as described above. If the
19955      type deduced for the template parameter U is not the same in each
19956      deduction, the program is ill-formed.  */
19957   if (TREE_TYPE (auto_node)
19958       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19959     {
19960       error ("inconsistent deduction for %qT: %qT and then %qT",
19961              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19962       return error_mark_node;
19963     }
19964   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19965
19966   if (processing_template_decl)
19967     targs = add_to_template_args (current_template_args (), targs);
19968   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19969 }
19970
19971 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19972    result.  */
19973
19974 tree
19975 splice_late_return_type (tree type, tree late_return_type)
19976 {
19977   tree argvec;
19978
19979   if (late_return_type == NULL_TREE)
19980     return type;
19981   argvec = make_tree_vec (1);
19982   TREE_VEC_ELT (argvec, 0) = late_return_type;
19983   if (processing_template_parmlist)
19984     /* For a late-specified return type in a template type-parameter, we
19985        need to add a dummy argument level for its parmlist.  */
19986     argvec = add_to_template_args
19987       (make_tree_vec (processing_template_parmlist), argvec);
19988   if (current_template_parms)
19989     argvec = add_to_template_args (current_template_args (), argvec);
19990   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19991 }
19992
19993 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19994
19995 bool
19996 is_auto (const_tree type)
19997 {
19998   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19999       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
20000     return true;
20001   else
20002     return false;
20003 }
20004
20005 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
20006    appear as a type-specifier for the declaration in question, we don't
20007    have to look through the whole type.  */
20008
20009 tree
20010 type_uses_auto (tree type)
20011 {
20012   enum tree_code code;
20013   if (is_auto (type))
20014     return type;
20015
20016   code = TREE_CODE (type);
20017
20018   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20019       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20020       || code == METHOD_TYPE || code == ARRAY_TYPE)
20021     return type_uses_auto (TREE_TYPE (type));
20022
20023   if (TYPE_PTRMEMFUNC_P (type))
20024     return type_uses_auto (TREE_TYPE (TREE_TYPE
20025                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20026
20027   return NULL_TREE;
20028 }
20029
20030 /* For a given template T, return the vector of typedefs referenced
20031    in T for which access check is needed at T instantiation time.
20032    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20033    Those typedefs were added to T by the function
20034    append_type_to_template_for_access_check.  */
20035
20036 VEC(qualified_typedef_usage_t,gc)*
20037 get_types_needing_access_check (tree t)
20038 {
20039   tree ti;
20040   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20041
20042   if (!t || t == error_mark_node)
20043     return NULL;
20044
20045   if (!(ti = get_template_info (t)))
20046     return NULL;
20047
20048   if (CLASS_TYPE_P (t)
20049       || TREE_CODE (t) == FUNCTION_DECL)
20050     {
20051       if (!TI_TEMPLATE (ti))
20052         return NULL;
20053
20054       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20055     }
20056
20057   return result;
20058 }
20059
20060 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20061    tied to T. That list of typedefs will be access checked at
20062    T instantiation time.
20063    T is either a FUNCTION_DECL or a RECORD_TYPE.
20064    TYPE_DECL is a TYPE_DECL node representing a typedef.
20065    SCOPE is the scope through which TYPE_DECL is accessed.
20066    LOCATION is the location of the usage point of TYPE_DECL.
20067
20068    This function is a subroutine of
20069    append_type_to_template_for_access_check.  */
20070
20071 static void
20072 append_type_to_template_for_access_check_1 (tree t,
20073                                             tree type_decl,
20074                                             tree scope,
20075                                             location_t location)
20076 {
20077   qualified_typedef_usage_t typedef_usage;
20078   tree ti;
20079
20080   if (!t || t == error_mark_node)
20081     return;
20082
20083   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20084                || CLASS_TYPE_P (t))
20085               && type_decl
20086               && TREE_CODE (type_decl) == TYPE_DECL
20087               && scope);
20088
20089   if (!(ti = get_template_info (t)))
20090     return;
20091
20092   gcc_assert (TI_TEMPLATE (ti));
20093
20094   typedef_usage.typedef_decl = type_decl;
20095   typedef_usage.context = scope;
20096   typedef_usage.locus = location;
20097
20098   VEC_safe_push (qualified_typedef_usage_t, gc,
20099                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20100                  &typedef_usage);
20101 }
20102
20103 /* Append TYPE_DECL to the template TEMPL.
20104    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20105    At TEMPL instanciation time, TYPE_DECL will be checked to see
20106    if it can be accessed through SCOPE.
20107    LOCATION is the location of the usage point of TYPE_DECL.
20108
20109    e.g. consider the following code snippet:
20110
20111      class C
20112      {
20113        typedef int myint;
20114      };
20115
20116      template<class U> struct S
20117      {
20118        C::myint mi; // <-- usage point of the typedef C::myint
20119      };
20120
20121      S<char> s;
20122
20123    At S<char> instantiation time, we need to check the access of C::myint
20124    In other words, we need to check the access of the myint typedef through
20125    the C scope. For that purpose, this function will add the myint typedef
20126    and the scope C through which its being accessed to a list of typedefs
20127    tied to the template S. That list will be walked at template instantiation
20128    time and access check performed on each typedefs it contains.
20129    Note that this particular code snippet should yield an error because
20130    myint is private to C.  */
20131
20132 void
20133 append_type_to_template_for_access_check (tree templ,
20134                                           tree type_decl,
20135                                           tree scope,
20136                                           location_t location)
20137 {
20138   qualified_typedef_usage_t *iter;
20139   int i;
20140
20141   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20142
20143   /* Make sure we don't append the type to the template twice.  */
20144   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20145                     get_types_needing_access_check (templ),
20146                     i, iter)
20147     if (iter->typedef_decl == type_decl && scope == iter->context)
20148       return;
20149
20150   append_type_to_template_for_access_check_1 (templ, type_decl,
20151                                               scope, location);
20152 }
20153
20154 /* Set up the hash tables for template instantiations.  */
20155
20156 void
20157 init_template_processing (void)
20158 {
20159   decl_specializations = htab_create_ggc (37,
20160                                           hash_specialization,
20161                                           eq_specializations,
20162                                           ggc_free);
20163   type_specializations = htab_create_ggc (37,
20164                                           hash_specialization,
20165                                           eq_specializations,
20166                                           ggc_free);
20167 }
20168
20169 /* Print stats about the template hash tables for -fstats.  */
20170
20171 void
20172 print_template_statistics (void)
20173 {
20174   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20175            "%f collisions\n", (long) htab_size (decl_specializations),
20176            (long) htab_elements (decl_specializations),
20177            htab_collisions (decl_specializations));
20178   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20179            "%f collisions\n", (long) htab_size (type_specializations),
20180            (long) htab_elements (type_specializations),
20181            htab_collisions (type_specializations));
20182 }
20183
20184 #include "gt-cp-pt.h"