OSDN Git Service

PR c++/50437
[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     default:
2984       /* Not a parameter pack.  */
2985       break;
2986     }
2987
2988   if (parameter_pack_p)
2989     {
2990       /* Add this parameter pack to the list.  */
2991       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2992     }
2993
2994   if (TYPE_P (t))
2995     cp_walk_tree (&TYPE_CONTEXT (t), 
2996                   &find_parameter_packs_r, ppd, ppd->visited);
2997
2998   /* This switch statement will return immediately if we don't find a
2999      parameter pack.  */
3000   switch (TREE_CODE (t)) 
3001     {
3002     case TEMPLATE_PARM_INDEX:
3003       return NULL_TREE;
3004
3005     case BOUND_TEMPLATE_TEMPLATE_PARM:
3006       /* Check the template itself.  */
3007       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3008                     &find_parameter_packs_r, ppd, ppd->visited);
3009       /* Check the template arguments.  */
3010       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3011                     ppd->visited);
3012       *walk_subtrees = 0;
3013       return NULL_TREE;
3014
3015     case TEMPLATE_TYPE_PARM:
3016     case TEMPLATE_TEMPLATE_PARM:
3017       return NULL_TREE;
3018
3019     case PARM_DECL:
3020       return NULL_TREE;
3021
3022     case RECORD_TYPE:
3023       if (TYPE_PTRMEMFUNC_P (t))
3024         return NULL_TREE;
3025       /* Fall through.  */
3026
3027     case UNION_TYPE:
3028     case ENUMERAL_TYPE:
3029       if (TYPE_TEMPLATE_INFO (t))
3030         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3031                       &find_parameter_packs_r, ppd, ppd->visited);
3032
3033       *walk_subtrees = 0;
3034       return NULL_TREE;
3035
3036     case CONSTRUCTOR:
3037     case TEMPLATE_DECL:
3038       cp_walk_tree (&TREE_TYPE (t),
3039                     &find_parameter_packs_r, ppd, ppd->visited);
3040       return NULL_TREE;
3041  
3042     case TYPENAME_TYPE:
3043       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3044                    ppd, ppd->visited);
3045       *walk_subtrees = 0;
3046       return NULL_TREE;
3047       
3048     case TYPE_PACK_EXPANSION:
3049     case EXPR_PACK_EXPANSION:
3050       *walk_subtrees = 0;
3051       return NULL_TREE;
3052
3053     case INTEGER_TYPE:
3054       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3055                     ppd, ppd->visited);
3056       *walk_subtrees = 0;
3057       return NULL_TREE;
3058
3059     case IDENTIFIER_NODE:
3060       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3061                     ppd->visited);
3062       *walk_subtrees = 0;
3063       return NULL_TREE;
3064
3065     default:
3066       return NULL_TREE;
3067     }
3068
3069   return NULL_TREE;
3070 }
3071
3072 /* Determines if the expression or type T uses any parameter packs.  */
3073 bool
3074 uses_parameter_packs (tree t)
3075 {
3076   tree parameter_packs = NULL_TREE;
3077   struct find_parameter_pack_data ppd;
3078   ppd.parameter_packs = &parameter_packs;
3079   ppd.visited = pointer_set_create ();
3080   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3081   pointer_set_destroy (ppd.visited);
3082   return parameter_packs != NULL_TREE;
3083 }
3084
3085 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3086    representation a base-class initializer into a parameter pack
3087    expansion. If all goes well, the resulting node will be an
3088    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3089    respectively.  */
3090 tree 
3091 make_pack_expansion (tree arg)
3092 {
3093   tree result;
3094   tree parameter_packs = NULL_TREE;
3095   bool for_types = false;
3096   struct find_parameter_pack_data ppd;
3097
3098   if (!arg || arg == error_mark_node)
3099     return arg;
3100
3101   if (TREE_CODE (arg) == TREE_LIST)
3102     {
3103       /* The only time we will see a TREE_LIST here is for a base
3104          class initializer.  In this case, the TREE_PURPOSE will be a
3105          _TYPE node (representing the base class expansion we're
3106          initializing) and the TREE_VALUE will be a TREE_LIST
3107          containing the initialization arguments. 
3108
3109          The resulting expansion looks somewhat different from most
3110          expansions. Rather than returning just one _EXPANSION, we
3111          return a TREE_LIST whose TREE_PURPOSE is a
3112          TYPE_PACK_EXPANSION containing the bases that will be
3113          initialized.  The TREE_VALUE will be identical to the
3114          original TREE_VALUE, which is a list of arguments that will
3115          be passed to each base.  We do not introduce any new pack
3116          expansion nodes into the TREE_VALUE (although it is possible
3117          that some already exist), because the TREE_PURPOSE and
3118          TREE_VALUE all need to be expanded together with the same
3119          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3120          resulting TREE_PURPOSE will mention the parameter packs in
3121          both the bases and the arguments to the bases.  */
3122       tree purpose;
3123       tree value;
3124       tree parameter_packs = NULL_TREE;
3125
3126       /* Determine which parameter packs will be used by the base
3127          class expansion.  */
3128       ppd.visited = pointer_set_create ();
3129       ppd.parameter_packs = &parameter_packs;
3130       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3131                     &ppd, ppd.visited);
3132
3133       if (parameter_packs == NULL_TREE)
3134         {
3135           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3136           pointer_set_destroy (ppd.visited);
3137           return error_mark_node;
3138         }
3139
3140       if (TREE_VALUE (arg) != void_type_node)
3141         {
3142           /* Collect the sets of parameter packs used in each of the
3143              initialization arguments.  */
3144           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3145             {
3146               /* Determine which parameter packs will be expanded in this
3147                  argument.  */
3148               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3149                             &ppd, ppd.visited);
3150             }
3151         }
3152
3153       pointer_set_destroy (ppd.visited);
3154
3155       /* Create the pack expansion type for the base type.  */
3156       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3157       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3158       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3159
3160       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3161          they will rarely be compared to anything.  */
3162       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3163
3164       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3165     }
3166
3167   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3168     for_types = true;
3169
3170   /* Build the PACK_EXPANSION_* node.  */
3171   result = for_types
3172      ? cxx_make_type (TYPE_PACK_EXPANSION)
3173      : make_node (EXPR_PACK_EXPANSION);
3174   SET_PACK_EXPANSION_PATTERN (result, arg);
3175   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3176     {
3177       /* Propagate type and const-expression information.  */
3178       TREE_TYPE (result) = TREE_TYPE (arg);
3179       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3180     }
3181   else
3182     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3183        they will rarely be compared to anything.  */
3184     SET_TYPE_STRUCTURAL_EQUALITY (result);
3185
3186   /* Determine which parameter packs will be expanded.  */
3187   ppd.parameter_packs = &parameter_packs;
3188   ppd.visited = pointer_set_create ();
3189   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3190   pointer_set_destroy (ppd.visited);
3191
3192   /* Make sure we found some parameter packs.  */
3193   if (parameter_packs == NULL_TREE)
3194     {
3195       if (TYPE_P (arg))
3196         error ("expansion pattern %<%T%> contains no argument packs", arg);
3197       else
3198         error ("expansion pattern %<%E%> contains no argument packs", arg);
3199       return error_mark_node;
3200     }
3201   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3202
3203   return result;
3204 }
3205
3206 /* Checks T for any "bare" parameter packs, which have not yet been
3207    expanded, and issues an error if any are found. This operation can
3208    only be done on full expressions or types (e.g., an expression
3209    statement, "if" condition, etc.), because we could have expressions like:
3210
3211      foo(f(g(h(args)))...)
3212
3213    where "args" is a parameter pack. check_for_bare_parameter_packs
3214    should not be called for the subexpressions args, h(args),
3215    g(h(args)), or f(g(h(args))), because we would produce erroneous
3216    error messages. 
3217
3218    Returns TRUE and emits an error if there were bare parameter packs,
3219    returns FALSE otherwise.  */
3220 bool 
3221 check_for_bare_parameter_packs (tree t)
3222 {
3223   tree parameter_packs = NULL_TREE;
3224   struct find_parameter_pack_data ppd;
3225
3226   if (!processing_template_decl || !t || t == error_mark_node)
3227     return false;
3228
3229   if (TREE_CODE (t) == TYPE_DECL)
3230     t = TREE_TYPE (t);
3231
3232   ppd.parameter_packs = &parameter_packs;
3233   ppd.visited = pointer_set_create ();
3234   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3235   pointer_set_destroy (ppd.visited);
3236
3237   if (parameter_packs) 
3238     {
3239       error ("parameter packs not expanded with %<...%>:");
3240       while (parameter_packs)
3241         {
3242           tree pack = TREE_VALUE (parameter_packs);
3243           tree name = NULL_TREE;
3244
3245           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3246               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3247             name = TYPE_NAME (pack);
3248           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3249             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3250           else
3251             name = DECL_NAME (pack);
3252
3253           if (name)
3254             inform (input_location, "        %qD", name);
3255           else
3256             inform (input_location, "        <anonymous>");
3257
3258           parameter_packs = TREE_CHAIN (parameter_packs);
3259         }
3260
3261       return true;
3262     }
3263
3264   return false;
3265 }
3266
3267 /* Expand any parameter packs that occur in the template arguments in
3268    ARGS.  */
3269 tree
3270 expand_template_argument_pack (tree args)
3271 {
3272   tree result_args = NULL_TREE;
3273   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3274   int num_result_args = -1;
3275   int non_default_args_count = -1;
3276
3277   /* First, determine if we need to expand anything, and the number of
3278      slots we'll need.  */
3279   for (in_arg = 0; in_arg < nargs; ++in_arg)
3280     {
3281       tree arg = TREE_VEC_ELT (args, in_arg);
3282       if (arg == NULL_TREE)
3283         return args;
3284       if (ARGUMENT_PACK_P (arg))
3285         {
3286           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3287           if (num_result_args < 0)
3288             num_result_args = in_arg + num_packed;
3289           else
3290             num_result_args += num_packed;
3291         }
3292       else
3293         {
3294           if (num_result_args >= 0)
3295             num_result_args++;
3296         }
3297     }
3298
3299   /* If no expansion is necessary, we're done.  */
3300   if (num_result_args < 0)
3301     return args;
3302
3303   /* Expand arguments.  */
3304   result_args = make_tree_vec (num_result_args);
3305   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3306     non_default_args_count =
3307       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3308   for (in_arg = 0; in_arg < nargs; ++in_arg)
3309     {
3310       tree arg = TREE_VEC_ELT (args, in_arg);
3311       if (ARGUMENT_PACK_P (arg))
3312         {
3313           tree packed = ARGUMENT_PACK_ARGS (arg);
3314           int i, num_packed = TREE_VEC_LENGTH (packed);
3315           for (i = 0; i < num_packed; ++i, ++out_arg)
3316             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3317           if (non_default_args_count > 0)
3318             non_default_args_count += num_packed;
3319         }
3320       else
3321         {
3322           TREE_VEC_ELT (result_args, out_arg) = arg;
3323           ++out_arg;
3324         }
3325     }
3326   if (non_default_args_count >= 0)
3327     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3328   return result_args;
3329 }
3330
3331 /* Checks if DECL shadows a template parameter.
3332
3333    [temp.local]: A template-parameter shall not be redeclared within its
3334    scope (including nested scopes).
3335
3336    Emits an error and returns TRUE if the DECL shadows a parameter,
3337    returns FALSE otherwise.  */
3338
3339 bool
3340 check_template_shadow (tree decl)
3341 {
3342   tree olddecl;
3343
3344   /* If we're not in a template, we can't possibly shadow a template
3345      parameter.  */
3346   if (!current_template_parms)
3347     return true;
3348
3349   /* Figure out what we're shadowing.  */
3350   if (TREE_CODE (decl) == OVERLOAD)
3351     decl = OVL_CURRENT (decl);
3352   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3353
3354   /* If there's no previous binding for this name, we're not shadowing
3355      anything, let alone a template parameter.  */
3356   if (!olddecl)
3357     return true;
3358
3359   /* If we're not shadowing a template parameter, we're done.  Note
3360      that OLDDECL might be an OVERLOAD (or perhaps even an
3361      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3362      node.  */
3363   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3364     return true;
3365
3366   /* We check for decl != olddecl to avoid bogus errors for using a
3367      name inside a class.  We check TPFI to avoid duplicate errors for
3368      inline member templates.  */
3369   if (decl == olddecl
3370       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3371     return true;
3372
3373   error ("declaration of %q+#D", decl);
3374   error (" shadows template parm %q+#D", olddecl);
3375   return false;
3376 }
3377
3378 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3379    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3380    template parameters.  */
3381
3382 static tree
3383 build_template_parm_index (int index,
3384                            int level,
3385                            int orig_level,
3386                            int num_siblings,
3387                            tree decl,
3388                            tree type)
3389 {
3390   tree t = make_node (TEMPLATE_PARM_INDEX);
3391   TEMPLATE_PARM_IDX (t) = index;
3392   TEMPLATE_PARM_LEVEL (t) = level;
3393   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3394   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3395   TEMPLATE_PARM_DECL (t) = decl;
3396   TREE_TYPE (t) = type;
3397   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3398   TREE_READONLY (t) = TREE_READONLY (decl);
3399
3400   return t;
3401 }
3402
3403 /* Find the canonical type parameter for the given template type
3404    parameter.  Returns the canonical type parameter, which may be TYPE
3405    if no such parameter existed.  */
3406
3407 static tree
3408 canonical_type_parameter (tree type)
3409 {
3410   tree list;
3411   int idx = TEMPLATE_TYPE_IDX (type);
3412   if (!canonical_template_parms)
3413     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3414
3415   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3416     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3417
3418   list = VEC_index (tree, canonical_template_parms, idx);
3419   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3420     list = TREE_CHAIN (list);
3421
3422   if (list)
3423     return TREE_VALUE (list);
3424   else
3425     {
3426       VEC_replace(tree, canonical_template_parms, idx,
3427                   tree_cons (NULL_TREE, type, 
3428                              VEC_index (tree, canonical_template_parms, idx)));
3429       return type;
3430     }
3431 }
3432
3433 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3434    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3435    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3436    new one is created.  */
3437
3438 static tree
3439 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3440                             tsubst_flags_t complain)
3441 {
3442   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3443       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3444           != TEMPLATE_PARM_LEVEL (index) - levels)
3445       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3446     {
3447       tree orig_decl = TEMPLATE_PARM_DECL (index);
3448       tree decl, t;
3449
3450       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3451                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3452       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3453       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3454       DECL_ARTIFICIAL (decl) = 1;
3455       SET_DECL_TEMPLATE_PARM_P (decl);
3456
3457       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3458                                      TEMPLATE_PARM_LEVEL (index) - levels,
3459                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3460                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3461                                      decl, type);
3462       TEMPLATE_PARM_DESCENDANTS (index) = t;
3463       TEMPLATE_PARM_PARAMETER_PACK (t) 
3464         = TEMPLATE_PARM_PARAMETER_PACK (index);
3465
3466         /* Template template parameters need this.  */
3467       if (TREE_CODE (decl) == TEMPLATE_DECL)
3468         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3469           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3470            args, complain);
3471     }
3472
3473   return TEMPLATE_PARM_DESCENDANTS (index);
3474 }
3475
3476 /* Process information from new template parameter PARM and append it
3477    to the LIST being built.  This new parameter is a non-type
3478    parameter iff IS_NON_TYPE is true. This new parameter is a
3479    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3480    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3481    parameter list PARM belongs to. This is used used to create a
3482    proper canonical type for the type of PARM that is to be created,
3483    iff PARM is a type.  If the size is not known, this parameter shall
3484    be set to 0.  */
3485
3486 tree
3487 process_template_parm (tree list, location_t parm_loc, tree parm,
3488                        bool is_non_type, bool is_parameter_pack,
3489                        unsigned num_template_parms)
3490 {
3491   tree decl = 0;
3492   tree defval;
3493   tree err_parm_list;
3494   int idx = 0;
3495
3496   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3497   defval = TREE_PURPOSE (parm);
3498
3499   if (list)
3500     {
3501       tree p = tree_last (list);
3502
3503       if (p && TREE_VALUE (p) != error_mark_node)
3504         {
3505           p = TREE_VALUE (p);
3506           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3507             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3508           else
3509             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3510         }
3511
3512       ++idx;
3513     }
3514   else
3515     idx = 0;
3516
3517   if (is_non_type)
3518     {
3519       parm = TREE_VALUE (parm);
3520
3521       SET_DECL_TEMPLATE_PARM_P (parm);
3522
3523       if (TREE_TYPE (parm) == error_mark_node)
3524         {
3525           err_parm_list = build_tree_list (defval, parm);
3526           TREE_VALUE (err_parm_list) = error_mark_node;
3527            return chainon (list, err_parm_list);
3528         }
3529       else
3530       {
3531         /* [temp.param]
3532
3533            The top-level cv-qualifiers on the template-parameter are
3534            ignored when determining its type.  */
3535         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3536         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3537           {
3538             err_parm_list = build_tree_list (defval, parm);
3539             TREE_VALUE (err_parm_list) = error_mark_node;
3540              return chainon (list, err_parm_list);
3541           }
3542
3543         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3544           {
3545             /* This template parameter is not a parameter pack, but it
3546                should be. Complain about "bare" parameter packs.  */
3547             check_for_bare_parameter_packs (TREE_TYPE (parm));
3548             
3549             /* Recover by calling this a parameter pack.  */
3550             is_parameter_pack = true;
3551           }
3552       }
3553
3554       /* A template parameter is not modifiable.  */
3555       TREE_CONSTANT (parm) = 1;
3556       TREE_READONLY (parm) = 1;
3557       decl = build_decl (parm_loc,
3558                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3559       TREE_CONSTANT (decl) = 1;
3560       TREE_READONLY (decl) = 1;
3561       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3562         = build_template_parm_index (idx, processing_template_decl,
3563                                      processing_template_decl,
3564                                      num_template_parms,
3565                                      decl, TREE_TYPE (parm));
3566
3567       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3568         = is_parameter_pack;
3569     }
3570   else
3571     {
3572       tree t;
3573       parm = TREE_VALUE (TREE_VALUE (parm));
3574
3575       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3576         {
3577           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3578           /* This is for distinguishing between real templates and template
3579              template parameters */
3580           TREE_TYPE (parm) = t;
3581           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3582           decl = parm;
3583         }
3584       else
3585         {
3586           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3587           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3588           decl = build_decl (parm_loc,
3589                              TYPE_DECL, parm, t);
3590         }
3591
3592       TYPE_NAME (t) = decl;
3593       TYPE_STUB_DECL (t) = decl;
3594       parm = decl;
3595       TEMPLATE_TYPE_PARM_INDEX (t)
3596         = build_template_parm_index (idx, processing_template_decl,
3597                                      processing_template_decl,
3598                                      num_template_parms,
3599                                      decl, TREE_TYPE (parm));
3600       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3601       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3602     }
3603   DECL_ARTIFICIAL (decl) = 1;
3604   SET_DECL_TEMPLATE_PARM_P (decl);
3605   pushdecl (decl);
3606   parm = build_tree_list (defval, parm);
3607   return chainon (list, parm);
3608 }
3609
3610 /* The end of a template parameter list has been reached.  Process the
3611    tree list into a parameter vector, converting each parameter into a more
3612    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3613    as PARM_DECLs.  */
3614
3615 tree
3616 end_template_parm_list (tree parms)
3617 {
3618   int nparms;
3619   tree parm, next;
3620   tree saved_parmlist = make_tree_vec (list_length (parms));
3621
3622   current_template_parms
3623     = tree_cons (size_int (processing_template_decl),
3624                  saved_parmlist, current_template_parms);
3625
3626   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3627     {
3628       next = TREE_CHAIN (parm);
3629       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3630       TREE_CHAIN (parm) = NULL_TREE;
3631     }
3632
3633   --processing_template_parmlist;
3634
3635   return saved_parmlist;
3636 }
3637
3638 /* Create a new type almost identical to TYPE but which has the
3639    following differences:
3640
3641      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3642      template sibling parameters of T.
3643
3644      2/ T has a new canonical type that matches the new number
3645      of sibling parms.
3646
3647      3/ From now on, T is going to be what lookups referring to the
3648      name of TYPE will return. No lookup should return TYPE anymore.
3649
3650    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3651
3652    This is a subroutine of fixup_template_parms.  */
3653
3654 static tree
3655 fixup_template_type_parm_type (tree type, int num_parms)
3656 {
3657   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3658   tree t;
3659   /* This is the decl which name is inserted into the symbol table for
3660      the template parm type. So whenever we lookup the type name, this
3661      is the DECL we get.  */
3662   tree decl;
3663
3664   /* Do not fix up the type twice.  */
3665   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3666     return type;
3667
3668   t = copy_type (type);
3669   decl = TYPE_NAME (t);
3670
3671   TYPE_MAIN_VARIANT (t) = t;
3672   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3673   TYPE_POINTER_TO (t) = 0;
3674   TYPE_REFERENCE_TO (t) = 0;
3675
3676   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3677                                    TEMPLATE_PARM_LEVEL (orig_idx),
3678                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3679                                    num_parms,
3680                                    decl, t);
3681   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3682   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3683   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3684
3685   TYPE_STUB_DECL (t) = decl;
3686   TEMPLATE_TYPE_DECL (t) = decl;
3687   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3688     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3689
3690   /* Update the type associated to the type name stored in the symbol
3691      table. Now, whenever the type name is looked up, the resulting
3692      type is properly fixed up.  */
3693   TREE_TYPE (decl) = t;
3694
3695   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3696
3697   return t;
3698 }
3699
3700 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3701    identical to I, but that is fixed up as to:
3702
3703    1/ carry the number of sibling parms (NUM_PARMS) of the template
3704    parm represented by I.
3705
3706    2/ replace all references to template parm types declared before I
3707    (in the same template parm list as I) by references to template
3708    parm types contained in ARGS. ARGS should contain the list of
3709    template parms that have been fixed up so far, in a form suitable
3710    to be passed to tsubst.
3711
3712    This is a subroutine of fixup_template_parms.  */
3713
3714 static tree
3715 fixup_template_parm_index (tree i, tree args, int num_parms)
3716 {
3717   tree index, decl, type;
3718
3719   if (i == NULL_TREE
3720       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3721       /* Do not fix up the index twice.  */
3722       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3723     return i;
3724
3725   decl = TEMPLATE_PARM_DECL (i);
3726   type = TREE_TYPE (decl);
3727
3728   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3729                                      TEMPLATE_PARM_LEVEL (i),
3730                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3731                                      num_parms,
3732                                      decl, type);
3733
3734   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3735   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3736
3737   type = tsubst (type, args, tf_none, NULL_TREE);
3738   
3739   TREE_TYPE (decl) = type;
3740   TREE_TYPE (index) = type;
3741
3742   return index;
3743 }
3744
3745 /* 
3746    This is a subroutine of fixup_template_parms.
3747
3748    It computes the canonical type of the type of the template
3749    parameter PARM_DESC and update all references to that type so that
3750    they use the newly computed canonical type. No access check is
3751    performed during the fixup. PARM_DESC is a TREE_LIST which
3752    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3753    default argument of the template parm if any. IDX is the index of
3754    the template parameter, starting at 0. NUM_PARMS is the number of
3755    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3756    TREE_VEC containing the full set of template parameters in a form
3757    suitable to be passed to substs functions as their ARGS
3758    argument. This is what current_template_args returns for a given
3759    template. The innermost vector of args in ARGLIST is the set of
3760    template parms that have been fixed up so far. This function adds
3761    the fixed up parameter into that vector.  */
3762
3763 static void
3764 fixup_template_parm (tree parm_desc,
3765                      int idx,
3766                      int num_parms,
3767                      tree arglist)
3768 {
3769   tree parm = TREE_VALUE (parm_desc);
3770   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3771
3772   push_deferring_access_checks (dk_no_check);
3773
3774   if (TREE_CODE (parm) == TYPE_DECL)
3775     {
3776       /* PARM is a template type parameter. Fix up its type, add
3777          the fixed-up template parm to the vector of fixed-up
3778          template parms so far, and substitute the fixed-up
3779          template parms into the default argument of this
3780          parameter.  */
3781       tree t =
3782         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3783       TREE_TYPE (parm) = t;
3784
3785       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3786     }
3787   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3788     {
3789       /* PARM is a template template parameter. This is going to
3790          be interesting.  */
3791       tree tparms, targs, innermost_args, t;
3792       int j;
3793
3794       /* First, fix up the parms of the template template parm
3795          because the parms are involved in defining the new canonical
3796          type of the template template parm.  */
3797
3798       /* So we need to substitute the template parm types that have
3799          been fixed up so far into the template parms of this template
3800          template parm. E.g, consider this:
3801
3802          template<class T, template<T u> class TT> class S;
3803
3804          In this case we want to substitute T into the
3805          template parameters of TT.
3806
3807          So let's walk the template parms of PARM here, and
3808          tsubst ARGLIST into into each of the template
3809          parms.   */
3810
3811       /* For this substitution we need to build the full set of
3812          template parameters and use that as arguments for the
3813          tsubsting function.  */
3814       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3815
3816       /* This will contain the innermost parms of PARM into which
3817          we have substituted so far.  */
3818       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3819       targs = add_to_template_args (arglist, innermost_args);
3820       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3821         {
3822           tree parameter;
3823
3824           parameter = TREE_VEC_ELT (tparms, j);
3825
3826           /* INNERMOST_ARGS needs to have at least the same number
3827              of elements as the index PARAMETER, ortherwise
3828              tsubsting into PARAMETER will result in partially
3829              instantiating it, reducing its tempate parm
3830              level. Let's tactically fill INNERMOST_ARGS for that
3831              purpose.  */
3832           TREE_VEC_ELT (innermost_args, j) =
3833             template_parm_to_arg (parameter);
3834
3835           fixup_template_parm (parameter, j,
3836                                TREE_VEC_LENGTH (tparms),
3837                                targs);
3838         }
3839
3840       /* Now fix up the type of the template template parm.  */
3841
3842       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3843       TREE_TYPE (parm) = t;
3844
3845       TREE_VEC_ELT (fixedup_args, idx) =
3846         template_parm_to_arg (parm_desc);
3847     }
3848   else if (TREE_CODE (parm) == PARM_DECL)
3849     {
3850       /* PARM is a non-type template parameter. We need to:
3851
3852        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3853        proper number of sibling parameters.
3854
3855        * Make lookups of the template parameter return a reference
3856        to the fixed-up index. No lookup should return references
3857        to the former index anymore.
3858
3859        * Substitute the template parms that got fixed up so far
3860
3861        * into the type of PARM.  */
3862
3863       tree index = DECL_INITIAL (parm);
3864
3865       /* PUSHED_DECL is the decl added to the symbol table with
3866          the name of the parameter. E,g:
3867              
3868          template<class T, T u> //#0
3869          auto my_function(T t) -> decltype(u); //#1
3870
3871          Here, when looking up u at //#1, we get the decl of u
3872          resulting from the declaration in #0. This is what
3873          PUSHED_DECL is. We need to replace the reference to the
3874          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3875          fixed-up TEMPLATE_PARM_INDEX.  */
3876       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3877
3878       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3879          fixup the type of PUSHED_DECL as well and luckily
3880          fixup_template_parm_index does it for us too.  */
3881       tree fixed_up_index =
3882         fixup_template_parm_index (index, arglist, num_parms);
3883
3884       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3885
3886       /* Add this fixed up PARM to the template parms we've fixed
3887          up so far and use that to substitute the fixed-up
3888          template parms into the type of PARM.  */
3889       TREE_VEC_ELT (fixedup_args, idx) =
3890         template_parm_to_arg (parm_desc);
3891       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3892                                  tf_none, NULL_TREE);
3893     }
3894
3895   TREE_PURPOSE (parm_desc) =
3896     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3897                          arglist, tf_none, parm);
3898
3899   pop_deferring_access_checks ();
3900 }
3901
3902 /* Walk the current template parms and properly compute the canonical
3903    types of the dependent types created during
3904    cp_parser_template_parameter_list.  */
3905
3906 void
3907 fixup_template_parms (void)
3908 {
3909   tree arglist;
3910   tree parameter_vec;
3911   tree fixedup_args;
3912   int i, num_parms;
3913
3914   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3915   if (parameter_vec == NULL_TREE)
3916     return;
3917
3918   num_parms = TREE_VEC_LENGTH (parameter_vec);
3919
3920   /* This vector contains the current innermost template parms that
3921      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3922      to be passed to tsubst* functions as their ARGS argument.  */
3923   fixedup_args = make_tree_vec (num_parms);
3924
3925   /* This vector contains the full set of template parms in a form
3926      suitable to be passed to substs functions as their ARGS
3927      argument.  */
3928   arglist = current_template_args ();
3929   arglist = add_outermost_template_args (arglist, fixedup_args);
3930
3931   /* Let's do the proper fixup now.  */
3932   for (i = 0; i < num_parms; ++i)
3933     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3934                          i, num_parms, arglist);
3935 }
3936
3937 /* end_template_decl is called after a template declaration is seen.  */
3938
3939 void
3940 end_template_decl (void)
3941 {
3942   reset_specialization ();
3943
3944   if (! processing_template_decl)
3945     return;
3946
3947   /* This matches the pushlevel in begin_template_parm_list.  */
3948   finish_scope ();
3949
3950   --processing_template_decl;
3951   current_template_parms = TREE_CHAIN (current_template_parms);
3952 }
3953
3954 /* Takes a TREE_LIST representing a template parameter and convert it
3955    into an argument suitable to be passed to the type substitution
3956    functions.  Note that If the TREE_LIST contains an error_mark
3957    node, the returned argument is error_mark_node.  */
3958
3959 static tree
3960 template_parm_to_arg (tree t)
3961 {
3962
3963   if (t == NULL_TREE
3964       || TREE_CODE (t) != TREE_LIST)
3965     return t;
3966
3967   if (error_operand_p (TREE_VALUE (t)))
3968     return error_mark_node;
3969
3970   t = TREE_VALUE (t);
3971
3972   if (TREE_CODE (t) == TYPE_DECL
3973       || TREE_CODE (t) == TEMPLATE_DECL)
3974     {
3975       t = TREE_TYPE (t);
3976
3977       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3978         {
3979           /* Turn this argument into a TYPE_ARGUMENT_PACK
3980              with a single element, which expands T.  */
3981           tree vec = make_tree_vec (1);
3982 #ifdef ENABLE_CHECKING
3983           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3984             (vec, TREE_VEC_LENGTH (vec));
3985 #endif
3986           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3987
3988           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3989           SET_ARGUMENT_PACK_ARGS (t, vec);
3990         }
3991     }
3992   else
3993     {
3994       t = DECL_INITIAL (t);
3995
3996       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3997         {
3998           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3999              with a single element, which expands T.  */
4000           tree vec = make_tree_vec (1);
4001           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
4002 #ifdef ENABLE_CHECKING
4003           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
4004             (vec, TREE_VEC_LENGTH (vec));
4005 #endif
4006           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4007
4008           t  = make_node (NONTYPE_ARGUMENT_PACK);
4009           SET_ARGUMENT_PACK_ARGS (t, vec);
4010           TREE_TYPE (t) = type;
4011         }
4012     }
4013   return t;
4014 }
4015
4016 /* This function returns TRUE if PARM_PACK is a template parameter
4017    pack and if ARG_PACK is what template_parm_to_arg returned when
4018    passed PARM_PACK.  */
4019
4020 static bool
4021 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
4022 {
4023   /* For clarity in the comments below let's use the representation
4024      argument_pack<elements>' to denote an argument pack and its
4025      elements.
4026
4027      In the 'if' block below, we want to detect cases where
4028      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
4029      check if ARG_PACK is an argument pack which sole element is
4030      the expansion of PARM_PACK.  That argument pack is typically
4031      created by template_parm_to_arg when passed a parameter
4032      pack.  */
4033
4034   if (arg_pack
4035       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
4036       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
4037     {
4038       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
4039       tree pattern = PACK_EXPANSION_PATTERN (expansion);
4040       /* So we have an argument_pack<P...>.  We want to test if P
4041          is actually PARM_PACK.  We will not use cp_tree_equal to
4042          test P and PARM_PACK because during type fixup (by
4043          fixup_template_parm) P can be a pre-fixup version of a
4044          type and PARM_PACK be its post-fixup version.
4045          cp_tree_equal would consider them as different even
4046          though we would want to consider them compatible for our
4047          precise purpose here.
4048
4049          Thus we are going to consider that P and PARM_PACK are
4050          compatible if they have the same DECL.  */
4051       if ((/* If ARG_PACK is a type parameter pack named by the
4052               same DECL as parm_pack ...  */
4053            (TYPE_P (pattern)
4054             && TYPE_P (parm_pack)
4055             && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
4056            /* ... or if PARM_PACK is a non-type parameter named by the
4057               same DECL as ARG_PACK.  Note that PARM_PACK being a
4058               non-type parameter means it's either a PARM_DECL or a
4059               TEMPLATE_PARM_INDEX.  */
4060            || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
4061                && ((TREE_CODE (parm_pack) == PARM_DECL
4062                     && (TEMPLATE_PARM_DECL (pattern)
4063                         == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
4064                    || (TREE_CODE (parm_pack) == TEMPLATE_PARM_INDEX
4065                        && (TEMPLATE_PARM_DECL (pattern)
4066                            == TEMPLATE_PARM_DECL (parm_pack))))))
4067           && template_parameter_pack_p (pattern))
4068         return true;
4069     }
4070   return false;
4071 }
4072
4073 /* Within the declaration of a template, return all levels of template
4074    parameters that apply.  The template parameters are represented as
4075    a TREE_VEC, in the form documented in cp-tree.h for template
4076    arguments.  */
4077
4078 static tree
4079 current_template_args (void)
4080 {
4081   tree header;
4082   tree args = NULL_TREE;
4083   int length = TMPL_PARMS_DEPTH (current_template_parms);
4084   int l = length;
4085
4086   /* If there is only one level of template parameters, we do not
4087      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4088      TREE_VEC containing the arguments.  */
4089   if (length > 1)
4090     args = make_tree_vec (length);
4091
4092   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4093     {
4094       tree a = copy_node (TREE_VALUE (header));
4095       int i;
4096
4097       TREE_TYPE (a) = NULL_TREE;
4098       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4099         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4100
4101 #ifdef ENABLE_CHECKING
4102       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4103 #endif
4104
4105       if (length > 1)
4106         TREE_VEC_ELT (args, --l) = a;
4107       else
4108         args = a;
4109     }
4110
4111     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4112       /* This can happen for template parms of a template template
4113          parameter, e.g:
4114
4115          template<template<class T, class U> class TT> struct S;
4116
4117          Consider the level of the parms of TT; T and U both have
4118          level 2; TT has no template parm of level 1. So in this case
4119          the first element of full_template_args is NULL_TREE. If we
4120          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4121          of 2. This will make tsubst wrongly consider that T and U
4122          have level 1. Instead, let's create a dummy vector as the
4123          first element of full_template_args so that TMPL_ARG_DEPTH
4124          returns the correct depth for args.  */
4125       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4126   return args;
4127 }
4128
4129 /* Update the declared TYPE by doing any lookups which were thought to be
4130    dependent, but are not now that we know the SCOPE of the declarator.  */
4131
4132 tree
4133 maybe_update_decl_type (tree orig_type, tree scope)
4134 {
4135   tree type = orig_type;
4136
4137   if (type == NULL_TREE)
4138     return type;
4139
4140   if (TREE_CODE (orig_type) == TYPE_DECL)
4141     type = TREE_TYPE (type);
4142
4143   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4144       && dependent_type_p (type)
4145       /* Don't bother building up the args in this case.  */
4146       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4147     {
4148       /* tsubst in the args corresponding to the template parameters,
4149          including auto if present.  Most things will be unchanged, but
4150          make_typename_type and tsubst_qualified_id will resolve
4151          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4152       tree args = current_template_args ();
4153       tree auto_node = type_uses_auto (type);
4154       tree pushed;
4155       if (auto_node)
4156         {
4157           tree auto_vec = make_tree_vec (1);
4158           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4159           args = add_to_template_args (args, auto_vec);
4160         }
4161       pushed = push_scope (scope);
4162       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4163       if (pushed)
4164         pop_scope (scope);
4165     }
4166
4167   if (type == error_mark_node)
4168     return orig_type;
4169
4170   if (TREE_CODE (orig_type) == TYPE_DECL)
4171     {
4172       if (same_type_p (type, TREE_TYPE (orig_type)))
4173         type = orig_type;
4174       else
4175         type = TYPE_NAME (type);
4176     }
4177   return type;
4178 }
4179
4180 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4181    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4182    a member template.  Used by push_template_decl below.  */
4183
4184 static tree
4185 build_template_decl (tree decl, tree parms, bool member_template_p)
4186 {
4187   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4188   DECL_TEMPLATE_PARMS (tmpl) = parms;
4189   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4190   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4191   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4192
4193   return tmpl;
4194 }
4195
4196 struct template_parm_data
4197 {
4198   /* The level of the template parameters we are currently
4199      processing.  */
4200   int level;
4201
4202   /* The index of the specialization argument we are currently
4203      processing.  */
4204   int current_arg;
4205
4206   /* An array whose size is the number of template parameters.  The
4207      elements are nonzero if the parameter has been used in any one
4208      of the arguments processed so far.  */
4209   int* parms;
4210
4211   /* An array whose size is the number of template arguments.  The
4212      elements are nonzero if the argument makes use of template
4213      parameters of this level.  */
4214   int* arg_uses_template_parms;
4215 };
4216
4217 /* Subroutine of push_template_decl used to see if each template
4218    parameter in a partial specialization is used in the explicit
4219    argument list.  If T is of the LEVEL given in DATA (which is
4220    treated as a template_parm_data*), then DATA->PARMS is marked
4221    appropriately.  */
4222
4223 static int
4224 mark_template_parm (tree t, void* data)
4225 {
4226   int level;
4227   int idx;
4228   struct template_parm_data* tpd = (struct template_parm_data*) data;
4229
4230   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4231     {
4232       level = TEMPLATE_PARM_LEVEL (t);
4233       idx = TEMPLATE_PARM_IDX (t);
4234     }
4235   else
4236     {
4237       level = TEMPLATE_TYPE_LEVEL (t);
4238       idx = TEMPLATE_TYPE_IDX (t);
4239     }
4240
4241   if (level == tpd->level)
4242     {
4243       tpd->parms[idx] = 1;
4244       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4245     }
4246
4247   /* Return zero so that for_each_template_parm will continue the
4248      traversal of the tree; we want to mark *every* template parm.  */
4249   return 0;
4250 }
4251
4252 /* Process the partial specialization DECL.  */
4253
4254 static tree
4255 process_partial_specialization (tree decl)
4256 {
4257   tree type = TREE_TYPE (decl);
4258   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4259   tree specargs = CLASSTYPE_TI_ARGS (type);
4260   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4261   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4262   tree inner_parms;
4263   tree inst;
4264   int nargs = TREE_VEC_LENGTH (inner_args);
4265   int ntparms;
4266   int  i;
4267   bool did_error_intro = false;
4268   struct template_parm_data tpd;
4269   struct template_parm_data tpd2;
4270
4271   gcc_assert (current_template_parms);
4272
4273   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4274   ntparms = TREE_VEC_LENGTH (inner_parms);
4275
4276   /* We check that each of the template parameters given in the
4277      partial specialization is used in the argument list to the
4278      specialization.  For example:
4279
4280        template <class T> struct S;
4281        template <class T> struct S<T*>;
4282
4283      The second declaration is OK because `T*' uses the template
4284      parameter T, whereas
4285
4286        template <class T> struct S<int>;
4287
4288      is no good.  Even trickier is:
4289
4290        template <class T>
4291        struct S1
4292        {
4293           template <class U>
4294           struct S2;
4295           template <class U>
4296           struct S2<T>;
4297        };
4298
4299      The S2<T> declaration is actually invalid; it is a
4300      full-specialization.  Of course,
4301
4302           template <class U>
4303           struct S2<T (*)(U)>;
4304
4305      or some such would have been OK.  */
4306   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4307   tpd.parms = XALLOCAVEC (int, ntparms);
4308   memset (tpd.parms, 0, sizeof (int) * ntparms);
4309
4310   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4311   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4312   for (i = 0; i < nargs; ++i)
4313     {
4314       tpd.current_arg = i;
4315       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4316                               &mark_template_parm,
4317                               &tpd,
4318                               NULL,
4319                               /*include_nondeduced_p=*/false);
4320     }
4321   for (i = 0; i < ntparms; ++i)
4322     if (tpd.parms[i] == 0)
4323       {
4324         /* One of the template parms was not used in the
4325            specialization.  */
4326         if (!did_error_intro)
4327           {
4328             error ("template parameters not used in partial specialization:");
4329             did_error_intro = true;
4330           }
4331
4332         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4333       }
4334
4335   if (did_error_intro)
4336     return error_mark_node;
4337
4338   /* [temp.class.spec]
4339
4340      The argument list of the specialization shall not be identical to
4341      the implicit argument list of the primary template.  */
4342   if (comp_template_args
4343       (inner_args,
4344        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4345                                                    (maintmpl)))))
4346     error ("partial specialization %qT does not specialize any template arguments", type);
4347
4348   /* [temp.class.spec]
4349
4350      A partially specialized non-type argument expression shall not
4351      involve template parameters of the partial specialization except
4352      when the argument expression is a simple identifier.
4353
4354      The type of a template parameter corresponding to a specialized
4355      non-type argument shall not be dependent on a parameter of the
4356      specialization. 
4357
4358      Also, we verify that pack expansions only occur at the
4359      end of the argument list.  */
4360   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4361   tpd2.parms = 0;
4362   for (i = 0; i < nargs; ++i)
4363     {
4364       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4365       tree arg = TREE_VEC_ELT (inner_args, i);
4366       tree packed_args = NULL_TREE;
4367       int j, len = 1;
4368
4369       if (ARGUMENT_PACK_P (arg))
4370         {
4371           /* Extract the arguments from the argument pack. We'll be
4372              iterating over these in the following loop.  */
4373           packed_args = ARGUMENT_PACK_ARGS (arg);
4374           len = TREE_VEC_LENGTH (packed_args);
4375         }
4376
4377       for (j = 0; j < len; j++)
4378         {
4379           if (packed_args)
4380             /* Get the Jth argument in the parameter pack.  */
4381             arg = TREE_VEC_ELT (packed_args, j);
4382
4383           if (PACK_EXPANSION_P (arg))
4384             {
4385               /* Pack expansions must come at the end of the
4386                  argument list.  */
4387               if ((packed_args && j < len - 1)
4388                   || (!packed_args && i < nargs - 1))
4389                 {
4390                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4391                     error ("parameter pack argument %qE must be at the "
4392                            "end of the template argument list", arg);
4393                   else
4394                     error ("parameter pack argument %qT must be at the "
4395                            "end of the template argument list", arg);
4396                 }
4397             }
4398
4399           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4400             /* We only care about the pattern.  */
4401             arg = PACK_EXPANSION_PATTERN (arg);
4402
4403           if (/* These first two lines are the `non-type' bit.  */
4404               !TYPE_P (arg)
4405               && TREE_CODE (arg) != TEMPLATE_DECL
4406               /* This next line is the `argument expression is not just a
4407                  simple identifier' condition and also the `specialized
4408                  non-type argument' bit.  */
4409               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4410             {
4411               if ((!packed_args && tpd.arg_uses_template_parms[i])
4412                   || (packed_args && uses_template_parms (arg)))
4413                 error ("template argument %qE involves template parameter(s)",
4414                        arg);
4415               else 
4416                 {
4417                   /* Look at the corresponding template parameter,
4418                      marking which template parameters its type depends
4419                      upon.  */
4420                   tree type = TREE_TYPE (parm);
4421
4422                   if (!tpd2.parms)
4423                     {
4424                       /* We haven't yet initialized TPD2.  Do so now.  */
4425                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4426                       /* The number of parameters here is the number in the
4427                          main template, which, as checked in the assertion
4428                          above, is NARGS.  */
4429                       tpd2.parms = XALLOCAVEC (int, nargs);
4430                       tpd2.level = 
4431                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4432                     }
4433
4434                   /* Mark the template parameters.  But this time, we're
4435                      looking for the template parameters of the main
4436                      template, not in the specialization.  */
4437                   tpd2.current_arg = i;
4438                   tpd2.arg_uses_template_parms[i] = 0;
4439                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4440                   for_each_template_parm (type,
4441                                           &mark_template_parm,
4442                                           &tpd2,
4443                                           NULL,
4444                                           /*include_nondeduced_p=*/false);
4445
4446                   if (tpd2.arg_uses_template_parms [i])
4447                     {
4448                       /* The type depended on some template parameters.
4449                          If they are fully specialized in the
4450                          specialization, that's OK.  */
4451                       int j;
4452                       int count = 0;
4453                       for (j = 0; j < nargs; ++j)
4454                         if (tpd2.parms[j] != 0
4455                             && tpd.arg_uses_template_parms [j])
4456                           ++count;
4457                       if (count != 0)
4458                         error_n (input_location, count,
4459                                  "type %qT of template argument %qE depends "
4460                                  "on a template parameter",
4461                                  "type %qT of template argument %qE depends "
4462                                  "on template parameters",
4463                                  type,
4464                                  arg);
4465                     }
4466                 }
4467             }
4468         }
4469     }
4470
4471   /* We should only get here once.  */
4472   gcc_assert (!COMPLETE_TYPE_P (type));
4473
4474   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4475     = tree_cons (specargs, inner_parms,
4476                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4477   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4478
4479   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4480        inst = TREE_CHAIN (inst))
4481     {
4482       tree inst_type = TREE_VALUE (inst);
4483       if (COMPLETE_TYPE_P (inst_type)
4484           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4485         {
4486           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4487           if (spec && TREE_TYPE (spec) == type)
4488             permerror (input_location,
4489                        "partial specialization of %qT after instantiation "
4490                        "of %qT", type, inst_type);
4491         }
4492     }
4493
4494   return decl;
4495 }
4496
4497 /* Check that a template declaration's use of default arguments and
4498    parameter packs is not invalid.  Here, PARMS are the template
4499    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4500    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4501    specialization.
4502    
4503
4504    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4505    declaration (but not a definition); 1 indicates a declaration, 2
4506    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4507    emitted for extraneous default arguments.
4508
4509    Returns TRUE if there were no errors found, FALSE otherwise. */
4510
4511 bool
4512 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4513                          int is_partial, int is_friend_decl)
4514 {
4515   const char *msg;
4516   int last_level_to_check;
4517   tree parm_level;
4518   bool no_errors = true;
4519
4520   /* [temp.param]
4521
4522      A default template-argument shall not be specified in a
4523      function template declaration or a function template definition, nor
4524      in the template-parameter-list of the definition of a member of a
4525      class template.  */
4526
4527   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4528     /* You can't have a function template declaration in a local
4529        scope, nor you can you define a member of a class template in a
4530        local scope.  */
4531     return true;
4532
4533   if (current_class_type
4534       && !TYPE_BEING_DEFINED (current_class_type)
4535       && DECL_LANG_SPECIFIC (decl)
4536       && DECL_DECLARES_FUNCTION_P (decl)
4537       /* If this is either a friend defined in the scope of the class
4538          or a member function.  */
4539       && (DECL_FUNCTION_MEMBER_P (decl)
4540           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4541           : DECL_FRIEND_CONTEXT (decl)
4542           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4543           : false)
4544       /* And, if it was a member function, it really was defined in
4545          the scope of the class.  */
4546       && (!DECL_FUNCTION_MEMBER_P (decl)
4547           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4548     /* We already checked these parameters when the template was
4549        declared, so there's no need to do it again now.  This function
4550        was defined in class scope, but we're processing it's body now
4551        that the class is complete.  */
4552     return true;
4553
4554   /* Core issue 226 (C++0x only): the following only applies to class
4555      templates.  */
4556   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4557     {
4558       /* [temp.param]
4559
4560          If a template-parameter has a default template-argument, all
4561          subsequent template-parameters shall have a default
4562          template-argument supplied.  */
4563       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4564         {
4565           tree inner_parms = TREE_VALUE (parm_level);
4566           int ntparms = TREE_VEC_LENGTH (inner_parms);
4567           int seen_def_arg_p = 0;
4568           int i;
4569
4570           for (i = 0; i < ntparms; ++i)
4571             {
4572               tree parm = TREE_VEC_ELT (inner_parms, i);
4573
4574               if (parm == error_mark_node)
4575                 continue;
4576
4577               if (TREE_PURPOSE (parm))
4578                 seen_def_arg_p = 1;
4579               else if (seen_def_arg_p
4580                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4581                 {
4582                   error ("no default argument for %qD", TREE_VALUE (parm));
4583                   /* For better subsequent error-recovery, we indicate that
4584                      there should have been a default argument.  */
4585                   TREE_PURPOSE (parm) = error_mark_node;
4586                   no_errors = false;
4587                 }
4588               else if (is_primary
4589                        && !is_partial
4590                        && !is_friend_decl
4591                        /* Don't complain about an enclosing partial
4592                           specialization.  */
4593                        && parm_level == parms
4594                        && TREE_CODE (decl) == TYPE_DECL
4595                        && i < ntparms - 1
4596                        && template_parameter_pack_p (TREE_VALUE (parm)))
4597                 {
4598                   /* A primary class template can only have one
4599                      parameter pack, at the end of the template
4600                      parameter list.  */
4601
4602                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4603                     error ("parameter pack %qE must be at the end of the"
4604                            " template parameter list", TREE_VALUE (parm));
4605                   else
4606                     error ("parameter pack %qT must be at the end of the"
4607                            " template parameter list", 
4608                            TREE_TYPE (TREE_VALUE (parm)));
4609
4610                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4611                     = error_mark_node;
4612                   no_errors = false;
4613                 }
4614             }
4615         }
4616     }
4617
4618   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4619       || is_partial 
4620       || !is_primary
4621       || is_friend_decl)
4622     /* For an ordinary class template, default template arguments are
4623        allowed at the innermost level, e.g.:
4624          template <class T = int>
4625          struct S {};
4626        but, in a partial specialization, they're not allowed even
4627        there, as we have in [temp.class.spec]:
4628
4629          The template parameter list of a specialization shall not
4630          contain default template argument values.
4631
4632        So, for a partial specialization, or for a function template
4633        (in C++98/C++03), we look at all of them.  */
4634     ;
4635   else
4636     /* But, for a primary class template that is not a partial
4637        specialization we look at all template parameters except the
4638        innermost ones.  */
4639     parms = TREE_CHAIN (parms);
4640
4641   /* Figure out what error message to issue.  */
4642   if (is_friend_decl == 2)
4643     msg = G_("default template arguments may not be used in function template "
4644              "friend re-declaration");
4645   else if (is_friend_decl)
4646     msg = G_("default template arguments may not be used in function template "
4647              "friend declarations");
4648   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4649     msg = G_("default template arguments may not be used in function templates "
4650              "without -std=c++0x or -std=gnu++0x");
4651   else if (is_partial)
4652     msg = G_("default template arguments may not be used in "
4653              "partial specializations");
4654   else
4655     msg = G_("default argument for template parameter for class enclosing %qD");
4656
4657   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4658     /* If we're inside a class definition, there's no need to
4659        examine the parameters to the class itself.  On the one
4660        hand, they will be checked when the class is defined, and,
4661        on the other, default arguments are valid in things like:
4662          template <class T = double>
4663          struct S { template <class U> void f(U); };
4664        Here the default argument for `S' has no bearing on the
4665        declaration of `f'.  */
4666     last_level_to_check = template_class_depth (current_class_type) + 1;
4667   else
4668     /* Check everything.  */
4669     last_level_to_check = 0;
4670
4671   for (parm_level = parms;
4672        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4673        parm_level = TREE_CHAIN (parm_level))
4674     {
4675       tree inner_parms = TREE_VALUE (parm_level);
4676       int i;
4677       int ntparms;
4678
4679       ntparms = TREE_VEC_LENGTH (inner_parms);
4680       for (i = 0; i < ntparms; ++i)
4681         {
4682           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4683             continue;
4684
4685           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4686             {
4687               if (msg)
4688                 {
4689                   no_errors = false;
4690                   if (is_friend_decl == 2)
4691                     return no_errors;
4692
4693                   error (msg, decl);
4694                   msg = 0;
4695                 }
4696
4697               /* Clear out the default argument so that we are not
4698                  confused later.  */
4699               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4700             }
4701         }
4702
4703       /* At this point, if we're still interested in issuing messages,
4704          they must apply to classes surrounding the object declared.  */
4705       if (msg)
4706         msg = G_("default argument for template parameter for class "
4707                  "enclosing %qD");
4708     }
4709
4710   return no_errors;
4711 }
4712
4713 /* Worker for push_template_decl_real, called via
4714    for_each_template_parm.  DATA is really an int, indicating the
4715    level of the parameters we are interested in.  If T is a template
4716    parameter of that level, return nonzero.  */
4717
4718 static int
4719 template_parm_this_level_p (tree t, void* data)
4720 {
4721   int this_level = *(int *)data;
4722   int level;
4723
4724   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4725     level = TEMPLATE_PARM_LEVEL (t);
4726   else
4727     level = TEMPLATE_TYPE_LEVEL (t);
4728   return level == this_level;
4729 }
4730
4731 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4732    parameters given by current_template_args, or reuses a
4733    previously existing one, if appropriate.  Returns the DECL, or an
4734    equivalent one, if it is replaced via a call to duplicate_decls.
4735
4736    If IS_FRIEND is true, DECL is a friend declaration.  */
4737
4738 tree
4739 push_template_decl_real (tree decl, bool is_friend)
4740 {
4741   tree tmpl;
4742   tree args;
4743   tree info;
4744   tree ctx;
4745   int primary;
4746   int is_partial;
4747   int new_template_p = 0;
4748   /* True if the template is a member template, in the sense of
4749      [temp.mem].  */
4750   bool member_template_p = false;
4751
4752   if (decl == error_mark_node || !current_template_parms)
4753     return error_mark_node;
4754
4755   /* See if this is a partial specialization.  */
4756   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4757                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4758                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4759
4760   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4761     is_friend = true;
4762
4763   if (is_friend)
4764     /* For a friend, we want the context of the friend function, not
4765        the type of which it is a friend.  */
4766     ctx = CP_DECL_CONTEXT (decl);
4767   else if (CP_DECL_CONTEXT (decl)
4768            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4769     /* In the case of a virtual function, we want the class in which
4770        it is defined.  */
4771     ctx = CP_DECL_CONTEXT (decl);
4772   else
4773     /* Otherwise, if we're currently defining some class, the DECL
4774        is assumed to be a member of the class.  */
4775     ctx = current_scope ();
4776
4777   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4778     ctx = NULL_TREE;
4779
4780   if (!DECL_CONTEXT (decl))
4781     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4782
4783   /* See if this is a primary template.  */
4784   if (is_friend && ctx)
4785     /* A friend template that specifies a class context, i.e.
4786          template <typename T> friend void A<T>::f();
4787        is not primary.  */
4788     primary = 0;
4789   else
4790     primary = template_parm_scope_p ();
4791
4792   if (primary)
4793     {
4794       if (DECL_CLASS_SCOPE_P (decl))
4795         member_template_p = true;
4796       if (TREE_CODE (decl) == TYPE_DECL
4797           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4798         {
4799           error ("template class without a name");
4800           return error_mark_node;
4801         }
4802       else if (TREE_CODE (decl) == FUNCTION_DECL)
4803         {
4804           if (DECL_DESTRUCTOR_P (decl))
4805             {
4806               /* [temp.mem]
4807
4808                  A destructor shall not be a member template.  */
4809               error ("destructor %qD declared as member template", decl);
4810               return error_mark_node;
4811             }
4812           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4813               && (!prototype_p (TREE_TYPE (decl))
4814                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4815                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4816                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4817                       == void_list_node)))
4818             {
4819               /* [basic.stc.dynamic.allocation]
4820
4821                  An allocation function can be a function
4822                  template. ... Template allocation functions shall
4823                  have two or more parameters.  */
4824               error ("invalid template declaration of %qD", decl);
4825               return error_mark_node;
4826             }
4827         }
4828       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4829                && CLASS_TYPE_P (TREE_TYPE (decl)))
4830         /* OK */;
4831       else
4832         {
4833           error ("template declaration of %q#D", decl);
4834           return error_mark_node;
4835         }
4836     }
4837
4838   /* Check to see that the rules regarding the use of default
4839      arguments are not being violated.  */
4840   check_default_tmpl_args (decl, current_template_parms,
4841                            primary, is_partial, /*is_friend_decl=*/0);
4842
4843   /* Ensure that there are no parameter packs in the type of this
4844      declaration that have not been expanded.  */
4845   if (TREE_CODE (decl) == FUNCTION_DECL)
4846     {
4847       /* Check each of the arguments individually to see if there are
4848          any bare parameter packs.  */
4849       tree type = TREE_TYPE (decl);
4850       tree arg = DECL_ARGUMENTS (decl);
4851       tree argtype = TYPE_ARG_TYPES (type);
4852
4853       while (arg && argtype)
4854         {
4855           if (!FUNCTION_PARAMETER_PACK_P (arg)
4856               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4857             {
4858             /* This is a PARM_DECL that contains unexpanded parameter
4859                packs. We have already complained about this in the
4860                check_for_bare_parameter_packs call, so just replace
4861                these types with ERROR_MARK_NODE.  */
4862               TREE_TYPE (arg) = error_mark_node;
4863               TREE_VALUE (argtype) = error_mark_node;
4864             }
4865
4866           arg = DECL_CHAIN (arg);
4867           argtype = TREE_CHAIN (argtype);
4868         }
4869
4870       /* Check for bare parameter packs in the return type and the
4871          exception specifiers.  */
4872       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4873         /* Errors were already issued, set return type to int
4874            as the frontend doesn't expect error_mark_node as
4875            the return type.  */
4876         TREE_TYPE (type) = integer_type_node;
4877       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4878         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4879     }
4880   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4881     {
4882       TREE_TYPE (decl) = error_mark_node;
4883       return error_mark_node;
4884     }
4885
4886   if (is_partial)
4887     return process_partial_specialization (decl);
4888
4889   args = current_template_args ();
4890
4891   if (!ctx
4892       || TREE_CODE (ctx) == FUNCTION_DECL
4893       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4894       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4895     {
4896       if (DECL_LANG_SPECIFIC (decl)
4897           && DECL_TEMPLATE_INFO (decl)
4898           && DECL_TI_TEMPLATE (decl))
4899         tmpl = DECL_TI_TEMPLATE (decl);
4900       /* If DECL is a TYPE_DECL for a class-template, then there won't
4901          be DECL_LANG_SPECIFIC.  The information equivalent to
4902          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4903       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4904                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4905                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4906         {
4907           /* Since a template declaration already existed for this
4908              class-type, we must be redeclaring it here.  Make sure
4909              that the redeclaration is valid.  */
4910           redeclare_class_template (TREE_TYPE (decl),
4911                                     current_template_parms);
4912           /* We don't need to create a new TEMPLATE_DECL; just use the
4913              one we already had.  */
4914           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4915         }
4916       else
4917         {
4918           tmpl = build_template_decl (decl, current_template_parms,
4919                                       member_template_p);
4920           new_template_p = 1;
4921
4922           if (DECL_LANG_SPECIFIC (decl)
4923               && DECL_TEMPLATE_SPECIALIZATION (decl))
4924             {
4925               /* A specialization of a member template of a template
4926                  class.  */
4927               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4928               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4929               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4930             }
4931         }
4932     }
4933   else
4934     {
4935       tree a, t, current, parms;
4936       int i;
4937       tree tinfo = get_template_info (decl);
4938
4939       if (!tinfo)
4940         {
4941           error ("template definition of non-template %q#D", decl);
4942           return error_mark_node;
4943         }
4944
4945       tmpl = TI_TEMPLATE (tinfo);
4946
4947       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4948           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4949           && DECL_TEMPLATE_SPECIALIZATION (decl)
4950           && DECL_MEMBER_TEMPLATE_P (tmpl))
4951         {
4952           tree new_tmpl;
4953
4954           /* The declaration is a specialization of a member
4955              template, declared outside the class.  Therefore, the
4956              innermost template arguments will be NULL, so we
4957              replace them with the arguments determined by the
4958              earlier call to check_explicit_specialization.  */
4959           args = DECL_TI_ARGS (decl);
4960
4961           new_tmpl
4962             = build_template_decl (decl, current_template_parms,
4963                                    member_template_p);
4964           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4965           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4966           DECL_TI_TEMPLATE (decl) = new_tmpl;
4967           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4968           DECL_TEMPLATE_INFO (new_tmpl)
4969             = build_template_info (tmpl, args);
4970
4971           register_specialization (new_tmpl,
4972                                    most_general_template (tmpl),
4973                                    args,
4974                                    is_friend, 0);
4975           return decl;
4976         }
4977
4978       /* Make sure the template headers we got make sense.  */
4979
4980       parms = DECL_TEMPLATE_PARMS (tmpl);
4981       i = TMPL_PARMS_DEPTH (parms);
4982       if (TMPL_ARGS_DEPTH (args) != i)
4983         {
4984           error ("expected %d levels of template parms for %q#D, got %d",
4985                  i, decl, TMPL_ARGS_DEPTH (args));
4986         }
4987       else
4988         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4989           {
4990             a = TMPL_ARGS_LEVEL (args, i);
4991             t = INNERMOST_TEMPLATE_PARMS (parms);
4992
4993             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4994               {
4995                 if (current == decl)
4996                   error ("got %d template parameters for %q#D",
4997                          TREE_VEC_LENGTH (a), decl);
4998                 else
4999                   error ("got %d template parameters for %q#T",
5000                          TREE_VEC_LENGTH (a), current);
5001                 error ("  but %d required", TREE_VEC_LENGTH (t));
5002                 return error_mark_node;
5003               }
5004
5005             if (current == decl)
5006               current = ctx;
5007             else if (current == NULL_TREE)
5008               /* Can happen in erroneous input.  */
5009               break;
5010             else
5011               current = (TYPE_P (current)
5012                          ? TYPE_CONTEXT (current)
5013                          : DECL_CONTEXT (current));
5014           }
5015
5016       /* Check that the parms are used in the appropriate qualifying scopes
5017          in the declarator.  */
5018       if (!comp_template_args
5019           (TI_ARGS (tinfo),
5020            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5021         {
5022           error ("\
5023 template arguments to %qD do not match original template %qD",
5024                  decl, DECL_TEMPLATE_RESULT (tmpl));
5025           if (!uses_template_parms (TI_ARGS (tinfo)))
5026             inform (input_location, "use template<> for an explicit specialization");
5027           /* Avoid crash in import_export_decl.  */
5028           DECL_INTERFACE_KNOWN (decl) = 1;
5029           return error_mark_node;
5030         }
5031     }
5032
5033   DECL_TEMPLATE_RESULT (tmpl) = decl;
5034   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5035
5036   /* Push template declarations for global functions and types.  Note
5037      that we do not try to push a global template friend declared in a
5038      template class; such a thing may well depend on the template
5039      parameters of the class.  */
5040   if (new_template_p && !ctx
5041       && !(is_friend && template_class_depth (current_class_type) > 0))
5042     {
5043       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5044       if (tmpl == error_mark_node)
5045         return error_mark_node;
5046
5047       /* Hide template friend classes that haven't been declared yet.  */
5048       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5049         {
5050           DECL_ANTICIPATED (tmpl) = 1;
5051           DECL_FRIEND_P (tmpl) = 1;
5052         }
5053     }
5054
5055   if (primary)
5056     {
5057       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5058       int i;
5059
5060       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5061       if (DECL_CONV_FN_P (tmpl))
5062         {
5063           int depth = TMPL_PARMS_DEPTH (parms);
5064
5065           /* It is a conversion operator. See if the type converted to
5066              depends on innermost template operands.  */
5067
5068           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5069                                          depth))
5070             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5071         }
5072
5073       /* Give template template parms a DECL_CONTEXT of the template
5074          for which they are a parameter.  */
5075       parms = INNERMOST_TEMPLATE_PARMS (parms);
5076       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5077         {
5078           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5079           if (TREE_CODE (parm) == TEMPLATE_DECL)
5080             DECL_CONTEXT (parm) = tmpl;
5081         }
5082     }
5083
5084   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5085      back to its most general template.  If TMPL is a specialization,
5086      ARGS may only have the innermost set of arguments.  Add the missing
5087      argument levels if necessary.  */
5088   if (DECL_TEMPLATE_INFO (tmpl))
5089     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5090
5091   info = build_template_info (tmpl, args);
5092
5093   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5094     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5095   else if (DECL_LANG_SPECIFIC (decl))
5096     DECL_TEMPLATE_INFO (decl) = info;
5097
5098   return DECL_TEMPLATE_RESULT (tmpl);
5099 }
5100
5101 tree
5102 push_template_decl (tree decl)
5103 {
5104   return push_template_decl_real (decl, false);
5105 }
5106
5107 /* Called when a class template TYPE is redeclared with the indicated
5108    template PARMS, e.g.:
5109
5110      template <class T> struct S;
5111      template <class T> struct S {};  */
5112
5113 bool
5114 redeclare_class_template (tree type, tree parms)
5115 {
5116   tree tmpl;
5117   tree tmpl_parms;
5118   int i;
5119
5120   if (!TYPE_TEMPLATE_INFO (type))
5121     {
5122       error ("%qT is not a template type", type);
5123       return false;
5124     }
5125
5126   tmpl = TYPE_TI_TEMPLATE (type);
5127   if (!PRIMARY_TEMPLATE_P (tmpl))
5128     /* The type is nested in some template class.  Nothing to worry
5129        about here; there are no new template parameters for the nested
5130        type.  */
5131     return true;
5132
5133   if (!parms)
5134     {
5135       error ("template specifiers not specified in declaration of %qD",
5136              tmpl);
5137       return false;
5138     }
5139
5140   parms = INNERMOST_TEMPLATE_PARMS (parms);
5141   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5142
5143   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5144     {
5145       error_n (input_location, TREE_VEC_LENGTH (parms),
5146                "redeclared with %d template parameter",
5147                "redeclared with %d template parameters",
5148                TREE_VEC_LENGTH (parms));
5149       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5150                 "previous declaration %q+D used %d template parameter",
5151                 "previous declaration %q+D used %d template parameters",
5152                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5153       return false;
5154     }
5155
5156   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5157     {
5158       tree tmpl_parm;
5159       tree parm;
5160       tree tmpl_default;
5161       tree parm_default;
5162
5163       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5164           || TREE_VEC_ELT (parms, i) == error_mark_node)
5165         continue;
5166
5167       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5168       if (tmpl_parm == error_mark_node)
5169         return false;
5170
5171       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5172       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5173       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5174
5175       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5176          TEMPLATE_DECL.  */
5177       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5178           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5179               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5180           || (TREE_CODE (tmpl_parm) != PARM_DECL
5181               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5182                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5183           || (TREE_CODE (tmpl_parm) == PARM_DECL
5184               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5185                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5186         {
5187           error ("template parameter %q+#D", tmpl_parm);
5188           error ("redeclared here as %q#D", parm);
5189           return false;
5190         }
5191
5192       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5193         {
5194           /* We have in [temp.param]:
5195
5196              A template-parameter may not be given default arguments
5197              by two different declarations in the same scope.  */
5198           error_at (input_location, "redefinition of default argument for %q#D", parm);
5199           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5200                   "original definition appeared here");
5201           return false;
5202         }
5203
5204       if (parm_default != NULL_TREE)
5205         /* Update the previous template parameters (which are the ones
5206            that will really count) with the new default value.  */
5207         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5208       else if (tmpl_default != NULL_TREE)
5209         /* Update the new parameters, too; they'll be used as the
5210            parameters for any members.  */
5211         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5212     }
5213
5214     return true;
5215 }
5216
5217 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5218    (possibly simplified) expression.  */
5219
5220 static tree
5221 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5222 {
5223   if (expr == NULL_TREE)
5224     return NULL_TREE;
5225
5226   /* If we're in a template, but EXPR isn't value dependent, simplify
5227      it.  We're supposed to treat:
5228
5229        template <typename T> void f(T[1 + 1]);
5230        template <typename T> void f(T[2]);
5231
5232      as two declarations of the same function, for example.  */
5233   if (processing_template_decl
5234       && !type_dependent_expression_p (expr)
5235       && potential_constant_expression (expr)
5236       && !value_dependent_expression_p (expr))
5237     {
5238       HOST_WIDE_INT saved_processing_template_decl;
5239
5240       saved_processing_template_decl = processing_template_decl;
5241       processing_template_decl = 0;
5242       expr = tsubst_copy_and_build (expr,
5243                                     /*args=*/NULL_TREE,
5244                                     complain,
5245                                     /*in_decl=*/NULL_TREE,
5246                                     /*function_p=*/false,
5247                                     /*integral_constant_expression_p=*/true);
5248       processing_template_decl = saved_processing_template_decl;
5249     }
5250   return expr;
5251 }
5252
5253 tree
5254 fold_non_dependent_expr (tree expr)
5255 {
5256   return fold_non_dependent_expr_sfinae (expr, tf_error);
5257 }
5258
5259 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5260    must be a function or a pointer-to-function type, as specified
5261    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5262    and check that the resulting function has external linkage.  */
5263
5264 static tree
5265 convert_nontype_argument_function (tree type, tree expr)
5266 {
5267   tree fns = expr;
5268   tree fn, fn_no_ptr;
5269
5270   fn = instantiate_type (type, fns, tf_none);
5271   if (fn == error_mark_node)
5272     return error_mark_node;
5273
5274   fn_no_ptr = fn;
5275   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5276     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5277   if (TREE_CODE (fn_no_ptr) == BASELINK)
5278     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5279  
5280   /* [temp.arg.nontype]/1
5281
5282      A template-argument for a non-type, non-template template-parameter
5283      shall be one of:
5284      [...]
5285      -- the address of an object or function with external linkage.  */
5286   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5287     {
5288       error ("%qE is not a valid template argument for type %qT "
5289              "because function %qD has not external linkage",
5290              expr, type, fn_no_ptr);
5291       return NULL_TREE;
5292     }
5293
5294   return fn;
5295 }
5296
5297 /* Subroutine of convert_nontype_argument.
5298    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5299    Emit an error otherwise.  */
5300
5301 static bool
5302 check_valid_ptrmem_cst_expr (tree type, tree expr,
5303                              tsubst_flags_t complain)
5304 {
5305   STRIP_NOPS (expr);
5306   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5307     return true;
5308   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5309     return true;
5310   if (complain & tf_error)
5311     {
5312       error ("%qE is not a valid template argument for type %qT",
5313              expr, type);
5314       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5315     }
5316   return false;
5317 }
5318
5319 /* Returns TRUE iff the address of OP is value-dependent.
5320
5321    14.6.2.4 [temp.dep.temp]:
5322    A non-integral non-type template-argument is dependent if its type is
5323    dependent or it has either of the following forms
5324      qualified-id
5325      & qualified-id
5326    and contains a nested-name-specifier which specifies a class-name that
5327    names a dependent type.
5328
5329    We generalize this to just say that the address of a member of a
5330    dependent class is value-dependent; the above doesn't cover the
5331    address of a static data member named with an unqualified-id.  */
5332
5333 static bool
5334 has_value_dependent_address (tree op)
5335 {
5336   /* We could use get_inner_reference here, but there's no need;
5337      this is only relevant for template non-type arguments, which
5338      can only be expressed as &id-expression.  */
5339   if (DECL_P (op))
5340     {
5341       tree ctx = CP_DECL_CONTEXT (op);
5342       if (TYPE_P (ctx) && dependent_type_p (ctx))
5343         return true;
5344     }
5345
5346   return false;
5347 }
5348
5349 /* The next set of functions are used for providing helpful explanatory
5350    diagnostics for failed overload resolution.  Their messages should be
5351    indented by two spaces for consistency with the messages in
5352    call.c  */
5353
5354 static int
5355 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5356 {
5357   return 0;
5358 }
5359
5360 static int
5361 unify_parameter_deduction_failure (bool explain_p, tree parm)
5362 {
5363   if (explain_p)
5364     inform (input_location,
5365             "  couldn't deduce template parameter %qD", parm);
5366   return 1;
5367 }
5368
5369 static int
5370 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5371 {
5372   return 1;
5373 }
5374
5375 static int
5376 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5377 {
5378   if (explain_p)
5379     inform (input_location,
5380             "  types %qT and %qT have incompatible cv-qualifiers",
5381             parm, arg);
5382   return 1;
5383 }
5384
5385 static int
5386 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5387 {
5388   if (explain_p)
5389     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5390   return 1;
5391 }
5392
5393 static int
5394 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5395 {
5396   if (explain_p)
5397     inform (input_location,
5398             "  template parameter %qD is not a parameter pack, but "
5399             "argument %qD is",
5400             parm, arg);
5401   return 1;
5402 }
5403
5404 static int
5405 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5406 {
5407   if (explain_p)
5408     inform (input_location,
5409             "  template argument %qE does not match "
5410             "pointer-to-member constant %qE",
5411             arg, parm);
5412   return 1;
5413 }
5414
5415 static int
5416 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5417 {
5418   if (explain_p)
5419     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5420   return 1;
5421 }
5422
5423 static int
5424 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5425 {
5426   if (explain_p)
5427     inform (input_location,
5428             "  inconsistent parameter pack deduction with %qT and %qT",
5429             old_arg, new_arg);
5430   return 1;
5431 }
5432
5433 static int
5434 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5435 {
5436   if (explain_p)
5437     inform (input_location,
5438             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5439             parm, first, second);
5440   return 1;
5441 }
5442
5443 static int
5444 unify_vla_arg (bool explain_p, tree arg)
5445 {
5446   if (explain_p)
5447     inform (input_location,
5448             "  variable-sized array type %qT is not "
5449             "a valid template argument",
5450             arg);
5451   return 1;
5452 }
5453
5454 static int
5455 unify_method_type_error (bool explain_p, tree arg)
5456 {
5457   if (explain_p)
5458     inform (input_location,
5459             "  member function type %qT is not a valid template argument",
5460             arg);
5461   return 1;
5462 }
5463
5464 static int
5465 unify_arity (bool explain_p, int have, int wanted)
5466 {
5467   if (explain_p)
5468     inform_n (input_location, wanted,
5469               "  candidate expects %d argument, %d provided",
5470               "  candidate expects %d arguments, %d provided",
5471               wanted, have);
5472   return 1;
5473 }
5474
5475 static int
5476 unify_too_many_arguments (bool explain_p, int have, int wanted)
5477 {
5478   return unify_arity (explain_p, have, wanted);
5479 }
5480
5481 static int
5482 unify_too_few_arguments (bool explain_p, int have, int wanted)
5483 {
5484   return unify_arity (explain_p, have, wanted);
5485 }
5486
5487 static int
5488 unify_arg_conversion (bool explain_p, tree to_type,
5489                       tree from_type, tree arg)
5490 {
5491   if (explain_p)
5492     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5493             arg, from_type, to_type);
5494   return 1;
5495 }
5496
5497 static int
5498 unify_no_common_base (bool explain_p, enum template_base_result r,
5499                       tree parm, tree arg)
5500 {
5501   if (explain_p)
5502     switch (r)
5503       {
5504       case tbr_ambiguous_baseclass:
5505         inform (input_location, "  %qT is an ambiguous base class of %qT",
5506                 arg, parm);
5507         break;
5508       default:
5509         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5510         break;
5511       }
5512   return 1;
5513 }
5514
5515 static int
5516 unify_inconsistent_template_template_parameters (bool explain_p)
5517 {
5518   if (explain_p)
5519     inform (input_location,
5520             "  template parameters of a template template argument are "
5521             "inconsistent with other deduced template arguments");
5522   return 1;
5523 }
5524
5525 static int
5526 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5527 {
5528   if (explain_p)
5529     inform (input_location,
5530             "  can't deduce a template for %qT from non-template type %qT",
5531             parm, arg);
5532   return 1;
5533 }
5534
5535 static int
5536 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5537 {
5538   if (explain_p)
5539     inform (input_location,
5540             "  template argument %qE does not match %qD", arg, parm);
5541   return 1;
5542 }
5543
5544 static int
5545 unify_overload_resolution_failure (bool explain_p, tree arg)
5546 {
5547   if (explain_p)
5548     inform (input_location,
5549             "  could not resolve address from overloaded function %qE",
5550             arg);
5551   return 1;
5552 }
5553
5554 /* Attempt to convert the non-type template parameter EXPR to the
5555    indicated TYPE.  If the conversion is successful, return the
5556    converted value.  If the conversion is unsuccessful, return
5557    NULL_TREE if we issued an error message, or error_mark_node if we
5558    did not.  We issue error messages for out-and-out bad template
5559    parameters, but not simply because the conversion failed, since we
5560    might be just trying to do argument deduction.  Both TYPE and EXPR
5561    must be non-dependent.
5562
5563    The conversion follows the special rules described in
5564    [temp.arg.nontype], and it is much more strict than an implicit
5565    conversion.
5566
5567    This function is called twice for each template argument (see
5568    lookup_template_class for a more accurate description of this
5569    problem). This means that we need to handle expressions which
5570    are not valid in a C++ source, but can be created from the
5571    first call (for instance, casts to perform conversions). These
5572    hacks can go away after we fix the double coercion problem.  */
5573
5574 static tree
5575 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5576 {
5577   tree expr_type;
5578
5579   /* Detect immediately string literals as invalid non-type argument.
5580      This special-case is not needed for correctness (we would easily
5581      catch this later), but only to provide better diagnostic for this
5582      common user mistake. As suggested by DR 100, we do not mention
5583      linkage issues in the diagnostic as this is not the point.  */
5584   /* FIXME we're making this OK.  */
5585   if (TREE_CODE (expr) == STRING_CST)
5586     {
5587       if (complain & tf_error)
5588         error ("%qE is not a valid template argument for type %qT "
5589                "because string literals can never be used in this context",
5590                expr, type);
5591       return NULL_TREE;
5592     }
5593
5594   /* Add the ADDR_EXPR now for the benefit of
5595      value_dependent_expression_p.  */
5596   if (TYPE_PTROBV_P (type)
5597       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5598     expr = decay_conversion (expr);
5599
5600   /* If we are in a template, EXPR may be non-dependent, but still
5601      have a syntactic, rather than semantic, form.  For example, EXPR
5602      might be a SCOPE_REF, rather than the VAR_DECL to which the
5603      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5604      so that access checking can be performed when the template is
5605      instantiated -- but here we need the resolved form so that we can
5606      convert the argument.  */
5607   if (TYPE_REF_OBJ_P (type)
5608       && has_value_dependent_address (expr))
5609     /* If we want the address and it's value-dependent, don't fold.  */;
5610   else if (!type_unknown_p (expr))
5611     expr = fold_non_dependent_expr_sfinae (expr, complain);
5612   if (error_operand_p (expr))
5613     return error_mark_node;
5614   expr_type = TREE_TYPE (expr);
5615   if (TREE_CODE (type) == REFERENCE_TYPE)
5616     expr = mark_lvalue_use (expr);
5617   else
5618     expr = mark_rvalue_use (expr);
5619
5620   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5621      to a non-type argument of "nullptr".  */
5622   if (expr == nullptr_node
5623       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5624     expr = convert (type, expr);
5625
5626   /* In C++11, non-type template arguments can be arbitrary constant
5627      expressions.  But don't fold a PTRMEM_CST to a CONSTRUCTOR yet.  */
5628   if (cxx_dialect >= cxx0x && TREE_CODE (expr) != PTRMEM_CST)
5629     expr = maybe_constant_value (expr);
5630
5631   /* HACK: Due to double coercion, we can get a
5632      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5633      which is the tree that we built on the first call (see
5634      below when coercing to reference to object or to reference to
5635      function). We just strip everything and get to the arg.
5636      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5637      for examples.  */
5638   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5639     {
5640       tree probe_type, probe = expr;
5641       if (REFERENCE_REF_P (probe))
5642         probe = TREE_OPERAND (probe, 0);
5643       probe_type = TREE_TYPE (probe);
5644       if (TREE_CODE (probe) == NOP_EXPR)
5645         {
5646           /* ??? Maybe we could use convert_from_reference here, but we
5647              would need to relax its constraints because the NOP_EXPR
5648              could actually change the type to something more cv-qualified,
5649              and this is not folded by convert_from_reference.  */
5650           tree addr = TREE_OPERAND (probe, 0);
5651           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5652           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5653           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5654           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5655                       (TREE_TYPE (probe_type),
5656                        TREE_TYPE (TREE_TYPE (addr))));
5657
5658           expr = TREE_OPERAND (addr, 0);
5659           expr_type = TREE_TYPE (expr);
5660         }
5661     }
5662
5663   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5664      parameter is a pointer to object, through decay and
5665      qualification conversion. Let's strip everything.  */
5666   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5667     {
5668       STRIP_NOPS (expr);
5669       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5670       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5671       /* Skip the ADDR_EXPR only if it is part of the decay for
5672          an array. Otherwise, it is part of the original argument
5673          in the source code.  */
5674       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5675         expr = TREE_OPERAND (expr, 0);
5676       expr_type = TREE_TYPE (expr);
5677     }
5678
5679   /* [temp.arg.nontype]/5, bullet 1
5680
5681      For a non-type template-parameter of integral or enumeration type,
5682      integral promotions (_conv.prom_) and integral conversions
5683      (_conv.integral_) are applied.  */
5684   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5685     {
5686       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5687       t = maybe_constant_value (t);
5688       if (t != error_mark_node)
5689         expr = t;
5690
5691       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5692         return error_mark_node;
5693
5694       /* Notice that there are constant expressions like '4 % 0' which
5695          do not fold into integer constants.  */
5696       if (TREE_CODE (expr) != INTEGER_CST)
5697         {
5698           if (complain & tf_error)
5699             {
5700               int errs = errorcount, warns = warningcount;
5701               expr = cxx_constant_value (expr);
5702               if (errorcount > errs || warningcount > warns)
5703                 inform (EXPR_LOC_OR_HERE (expr),
5704                         "in template argument for type %qT ", type);
5705               if (expr == error_mark_node)
5706                 return NULL_TREE;
5707               /* else cxx_constant_value complained but gave us
5708                  a real constant, so go ahead.  */
5709               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5710             }
5711           else
5712             return NULL_TREE;
5713         }
5714     }
5715   /* [temp.arg.nontype]/5, bullet 2
5716
5717      For a non-type template-parameter of type pointer to object,
5718      qualification conversions (_conv.qual_) and the array-to-pointer
5719      conversion (_conv.array_) are applied.  */
5720   else if (TYPE_PTROBV_P (type))
5721     {
5722       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5723
5724          A template-argument for a non-type, non-template template-parameter
5725          shall be one of: [...]
5726
5727          -- the name of a non-type template-parameter;
5728          -- the address of an object or function with external linkage, [...]
5729             expressed as "& id-expression" where the & is optional if the name
5730             refers to a function or array, or if the corresponding
5731             template-parameter is a reference.
5732
5733         Here, we do not care about functions, as they are invalid anyway
5734         for a parameter of type pointer-to-object.  */
5735
5736       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5737         /* Non-type template parameters are OK.  */
5738         ;
5739       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5740         /* Null pointer values are OK in C++11.  */;
5741       else if (TREE_CODE (expr) != ADDR_EXPR
5742                && TREE_CODE (expr_type) != ARRAY_TYPE)
5743         {
5744           if (TREE_CODE (expr) == VAR_DECL)
5745             {
5746               error ("%qD is not a valid template argument "
5747                      "because %qD is a variable, not the address of "
5748                      "a variable",
5749                      expr, expr);
5750               return NULL_TREE;
5751             }
5752           /* Other values, like integer constants, might be valid
5753              non-type arguments of some other type.  */
5754           return error_mark_node;
5755         }
5756       else
5757         {
5758           tree decl;
5759
5760           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5761                   ? TREE_OPERAND (expr, 0) : expr);
5762           if (TREE_CODE (decl) != VAR_DECL)
5763             {
5764               error ("%qE is not a valid template argument of type %qT "
5765                      "because %qE is not a variable",
5766                      expr, type, decl);
5767               return NULL_TREE;
5768             }
5769           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5770             {
5771               error ("%qE is not a valid template argument of type %qT "
5772                      "because %qD does not have external linkage",
5773                      expr, type, decl);
5774               return NULL_TREE;
5775             }
5776         }
5777
5778       expr = decay_conversion (expr);
5779       if (expr == error_mark_node)
5780         return error_mark_node;
5781
5782       expr = perform_qualification_conversions (type, expr);
5783       if (expr == error_mark_node)
5784         return error_mark_node;
5785     }
5786   /* [temp.arg.nontype]/5, bullet 3
5787
5788      For a non-type template-parameter of type reference to object, no
5789      conversions apply. The type referred to by the reference may be more
5790      cv-qualified than the (otherwise identical) type of the
5791      template-argument. The template-parameter is bound directly to the
5792      template-argument, which must be an lvalue.  */
5793   else if (TYPE_REF_OBJ_P (type))
5794     {
5795       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5796                                                       expr_type))
5797         return error_mark_node;
5798
5799       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5800         {
5801           error ("%qE is not a valid template argument for type %qT "
5802                  "because of conflicts in cv-qualification", expr, type);
5803           return NULL_TREE;
5804         }
5805
5806       if (!real_lvalue_p (expr))
5807         {
5808           error ("%qE is not a valid template argument for type %qT "
5809                  "because it is not an lvalue", expr, type);
5810           return NULL_TREE;
5811         }
5812
5813       /* [temp.arg.nontype]/1
5814
5815          A template-argument for a non-type, non-template template-parameter
5816          shall be one of: [...]
5817
5818          -- the address of an object or function with external linkage.  */
5819       if (TREE_CODE (expr) == INDIRECT_REF
5820           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5821         {
5822           expr = TREE_OPERAND (expr, 0);
5823           if (DECL_P (expr))
5824             {
5825               error ("%q#D is not a valid template argument for type %qT "
5826                      "because a reference variable does not have a constant "
5827                      "address", expr, type);
5828               return NULL_TREE;
5829             }
5830         }
5831
5832       if (!DECL_P (expr))
5833         {
5834           error ("%qE is not a valid template argument for type %qT "
5835                  "because it is not an object with external linkage",
5836                  expr, type);
5837           return NULL_TREE;
5838         }
5839
5840       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5841         {
5842           error ("%qE is not a valid template argument for type %qT "
5843                  "because object %qD has not external linkage",
5844                  expr, type, expr);
5845           return NULL_TREE;
5846         }
5847
5848       expr = build_nop (type, build_address (expr));
5849     }
5850   /* [temp.arg.nontype]/5, bullet 4
5851
5852      For a non-type template-parameter of type pointer to function, only
5853      the function-to-pointer conversion (_conv.func_) is applied. If the
5854      template-argument represents a set of overloaded functions (or a
5855      pointer to such), the matching function is selected from the set
5856      (_over.over_).  */
5857   else if (TYPE_PTRFN_P (type))
5858     {
5859       /* If the argument is a template-id, we might not have enough
5860          context information to decay the pointer.  */
5861       if (!type_unknown_p (expr_type))
5862         {
5863           expr = decay_conversion (expr);
5864           if (expr == error_mark_node)
5865             return error_mark_node;
5866         }
5867
5868       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5869         /* Null pointer values are OK in C++11.  */
5870         return perform_qualification_conversions (type, expr);
5871
5872       expr = convert_nontype_argument_function (type, expr);
5873       if (!expr || expr == error_mark_node)
5874         return expr;
5875
5876       if (TREE_CODE (expr) != ADDR_EXPR)
5877         {
5878           error ("%qE is not a valid template argument for type %qT", expr, type);
5879           error ("it must be the address of a function with external linkage");
5880           return NULL_TREE;
5881         }
5882     }
5883   /* [temp.arg.nontype]/5, bullet 5
5884
5885      For a non-type template-parameter of type reference to function, no
5886      conversions apply. If the template-argument represents a set of
5887      overloaded functions, the matching function is selected from the set
5888      (_over.over_).  */
5889   else if (TYPE_REFFN_P (type))
5890     {
5891       if (TREE_CODE (expr) == ADDR_EXPR)
5892         {
5893           error ("%qE is not a valid template argument for type %qT "
5894                  "because it is a pointer", expr, type);
5895           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5896           return NULL_TREE;
5897         }
5898
5899       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5900       if (!expr || expr == error_mark_node)
5901         return expr;
5902
5903       expr = build_nop (type, build_address (expr));
5904     }
5905   /* [temp.arg.nontype]/5, bullet 6
5906
5907      For a non-type template-parameter of type pointer to member function,
5908      no conversions apply. If the template-argument represents a set of
5909      overloaded member functions, the matching member function is selected
5910      from the set (_over.over_).  */
5911   else if (TYPE_PTRMEMFUNC_P (type))
5912     {
5913       expr = instantiate_type (type, expr, tf_none);
5914       if (expr == error_mark_node)
5915         return error_mark_node;
5916
5917       /* [temp.arg.nontype] bullet 1 says the pointer to member
5918          expression must be a pointer-to-member constant.  */
5919       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5920         return error_mark_node;
5921
5922       /* There is no way to disable standard conversions in
5923          resolve_address_of_overloaded_function (called by
5924          instantiate_type). It is possible that the call succeeded by
5925          converting &B::I to &D::I (where B is a base of D), so we need
5926          to reject this conversion here.
5927
5928          Actually, even if there was a way to disable standard conversions,
5929          it would still be better to reject them here so that we can
5930          provide a superior diagnostic.  */
5931       if (!same_type_p (TREE_TYPE (expr), type))
5932         {
5933           error ("%qE is not a valid template argument for type %qT "
5934                  "because it is of type %qT", expr, type,
5935                  TREE_TYPE (expr));
5936           /* If we are just one standard conversion off, explain.  */
5937           if (can_convert (type, TREE_TYPE (expr)))
5938             inform (input_location,
5939                     "standard conversions are not allowed in this context");
5940           return NULL_TREE;
5941         }
5942     }
5943   /* [temp.arg.nontype]/5, bullet 7
5944
5945      For a non-type template-parameter of type pointer to data member,
5946      qualification conversions (_conv.qual_) are applied.  */
5947   else if (TYPE_PTRMEM_P (type))
5948     {
5949       /* [temp.arg.nontype] bullet 1 says the pointer to member
5950          expression must be a pointer-to-member constant.  */
5951       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5952         return error_mark_node;
5953
5954       expr = perform_qualification_conversions (type, expr);
5955       if (expr == error_mark_node)
5956         return expr;
5957     }
5958   else if (NULLPTR_TYPE_P (type))
5959     {
5960       if (expr != nullptr_node)
5961         {
5962           error ("%qE is not a valid template argument for type %qT "
5963                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
5964           return NULL_TREE;
5965         }
5966       return expr;
5967     }
5968   /* A template non-type parameter must be one of the above.  */
5969   else
5970     gcc_unreachable ();
5971
5972   /* Sanity check: did we actually convert the argument to the
5973      right type?  */
5974   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5975               (type, TREE_TYPE (expr)));
5976   return expr;
5977 }
5978
5979 /* Subroutine of coerce_template_template_parms, which returns 1 if
5980    PARM_PARM and ARG_PARM match using the rule for the template
5981    parameters of template template parameters. Both PARM and ARG are
5982    template parameters; the rest of the arguments are the same as for
5983    coerce_template_template_parms.
5984  */
5985 static int
5986 coerce_template_template_parm (tree parm,
5987                               tree arg,
5988                               tsubst_flags_t complain,
5989                               tree in_decl,
5990                               tree outer_args)
5991 {
5992   if (arg == NULL_TREE || arg == error_mark_node
5993       || parm == NULL_TREE || parm == error_mark_node)
5994     return 0;
5995   
5996   if (TREE_CODE (arg) != TREE_CODE (parm))
5997     return 0;
5998   
5999   switch (TREE_CODE (parm))
6000     {
6001     case TEMPLATE_DECL:
6002       /* We encounter instantiations of templates like
6003          template <template <template <class> class> class TT>
6004          class C;  */
6005       {
6006         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6007         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6008         
6009         if (!coerce_template_template_parms
6010             (parmparm, argparm, complain, in_decl, outer_args))
6011           return 0;
6012       }
6013       /* Fall through.  */
6014       
6015     case TYPE_DECL:
6016       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6017           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6018         /* Argument is a parameter pack but parameter is not.  */
6019         return 0;
6020       break;
6021       
6022     case PARM_DECL:
6023       /* The tsubst call is used to handle cases such as
6024          
6025            template <int> class C {};
6026            template <class T, template <T> class TT> class D {};
6027            D<int, C> d;
6028
6029          i.e. the parameter list of TT depends on earlier parameters.  */
6030       if (!uses_template_parms (TREE_TYPE (arg))
6031           && !same_type_p
6032                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
6033                  TREE_TYPE (arg)))
6034         return 0;
6035       
6036       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6037           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6038         /* Argument is a parameter pack but parameter is not.  */
6039         return 0;
6040       
6041       break;
6042
6043     default:
6044       gcc_unreachable ();
6045     }
6046
6047   return 1;
6048 }
6049
6050
6051 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6052    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6053    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6054    or PARM_DECL.
6055
6056    Consider the example:
6057      template <class T> class A;
6058      template<template <class U> class TT> class B;
6059
6060    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6061    the parameters to A, and OUTER_ARGS contains A.  */
6062
6063 static int
6064 coerce_template_template_parms (tree parm_parms,
6065                                 tree arg_parms,
6066                                 tsubst_flags_t complain,
6067                                 tree in_decl,
6068                                 tree outer_args)
6069 {
6070   int nparms, nargs, i;
6071   tree parm, arg;
6072   int variadic_p = 0;
6073
6074   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6075   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6076
6077   nparms = TREE_VEC_LENGTH (parm_parms);
6078   nargs = TREE_VEC_LENGTH (arg_parms);
6079
6080   /* Determine whether we have a parameter pack at the end of the
6081      template template parameter's template parameter list.  */
6082   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6083     {
6084       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6085       
6086       if (parm == error_mark_node)
6087         return 0;
6088
6089       switch (TREE_CODE (parm))
6090         {
6091         case TEMPLATE_DECL:
6092         case TYPE_DECL:
6093           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6094             variadic_p = 1;
6095           break;
6096           
6097         case PARM_DECL:
6098           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6099             variadic_p = 1;
6100           break;
6101           
6102         default:
6103           gcc_unreachable ();
6104         }
6105     }
6106  
6107   if (nargs != nparms
6108       && !(variadic_p && nargs >= nparms - 1))
6109     return 0;
6110
6111   /* Check all of the template parameters except the parameter pack at
6112      the end (if any).  */
6113   for (i = 0; i < nparms - variadic_p; ++i)
6114     {
6115       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6116           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6117         continue;
6118
6119       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6120       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6121
6122       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6123                                           outer_args))
6124         return 0;
6125
6126     }
6127
6128   if (variadic_p)
6129     {
6130       /* Check each of the template parameters in the template
6131          argument against the template parameter pack at the end of
6132          the template template parameter.  */
6133       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6134         return 0;
6135
6136       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6137
6138       for (; i < nargs; ++i)
6139         {
6140           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6141             continue;
6142  
6143           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6144  
6145           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6146                                               outer_args))
6147             return 0;
6148         }
6149     }
6150
6151   return 1;
6152 }
6153
6154 /* Verifies that the deduced template arguments (in TARGS) for the
6155    template template parameters (in TPARMS) represent valid bindings,
6156    by comparing the template parameter list of each template argument
6157    to the template parameter list of its corresponding template
6158    template parameter, in accordance with DR150. This
6159    routine can only be called after all template arguments have been
6160    deduced. It will return TRUE if all of the template template
6161    parameter bindings are okay, FALSE otherwise.  */
6162 bool 
6163 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6164 {
6165   int i, ntparms = TREE_VEC_LENGTH (tparms);
6166   bool ret = true;
6167
6168   /* We're dealing with template parms in this process.  */
6169   ++processing_template_decl;
6170
6171   targs = INNERMOST_TEMPLATE_ARGS (targs);
6172
6173   for (i = 0; i < ntparms; ++i)
6174     {
6175       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6176       tree targ = TREE_VEC_ELT (targs, i);
6177
6178       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6179         {
6180           tree packed_args = NULL_TREE;
6181           int idx, len = 1;
6182
6183           if (ARGUMENT_PACK_P (targ))
6184             {
6185               /* Look inside the argument pack.  */
6186               packed_args = ARGUMENT_PACK_ARGS (targ);
6187               len = TREE_VEC_LENGTH (packed_args);
6188             }
6189
6190           for (idx = 0; idx < len; ++idx)
6191             {
6192               tree targ_parms = NULL_TREE;
6193
6194               if (packed_args)
6195                 /* Extract the next argument from the argument
6196                    pack.  */
6197                 targ = TREE_VEC_ELT (packed_args, idx);
6198
6199               if (PACK_EXPANSION_P (targ))
6200                 /* Look at the pattern of the pack expansion.  */
6201                 targ = PACK_EXPANSION_PATTERN (targ);
6202
6203               /* Extract the template parameters from the template
6204                  argument.  */
6205               if (TREE_CODE (targ) == TEMPLATE_DECL)
6206                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6207               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6208                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6209
6210               /* Verify that we can coerce the template template
6211                  parameters from the template argument to the template
6212                  parameter.  This requires an exact match.  */
6213               if (targ_parms
6214                   && !coerce_template_template_parms
6215                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6216                         targ_parms,
6217                         tf_none,
6218                         tparm,
6219                         targs))
6220                 {
6221                   ret = false;
6222                   goto out;
6223                 }
6224             }
6225         }
6226     }
6227
6228  out:
6229
6230   --processing_template_decl;
6231   return ret;
6232 }
6233
6234 /* Since type attributes aren't mangled, we need to strip them from
6235    template type arguments.  */
6236
6237 static tree
6238 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6239 {
6240   tree mv;
6241   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6242     return arg;
6243   mv = TYPE_MAIN_VARIANT (arg);
6244   arg = strip_typedefs (arg);
6245   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6246       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6247     {
6248       if (complain & tf_warning)
6249         warning (0, "ignoring attributes on template argument %qT", arg);
6250       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6251       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6252     }
6253   return arg;
6254 }
6255
6256 /* Convert the indicated template ARG as necessary to match the
6257    indicated template PARM.  Returns the converted ARG, or
6258    error_mark_node if the conversion was unsuccessful.  Error and
6259    warning messages are issued under control of COMPLAIN.  This
6260    conversion is for the Ith parameter in the parameter list.  ARGS is
6261    the full set of template arguments deduced so far.  */
6262
6263 static tree
6264 convert_template_argument (tree parm,
6265                            tree arg,
6266                            tree args,
6267                            tsubst_flags_t complain,
6268                            int i,
6269                            tree in_decl)
6270 {
6271   tree orig_arg;
6272   tree val;
6273   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6274
6275   if (TREE_CODE (arg) == TREE_LIST
6276       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6277     {
6278       /* The template argument was the name of some
6279          member function.  That's usually
6280          invalid, but static members are OK.  In any
6281          case, grab the underlying fields/functions
6282          and issue an error later if required.  */
6283       orig_arg = TREE_VALUE (arg);
6284       TREE_TYPE (arg) = unknown_type_node;
6285     }
6286
6287   orig_arg = arg;
6288
6289   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6290   requires_type = (TREE_CODE (parm) == TYPE_DECL
6291                    || requires_tmpl_type);
6292
6293   /* When determining whether an argument pack expansion is a template,
6294      look at the pattern.  */
6295   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6296     arg = PACK_EXPANSION_PATTERN (arg);
6297
6298   /* Deal with an injected-class-name used as a template template arg.  */
6299   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6300     {
6301       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6302       if (TREE_CODE (t) == TEMPLATE_DECL)
6303         {
6304           if (cxx_dialect >= cxx0x)
6305             /* OK under DR 1004.  */;
6306           else if (complain & tf_warning_or_error)
6307             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6308                      " used as template template argument", TYPE_NAME (arg));
6309           else if (flag_pedantic_errors)
6310             t = arg;
6311
6312           arg = t;
6313         }
6314     }
6315
6316   is_tmpl_type = 
6317     ((TREE_CODE (arg) == TEMPLATE_DECL
6318       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6319      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6320      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6321
6322   if (is_tmpl_type
6323       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6324           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6325     arg = TYPE_STUB_DECL (arg);
6326
6327   is_type = TYPE_P (arg) || is_tmpl_type;
6328
6329   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6330       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6331     {
6332       permerror (input_location, "to refer to a type member of a template parameter, "
6333                  "use %<typename %E%>", orig_arg);
6334
6335       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6336                                      TREE_OPERAND (arg, 1),
6337                                      typename_type,
6338                                      complain & tf_error);
6339       arg = orig_arg;
6340       is_type = 1;
6341     }
6342   if (is_type != requires_type)
6343     {
6344       if (in_decl)
6345         {
6346           if (complain & tf_error)
6347             {
6348               error ("type/value mismatch at argument %d in template "
6349                      "parameter list for %qD",
6350                      i + 1, in_decl);
6351               if (is_type)
6352                 error ("  expected a constant of type %qT, got %qT",
6353                        TREE_TYPE (parm),
6354                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6355               else if (requires_tmpl_type)
6356                 error ("  expected a class template, got %qE", orig_arg);
6357               else
6358                 error ("  expected a type, got %qE", orig_arg);
6359             }
6360         }
6361       return error_mark_node;
6362     }
6363   if (is_tmpl_type ^ requires_tmpl_type)
6364     {
6365       if (in_decl && (complain & tf_error))
6366         {
6367           error ("type/value mismatch at argument %d in template "
6368                  "parameter list for %qD",
6369                  i + 1, in_decl);
6370           if (is_tmpl_type)
6371             error ("  expected a type, got %qT", DECL_NAME (arg));
6372           else
6373             error ("  expected a class template, got %qT", orig_arg);
6374         }
6375       return error_mark_node;
6376     }
6377
6378   if (is_type)
6379     {
6380       if (requires_tmpl_type)
6381         {
6382           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6383             /* The number of argument required is not known yet.
6384                Just accept it for now.  */
6385             val = TREE_TYPE (arg);
6386           else
6387             {
6388               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6389               tree argparm;
6390
6391               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6392
6393               if (coerce_template_template_parms (parmparm, argparm,
6394                                                   complain, in_decl,
6395                                                   args))
6396                 {
6397                   val = arg;
6398
6399                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6400                      TEMPLATE_DECL.  */
6401                   if (val != error_mark_node)
6402                     {
6403                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6404                         val = TREE_TYPE (val);
6405                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6406                         val = make_pack_expansion (val);
6407                     }
6408                 }
6409               else
6410                 {
6411                   if (in_decl && (complain & tf_error))
6412                     {
6413                       error ("type/value mismatch at argument %d in "
6414                              "template parameter list for %qD",
6415                              i + 1, in_decl);
6416                       error ("  expected a template of type %qD, got %qT",
6417                              parm, orig_arg);
6418                     }
6419
6420                   val = error_mark_node;
6421                 }
6422             }
6423         }
6424       else
6425         val = orig_arg;
6426       /* We only form one instance of each template specialization.
6427          Therefore, if we use a non-canonical variant (i.e., a
6428          typedef), any future messages referring to the type will use
6429          the typedef, which is confusing if those future uses do not
6430          themselves also use the typedef.  */
6431       if (TYPE_P (val))
6432         val = canonicalize_type_argument (val, complain);
6433     }
6434   else
6435     {
6436       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6437
6438       if (invalid_nontype_parm_type_p (t, complain))
6439         return error_mark_node;
6440
6441       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6442         {
6443           if (same_type_p (t, TREE_TYPE (orig_arg)))
6444             val = orig_arg;
6445           else
6446             {
6447               /* Not sure if this is reachable, but it doesn't hurt
6448                  to be robust.  */
6449               error ("type mismatch in nontype parameter pack");
6450               val = error_mark_node;
6451             }
6452         }
6453       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6454         /* We used to call digest_init here.  However, digest_init
6455            will report errors, which we don't want when complain
6456            is zero.  More importantly, digest_init will try too
6457            hard to convert things: for example, `0' should not be
6458            converted to pointer type at this point according to
6459            the standard.  Accepting this is not merely an
6460            extension, since deciding whether or not these
6461            conversions can occur is part of determining which
6462            function template to call, or whether a given explicit
6463            argument specification is valid.  */
6464         val = convert_nontype_argument (t, orig_arg, complain);
6465       else
6466         val = orig_arg;
6467
6468       if (val == NULL_TREE)
6469         val = error_mark_node;
6470       else if (val == error_mark_node && (complain & tf_error))
6471         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6472
6473       if (TREE_CODE (val) == SCOPE_REF)
6474         {
6475           /* Strip typedefs from the SCOPE_REF.  */
6476           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6477           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6478                                                    complain);
6479           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6480                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6481         }
6482     }
6483
6484   return val;
6485 }
6486
6487 /* Coerces the remaining template arguments in INNER_ARGS (from
6488    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6489    Returns the coerced argument pack. PARM_IDX is the position of this
6490    parameter in the template parameter list. ARGS is the original
6491    template argument list.  */
6492 static tree
6493 coerce_template_parameter_pack (tree parms,
6494                                 int parm_idx,
6495                                 tree args,
6496                                 tree inner_args,
6497                                 int arg_idx,
6498                                 tree new_args,
6499                                 int* lost,
6500                                 tree in_decl,
6501                                 tsubst_flags_t complain)
6502 {
6503   tree parm = TREE_VEC_ELT (parms, parm_idx);
6504   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6505   tree packed_args;
6506   tree argument_pack;
6507   tree packed_types = NULL_TREE;
6508
6509   if (arg_idx > nargs)
6510     arg_idx = nargs;
6511
6512   packed_args = make_tree_vec (nargs - arg_idx);
6513
6514   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6515       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6516     {
6517       /* When the template parameter is a non-type template
6518          parameter pack whose type uses parameter packs, we need
6519          to look at each of the template arguments
6520          separately. Build a vector of the types for these
6521          non-type template parameters in PACKED_TYPES.  */
6522       tree expansion 
6523         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6524       packed_types = tsubst_pack_expansion (expansion, args,
6525                                             complain, in_decl);
6526
6527       if (packed_types == error_mark_node)
6528         return error_mark_node;
6529
6530       /* Check that we have the right number of arguments.  */
6531       if (arg_idx < nargs
6532           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6533           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6534         {
6535           int needed_parms 
6536             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6537           error ("wrong number of template arguments (%d, should be %d)",
6538                  nargs, needed_parms);
6539           return error_mark_node;
6540         }
6541
6542       /* If we aren't able to check the actual arguments now
6543          (because they haven't been expanded yet), we can at least
6544          verify that all of the types used for the non-type
6545          template parameter pack are, in fact, valid for non-type
6546          template parameters.  */
6547       if (arg_idx < nargs 
6548           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6549         {
6550           int j, len = TREE_VEC_LENGTH (packed_types);
6551           for (j = 0; j < len; ++j)
6552             {
6553               tree t = TREE_VEC_ELT (packed_types, j);
6554               if (invalid_nontype_parm_type_p (t, complain))
6555                 return error_mark_node;
6556             }
6557         }
6558     }
6559
6560   /* Convert the remaining arguments, which will be a part of the
6561      parameter pack "parm".  */
6562   for (; arg_idx < nargs; ++arg_idx)
6563     {
6564       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6565       tree actual_parm = TREE_VALUE (parm);
6566
6567       if (packed_types && !PACK_EXPANSION_P (arg))
6568         {
6569           /* When we have a vector of types (corresponding to the
6570              non-type template parameter pack that uses parameter
6571              packs in its type, as mention above), and the
6572              argument is not an expansion (which expands to a
6573              currently unknown number of arguments), clone the
6574              parm and give it the next type in PACKED_TYPES.  */
6575           actual_parm = copy_node (actual_parm);
6576           TREE_TYPE (actual_parm) = 
6577             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6578         }
6579
6580       if (arg != error_mark_node)
6581         arg = convert_template_argument (actual_parm, 
6582                                          arg, new_args, complain, parm_idx,
6583                                          in_decl);
6584       if (arg == error_mark_node)
6585         (*lost)++;
6586       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6587     }
6588
6589   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6590       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6591     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6592   else
6593     {
6594       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6595       TREE_TYPE (argument_pack) 
6596         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6597       TREE_CONSTANT (argument_pack) = 1;
6598     }
6599
6600   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6601 #ifdef ENABLE_CHECKING
6602   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6603                                        TREE_VEC_LENGTH (packed_args));
6604 #endif
6605   return argument_pack;
6606 }
6607
6608 /* Convert all template arguments to their appropriate types, and
6609    return a vector containing the innermost resulting template
6610    arguments.  If any error occurs, return error_mark_node. Error and
6611    warning messages are issued under control of COMPLAIN.
6612
6613    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6614    for arguments not specified in ARGS.  Otherwise, if
6615    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6616    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6617    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6618    ARGS.  */
6619
6620 static tree
6621 coerce_template_parms (tree parms,
6622                        tree args,
6623                        tree in_decl,
6624                        tsubst_flags_t complain,
6625                        bool require_all_args,
6626                        bool use_default_args)
6627 {
6628   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6629   tree inner_args;
6630   tree new_args;
6631   tree new_inner_args;
6632   int saved_unevaluated_operand;
6633   int saved_inhibit_evaluation_warnings;
6634
6635   /* When used as a boolean value, indicates whether this is a
6636      variadic template parameter list. Since it's an int, we can also
6637      subtract it from nparms to get the number of non-variadic
6638      parameters.  */
6639   int variadic_p = 0;
6640   int post_variadic_parms = 0;
6641
6642   if (args == error_mark_node)
6643     return error_mark_node;
6644
6645   nparms = TREE_VEC_LENGTH (parms);
6646
6647   /* Determine if there are any parameter packs.  */
6648   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6649     {
6650       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6651       if (variadic_p)
6652         ++post_variadic_parms;
6653       if (template_parameter_pack_p (tparm))
6654         ++variadic_p;
6655     }
6656
6657   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6658   /* If there are no parameters that follow a parameter pack, we need to
6659      expand any argument packs so that we can deduce a parameter pack from
6660      some non-packed args followed by an argument pack, as in variadic85.C.
6661      If there are such parameters, we need to leave argument packs intact
6662      so the arguments are assigned properly.  This can happen when dealing
6663      with a nested class inside a partial specialization of a class
6664      template, as in variadic92.C, or when deducing a template parameter pack
6665      from a sub-declarator, as in variadic114.C.  */
6666   if (!post_variadic_parms)
6667     inner_args = expand_template_argument_pack (inner_args);
6668
6669   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6670   if ((nargs > nparms && !variadic_p)
6671       || (nargs < nparms - variadic_p
6672           && require_all_args
6673           && (!use_default_args
6674               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6675                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6676     {
6677       if (complain & tf_error)
6678         {
6679           if (variadic_p)
6680             {
6681               nparms -= variadic_p;
6682               error ("wrong number of template arguments "
6683                      "(%d, should be %d or more)", nargs, nparms);
6684             }
6685           else
6686              error ("wrong number of template arguments "
6687                     "(%d, should be %d)", nargs, nparms);
6688
6689           if (in_decl)
6690             error ("provided for %q+D", in_decl);
6691         }
6692
6693       return error_mark_node;
6694     }
6695
6696   /* We need to evaluate the template arguments, even though this
6697      template-id may be nested within a "sizeof".  */
6698   saved_unevaluated_operand = cp_unevaluated_operand;
6699   cp_unevaluated_operand = 0;
6700   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6701   c_inhibit_evaluation_warnings = 0;
6702   new_inner_args = make_tree_vec (nparms);
6703   new_args = add_outermost_template_args (args, new_inner_args);
6704   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6705     {
6706       tree arg;
6707       tree parm;
6708
6709       /* Get the Ith template parameter.  */
6710       parm = TREE_VEC_ELT (parms, parm_idx);
6711  
6712       if (parm == error_mark_node)
6713       {
6714         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6715         continue;
6716       }
6717
6718       /* Calculate the next argument.  */
6719       if (arg_idx < nargs)
6720         arg = TREE_VEC_ELT (inner_args, arg_idx);
6721       else
6722         arg = NULL_TREE;
6723
6724       if (template_parameter_pack_p (TREE_VALUE (parm))
6725           && !(arg && ARGUMENT_PACK_P (arg)))
6726         {
6727           /* All remaining arguments will be placed in the
6728              template parameter pack PARM.  */
6729           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6730                                                 inner_args, arg_idx,
6731                                                 new_args, &lost,
6732                                                 in_decl, complain);
6733
6734           /* Store this argument.  */
6735           if (arg == error_mark_node)
6736             lost++;
6737           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6738
6739           /* We are done with all of the arguments.  */
6740           arg_idx = nargs;
6741           
6742           continue;
6743         }
6744       else if (arg)
6745         {
6746           if (PACK_EXPANSION_P (arg))
6747             {
6748               /* We don't know how many args we have yet, just
6749                  use the unconverted ones for now.  */
6750               new_inner_args = args;
6751               break;
6752             }
6753         }
6754       else if (require_all_args)
6755         {
6756           /* There must be a default arg in this case.  */
6757           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6758                                      complain, in_decl);
6759           /* The position of the first default template argument,
6760              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6761              Record that.  */
6762           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6763             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6764         }
6765       else
6766         break;
6767
6768       if (arg == error_mark_node)
6769         {
6770           if (complain & tf_error)
6771             error ("template argument %d is invalid", arg_idx + 1);
6772         }
6773       else if (!arg)
6774         /* This only occurs if there was an error in the template
6775            parameter list itself (which we would already have
6776            reported) that we are trying to recover from, e.g., a class
6777            template with a parameter list such as
6778            template<typename..., typename>.  */
6779         ++lost;
6780       else
6781         arg = convert_template_argument (TREE_VALUE (parm),
6782                                          arg, new_args, complain, 
6783                                          parm_idx, in_decl);
6784
6785       if (arg == error_mark_node)
6786         lost++;
6787       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6788     }
6789   cp_unevaluated_operand = saved_unevaluated_operand;
6790   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6791
6792   if (lost)
6793     return error_mark_node;
6794
6795 #ifdef ENABLE_CHECKING
6796   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6797     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6798                                          TREE_VEC_LENGTH (new_inner_args));
6799 #endif
6800
6801   return new_inner_args;
6802 }
6803
6804 /* Returns 1 if template args OT and NT are equivalent.  */
6805
6806 static int
6807 template_args_equal (tree ot, tree nt)
6808 {
6809   if (nt == ot)
6810     return 1;
6811   if (nt == NULL_TREE || ot == NULL_TREE)
6812     return false;
6813
6814   if (TREE_CODE (nt) == TREE_VEC)
6815     /* For member templates */
6816     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6817   else if (PACK_EXPANSION_P (ot))
6818     return PACK_EXPANSION_P (nt) 
6819       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6820                               PACK_EXPANSION_PATTERN (nt));
6821   else if (ARGUMENT_PACK_P (ot))
6822     {
6823       int i, len;
6824       tree opack, npack;
6825
6826       if (!ARGUMENT_PACK_P (nt))
6827         return 0;
6828
6829       opack = ARGUMENT_PACK_ARGS (ot);
6830       npack = ARGUMENT_PACK_ARGS (nt);
6831       len = TREE_VEC_LENGTH (opack);
6832       if (TREE_VEC_LENGTH (npack) != len)
6833         return 0;
6834       for (i = 0; i < len; ++i)
6835         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6836                                   TREE_VEC_ELT (npack, i)))
6837           return 0;
6838       return 1;
6839     }
6840   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6841     {
6842       /* We get here probably because we are in the middle of substituting
6843          into the pattern of a pack expansion. In that case the
6844          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6845          interested in. So we want to use the initial pack argument for
6846          the comparison.  */
6847       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6848       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6849         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6850       return template_args_equal (ot, nt);
6851     }
6852   else if (TYPE_P (nt))
6853     return TYPE_P (ot) && same_type_p (ot, nt);
6854   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6855     return 0;
6856   else
6857     return cp_tree_equal (ot, nt);
6858 }
6859
6860 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6861    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6862    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6863
6864 static int
6865 comp_template_args_with_info (tree oldargs, tree newargs,
6866                               tree *oldarg_ptr, tree *newarg_ptr)
6867 {
6868   int i;
6869
6870   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6871     return 0;
6872
6873   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6874     {
6875       tree nt = TREE_VEC_ELT (newargs, i);
6876       tree ot = TREE_VEC_ELT (oldargs, i);
6877
6878       if (! template_args_equal (ot, nt))
6879         {
6880           if (oldarg_ptr != NULL)
6881             *oldarg_ptr = ot;
6882           if (newarg_ptr != NULL)
6883             *newarg_ptr = nt;
6884           return 0;
6885         }
6886     }
6887   return 1;
6888 }
6889
6890 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6891    of template arguments.  Returns 0 otherwise.  */
6892
6893 int
6894 comp_template_args (tree oldargs, tree newargs)
6895 {
6896   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6897 }
6898
6899 static void
6900 add_pending_template (tree d)
6901 {
6902   tree ti = (TYPE_P (d)
6903              ? CLASSTYPE_TEMPLATE_INFO (d)
6904              : DECL_TEMPLATE_INFO (d));
6905   struct pending_template *pt;
6906   int level;
6907
6908   if (TI_PENDING_TEMPLATE_FLAG (ti))
6909     return;
6910
6911   /* We are called both from instantiate_decl, where we've already had a
6912      tinst_level pushed, and instantiate_template, where we haven't.
6913      Compensate.  */
6914   level = !current_tinst_level || current_tinst_level->decl != d;
6915
6916   if (level)
6917     push_tinst_level (d);
6918
6919   pt = ggc_alloc_pending_template ();
6920   pt->next = NULL;
6921   pt->tinst = current_tinst_level;
6922   if (last_pending_template)
6923     last_pending_template->next = pt;
6924   else
6925     pending_templates = pt;
6926
6927   last_pending_template = pt;
6928
6929   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6930
6931   if (level)
6932     pop_tinst_level ();
6933 }
6934
6935
6936 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6937    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6938    documentation for TEMPLATE_ID_EXPR.  */
6939
6940 tree
6941 lookup_template_function (tree fns, tree arglist)
6942 {
6943   tree type;
6944
6945   if (fns == error_mark_node || arglist == error_mark_node)
6946     return error_mark_node;
6947
6948   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6949
6950   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6951     {
6952       error ("%q#D is not a function template", fns);
6953       return error_mark_node;
6954     }
6955
6956   if (BASELINK_P (fns))
6957     {
6958       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6959                                          unknown_type_node,
6960                                          BASELINK_FUNCTIONS (fns),
6961                                          arglist);
6962       return fns;
6963     }
6964
6965   type = TREE_TYPE (fns);
6966   if (TREE_CODE (fns) == OVERLOAD || !type)
6967     type = unknown_type_node;
6968
6969   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6970 }
6971
6972 /* Within the scope of a template class S<T>, the name S gets bound
6973    (in build_self_reference) to a TYPE_DECL for the class, not a
6974    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6975    or one of its enclosing classes, and that type is a template,
6976    return the associated TEMPLATE_DECL.  Otherwise, the original
6977    DECL is returned.
6978
6979    Also handle the case when DECL is a TREE_LIST of ambiguous
6980    injected-class-names from different bases.  */
6981
6982 tree
6983 maybe_get_template_decl_from_type_decl (tree decl)
6984 {
6985   if (decl == NULL_TREE)
6986     return decl;
6987
6988   /* DR 176: A lookup that finds an injected-class-name (10.2
6989      [class.member.lookup]) can result in an ambiguity in certain cases
6990      (for example, if it is found in more than one base class). If all of
6991      the injected-class-names that are found refer to specializations of
6992      the same class template, and if the name is followed by a
6993      template-argument-list, the reference refers to the class template
6994      itself and not a specialization thereof, and is not ambiguous.  */
6995   if (TREE_CODE (decl) == TREE_LIST)
6996     {
6997       tree t, tmpl = NULL_TREE;
6998       for (t = decl; t; t = TREE_CHAIN (t))
6999         {
7000           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
7001           if (!tmpl)
7002             tmpl = elt;
7003           else if (tmpl != elt)
7004             break;
7005         }
7006       if (tmpl && t == NULL_TREE)
7007         return tmpl;
7008       else
7009         return decl;
7010     }
7011
7012   return (decl != NULL_TREE
7013           && DECL_SELF_REFERENCE_P (decl)
7014           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7015     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7016 }
7017
7018 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
7019    parameters, find the desired type.
7020
7021    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7022
7023    IN_DECL, if non-NULL, is the template declaration we are trying to
7024    instantiate.
7025
7026    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7027    the class we are looking up.
7028
7029    Issue error and warning messages under control of COMPLAIN.
7030
7031    If the template class is really a local class in a template
7032    function, then the FUNCTION_CONTEXT is the function in which it is
7033    being instantiated.
7034
7035    ??? Note that this function is currently called *twice* for each
7036    template-id: the first time from the parser, while creating the
7037    incomplete type (finish_template_type), and the second type during the
7038    real instantiation (instantiate_template_class). This is surely something
7039    that we want to avoid. It also causes some problems with argument
7040    coercion (see convert_nontype_argument for more information on this).  */
7041
7042 static tree
7043 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7044                          int entering_scope, tsubst_flags_t complain)
7045 {
7046   tree templ = NULL_TREE, parmlist;
7047   tree t;
7048   void **slot;
7049   spec_entry *entry;
7050   spec_entry elt;
7051   hashval_t hash;
7052
7053   if (TREE_CODE (d1) == IDENTIFIER_NODE)
7054     {
7055       tree value = innermost_non_namespace_value (d1);
7056       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7057         templ = value;
7058       else
7059         {
7060           if (context)
7061             push_decl_namespace (context);
7062           templ = lookup_name (d1);
7063           templ = maybe_get_template_decl_from_type_decl (templ);
7064           if (context)
7065             pop_decl_namespace ();
7066         }
7067       if (templ)
7068         context = DECL_CONTEXT (templ);
7069     }
7070   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7071     {
7072       tree type = TREE_TYPE (d1);
7073
7074       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7075          an implicit typename for the second A.  Deal with it.  */
7076       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7077         type = TREE_TYPE (type);
7078
7079       if (CLASSTYPE_TEMPLATE_INFO (type))
7080         {
7081           templ = CLASSTYPE_TI_TEMPLATE (type);
7082           d1 = DECL_NAME (templ);
7083         }
7084     }
7085   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7086            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7087     {
7088       templ = TYPE_TI_TEMPLATE (d1);
7089       d1 = DECL_NAME (templ);
7090     }
7091   else if (TREE_CODE (d1) == TEMPLATE_DECL
7092            && DECL_TEMPLATE_RESULT (d1)
7093            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7094     {
7095       templ = d1;
7096       d1 = DECL_NAME (templ);
7097       context = DECL_CONTEXT (templ);
7098     }
7099
7100   /* Issue an error message if we didn't find a template.  */
7101   if (! templ)
7102     {
7103       if (complain & tf_error)
7104         error ("%qT is not a template", d1);
7105       return error_mark_node;
7106     }
7107
7108   if (TREE_CODE (templ) != TEMPLATE_DECL
7109          /* Make sure it's a user visible template, if it was named by
7110             the user.  */
7111       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7112           && !PRIMARY_TEMPLATE_P (templ)))
7113     {
7114       if (complain & tf_error)
7115         {
7116           error ("non-template type %qT used as a template", d1);
7117           if (in_decl)
7118             error ("for template declaration %q+D", in_decl);
7119         }
7120       return error_mark_node;
7121     }
7122
7123   complain &= ~tf_user;
7124
7125   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7126     {
7127       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7128          template arguments */
7129
7130       tree parm;
7131       tree arglist2;
7132       tree outer;
7133
7134       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7135
7136       /* Consider an example where a template template parameter declared as
7137
7138            template <class T, class U = std::allocator<T> > class TT
7139
7140          The template parameter level of T and U are one level larger than
7141          of TT.  To proper process the default argument of U, say when an
7142          instantiation `TT<int>' is seen, we need to build the full
7143          arguments containing {int} as the innermost level.  Outer levels,
7144          available when not appearing as default template argument, can be
7145          obtained from the arguments of the enclosing template.
7146
7147          Suppose that TT is later substituted with std::vector.  The above
7148          instantiation is `TT<int, std::allocator<T> >' with TT at
7149          level 1, and T at level 2, while the template arguments at level 1
7150          becomes {std::vector} and the inner level 2 is {int}.  */
7151
7152       outer = DECL_CONTEXT (templ);
7153       if (outer)
7154         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7155       else if (current_template_parms)
7156         /* This is an argument of the current template, so we haven't set
7157            DECL_CONTEXT yet.  */
7158         outer = current_template_args ();
7159
7160       if (outer)
7161         arglist = add_to_template_args (outer, arglist);
7162
7163       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7164                                         complain,
7165                                         /*require_all_args=*/true,
7166                                         /*use_default_args=*/true);
7167       if (arglist2 == error_mark_node
7168           || (!uses_template_parms (arglist2)
7169               && check_instantiated_args (templ, arglist2, complain)))
7170         return error_mark_node;
7171
7172       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7173       return parm;
7174     }
7175   else
7176     {
7177       tree template_type = TREE_TYPE (templ);
7178       tree gen_tmpl;
7179       tree type_decl;
7180       tree found = NULL_TREE;
7181       int arg_depth;
7182       int parm_depth;
7183       int is_dependent_type;
7184       int use_partial_inst_tmpl = false;
7185
7186       gen_tmpl = most_general_template (templ);
7187       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7188       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7189       arg_depth = TMPL_ARGS_DEPTH (arglist);
7190
7191       if (arg_depth == 1 && parm_depth > 1)
7192         {
7193           /* We've been given an incomplete set of template arguments.
7194              For example, given:
7195
7196                template <class T> struct S1 {
7197                  template <class U> struct S2 {};
7198                  template <class U> struct S2<U*> {};
7199                 };
7200
7201              we will be called with an ARGLIST of `U*', but the
7202              TEMPLATE will be `template <class T> template
7203              <class U> struct S1<T>::S2'.  We must fill in the missing
7204              arguments.  */
7205           arglist
7206             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7207                                            arglist);
7208           arg_depth = TMPL_ARGS_DEPTH (arglist);
7209         }
7210
7211       /* Now we should have enough arguments.  */
7212       gcc_assert (parm_depth == arg_depth);
7213
7214       /* From here on, we're only interested in the most general
7215          template.  */
7216
7217       /* Calculate the BOUND_ARGS.  These will be the args that are
7218          actually tsubst'd into the definition to create the
7219          instantiation.  */
7220       if (parm_depth > 1)
7221         {
7222           /* We have multiple levels of arguments to coerce, at once.  */
7223           int i;
7224           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7225
7226           tree bound_args = make_tree_vec (parm_depth);
7227
7228           for (i = saved_depth,
7229                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7230                i > 0 && t != NULL_TREE;
7231                --i, t = TREE_CHAIN (t))
7232             {
7233               tree a;
7234               if (i == saved_depth)
7235                 a = coerce_template_parms (TREE_VALUE (t),
7236                                            arglist, gen_tmpl,
7237                                            complain,
7238                                            /*require_all_args=*/true,
7239                                            /*use_default_args=*/true);
7240               else
7241                 /* Outer levels should have already been coerced.  */
7242                 a = TMPL_ARGS_LEVEL (arglist, i);
7243
7244               /* Don't process further if one of the levels fails.  */
7245               if (a == error_mark_node)
7246                 {
7247                   /* Restore the ARGLIST to its full size.  */
7248                   TREE_VEC_LENGTH (arglist) = saved_depth;
7249                   return error_mark_node;
7250                 }
7251
7252               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7253
7254               /* We temporarily reduce the length of the ARGLIST so
7255                  that coerce_template_parms will see only the arguments
7256                  corresponding to the template parameters it is
7257                  examining.  */
7258               TREE_VEC_LENGTH (arglist)--;
7259             }
7260
7261           /* Restore the ARGLIST to its full size.  */
7262           TREE_VEC_LENGTH (arglist) = saved_depth;
7263
7264           arglist = bound_args;
7265         }
7266       else
7267         arglist
7268           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7269                                    INNERMOST_TEMPLATE_ARGS (arglist),
7270                                    gen_tmpl,
7271                                    complain,
7272                                    /*require_all_args=*/true,
7273                                    /*use_default_args=*/true);
7274
7275       if (arglist == error_mark_node)
7276         /* We were unable to bind the arguments.  */
7277         return error_mark_node;
7278
7279       /* In the scope of a template class, explicit references to the
7280          template class refer to the type of the template, not any
7281          instantiation of it.  For example, in:
7282
7283            template <class T> class C { void f(C<T>); }
7284
7285          the `C<T>' is just the same as `C'.  Outside of the
7286          class, however, such a reference is an instantiation.  */
7287       if ((entering_scope
7288            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7289            || currently_open_class (template_type))
7290           /* comp_template_args is expensive, check it last.  */
7291           && comp_template_args (TYPE_TI_ARGS (template_type),
7292                                  arglist))
7293         return template_type;
7294
7295       /* If we already have this specialization, return it.  */
7296       elt.tmpl = gen_tmpl;
7297       elt.args = arglist;
7298       hash = hash_specialization (&elt);
7299       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7300                                                   &elt, hash);
7301
7302       if (entry)
7303         return entry->spec;
7304
7305       is_dependent_type = uses_template_parms (arglist);
7306
7307       /* If the deduced arguments are invalid, then the binding
7308          failed.  */
7309       if (!is_dependent_type
7310           && check_instantiated_args (gen_tmpl,
7311                                       INNERMOST_TEMPLATE_ARGS (arglist),
7312                                       complain))
7313         return error_mark_node;
7314
7315       if (!is_dependent_type
7316           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7317           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7318           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7319         {
7320           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7321                                       DECL_NAME (gen_tmpl),
7322                                       /*tag_scope=*/ts_global);
7323           return found;
7324         }
7325
7326       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7327                         complain, in_decl);
7328       if (!context)
7329         context = global_namespace;
7330
7331       /* Create the type.  */
7332       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7333         {
7334           if (!is_dependent_type)
7335             {
7336               set_current_access_from_decl (TYPE_NAME (template_type));
7337               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7338                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7339                                       arglist, complain, in_decl),
7340                               SCOPED_ENUM_P (template_type), NULL);
7341             }
7342           else
7343             {
7344               /* We don't want to call start_enum for this type, since
7345                  the values for the enumeration constants may involve
7346                  template parameters.  And, no one should be interested
7347                  in the enumeration constants for such a type.  */
7348               t = cxx_make_type (ENUMERAL_TYPE);
7349               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7350             }
7351           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7352           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7353             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7354         }
7355       else
7356         {
7357           t = make_class_type (TREE_CODE (template_type));
7358           CLASSTYPE_DECLARED_CLASS (t)
7359             = CLASSTYPE_DECLARED_CLASS (template_type);
7360           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7361           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7362
7363           /* A local class.  Make sure the decl gets registered properly.  */
7364           if (context == current_function_decl)
7365             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7366
7367           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7368             /* This instantiation is another name for the primary
7369                template type. Set the TYPE_CANONICAL field
7370                appropriately. */
7371             TYPE_CANONICAL (t) = template_type;
7372           else if (any_template_arguments_need_structural_equality_p (arglist))
7373             /* Some of the template arguments require structural
7374                equality testing, so this template class requires
7375                structural equality testing. */
7376             SET_TYPE_STRUCTURAL_EQUALITY (t);
7377         }
7378
7379       /* If we called start_enum or pushtag above, this information
7380          will already be set up.  */
7381       if (!TYPE_NAME (t))
7382         {
7383           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7384
7385           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7386           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7387           DECL_SOURCE_LOCATION (type_decl)
7388             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7389         }
7390       else
7391         type_decl = TYPE_NAME (t);
7392
7393       TREE_PRIVATE (type_decl)
7394         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7395       TREE_PROTECTED (type_decl)
7396         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7397       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7398         {
7399           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7400           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7401         }
7402
7403       /* Let's consider the explicit specialization of a member
7404          of a class template specialization that is implicitely instantiated,
7405          e.g.:
7406              template<class T>
7407              struct S
7408              {
7409                template<class U> struct M {}; //#0
7410              };
7411
7412              template<>
7413              template<>
7414              struct S<int>::M<char> //#1
7415              {
7416                int i;
7417              };
7418         [temp.expl.spec]/4 says this is valid.
7419
7420         In this case, when we write:
7421         S<int>::M<char> m;
7422
7423         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7424         the one of #0.
7425
7426         When we encounter #1, we want to store the partial instantiation
7427         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7428
7429         For all cases other than this "explicit specialization of member of a
7430         class template", we just want to store the most general template into
7431         the CLASSTYPE_TI_TEMPLATE of M.
7432
7433         This case of "explicit specialization of member of a class template"
7434         only happens when:
7435         1/ the enclosing class is an instantiation of, and therefore not
7436         the same as, the context of the most general template, and
7437         2/ we aren't looking at the partial instantiation itself, i.e.
7438         the innermost arguments are not the same as the innermost parms of
7439         the most general template.
7440
7441         So it's only when 1/ and 2/ happens that we want to use the partial
7442         instantiation of the member template in lieu of its most general
7443         template.  */
7444
7445       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7446           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7447           /* the enclosing class must be an instantiation...  */
7448           && CLASS_TYPE_P (context)
7449           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7450         {
7451           tree partial_inst_args;
7452           TREE_VEC_LENGTH (arglist)--;
7453           ++processing_template_decl;
7454           partial_inst_args =
7455             tsubst (INNERMOST_TEMPLATE_ARGS
7456                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7457                     arglist, complain, NULL_TREE);
7458           --processing_template_decl;
7459           TREE_VEC_LENGTH (arglist)++;
7460           use_partial_inst_tmpl =
7461             /*...and we must not be looking at the partial instantiation
7462              itself. */
7463             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7464                                  partial_inst_args);
7465         }
7466
7467       if (!use_partial_inst_tmpl)
7468         /* This case is easy; there are no member templates involved.  */
7469         found = gen_tmpl;
7470       else
7471         {
7472           /* This is a full instantiation of a member template.  Find
7473              the partial instantiation of which this is an instance.  */
7474
7475           /* Temporarily reduce by one the number of levels in the ARGLIST
7476              so as to avoid comparing the last set of arguments.  */
7477           TREE_VEC_LENGTH (arglist)--;
7478           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7479           TREE_VEC_LENGTH (arglist)++;
7480           found = CLASSTYPE_TI_TEMPLATE (found);
7481         }
7482
7483       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7484
7485       elt.spec = t;
7486       slot = htab_find_slot_with_hash (type_specializations,
7487                                        &elt, hash, INSERT);
7488       entry = ggc_alloc_spec_entry ();
7489       *entry = elt;
7490       *slot = entry;
7491
7492       /* Note this use of the partial instantiation so we can check it
7493          later in maybe_process_partial_specialization.  */
7494       DECL_TEMPLATE_INSTANTIATIONS (templ)
7495         = tree_cons (arglist, t,
7496                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7497
7498       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7499         /* Now that the type has been registered on the instantiations
7500            list, we set up the enumerators.  Because the enumeration
7501            constants may involve the enumeration type itself, we make
7502            sure to register the type first, and then create the
7503            constants.  That way, doing tsubst_expr for the enumeration
7504            constants won't result in recursive calls here; we'll find
7505            the instantiation and exit above.  */
7506         tsubst_enum (template_type, t, arglist);
7507
7508       if (is_dependent_type)
7509         /* If the type makes use of template parameters, the
7510            code that generates debugging information will crash.  */
7511         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7512
7513       /* Possibly limit visibility based on template args.  */
7514       TREE_PUBLIC (type_decl) = 1;
7515       determine_visibility (type_decl);
7516
7517       return t;
7518     }
7519 }
7520
7521 /* Wrapper for lookup_template_class_1.  */
7522
7523 tree
7524 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7525                        int entering_scope, tsubst_flags_t complain)
7526 {
7527   tree ret;
7528   timevar_push (TV_TEMPLATE_INST);
7529   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7530                                  entering_scope, complain);
7531   timevar_pop (TV_TEMPLATE_INST);
7532   return ret;
7533 }
7534 \f
7535 struct pair_fn_data
7536 {
7537   tree_fn_t fn;
7538   void *data;
7539   /* True when we should also visit template parameters that occur in
7540      non-deduced contexts.  */
7541   bool include_nondeduced_p;
7542   struct pointer_set_t *visited;
7543 };
7544
7545 /* Called from for_each_template_parm via walk_tree.  */
7546
7547 static tree
7548 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7549 {
7550   tree t = *tp;
7551   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7552   tree_fn_t fn = pfd->fn;
7553   void *data = pfd->data;
7554
7555   if (TYPE_P (t)
7556       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7557       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7558                                  pfd->include_nondeduced_p))
7559     return error_mark_node;
7560
7561   switch (TREE_CODE (t))
7562     {
7563     case RECORD_TYPE:
7564       if (TYPE_PTRMEMFUNC_P (t))
7565         break;
7566       /* Fall through.  */
7567
7568     case UNION_TYPE:
7569     case ENUMERAL_TYPE:
7570       if (!TYPE_TEMPLATE_INFO (t))
7571         *walk_subtrees = 0;
7572       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7573                                        fn, data, pfd->visited, 
7574                                        pfd->include_nondeduced_p))
7575         return error_mark_node;
7576       break;
7577
7578     case INTEGER_TYPE:
7579       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7580                                   fn, data, pfd->visited, 
7581                                   pfd->include_nondeduced_p)
7582           || for_each_template_parm (TYPE_MAX_VALUE (t),
7583                                      fn, data, pfd->visited,
7584                                      pfd->include_nondeduced_p))
7585         return error_mark_node;
7586       break;
7587
7588     case METHOD_TYPE:
7589       /* Since we're not going to walk subtrees, we have to do this
7590          explicitly here.  */
7591       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7592                                   pfd->visited, pfd->include_nondeduced_p))
7593         return error_mark_node;
7594       /* Fall through.  */
7595
7596     case FUNCTION_TYPE:
7597       /* Check the return type.  */
7598       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7599                                   pfd->include_nondeduced_p))
7600         return error_mark_node;
7601
7602       /* Check the parameter types.  Since default arguments are not
7603          instantiated until they are needed, the TYPE_ARG_TYPES may
7604          contain expressions that involve template parameters.  But,
7605          no-one should be looking at them yet.  And, once they're
7606          instantiated, they don't contain template parameters, so
7607          there's no point in looking at them then, either.  */
7608       {
7609         tree parm;
7610
7611         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7612           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7613                                       pfd->visited, pfd->include_nondeduced_p))
7614             return error_mark_node;
7615
7616         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7617            want walk_tree walking into them itself.  */
7618         *walk_subtrees = 0;
7619       }
7620       break;
7621
7622     case TYPEOF_TYPE:
7623     case UNDERLYING_TYPE:
7624       if (pfd->include_nondeduced_p
7625           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7626                                      pfd->visited, 
7627                                      pfd->include_nondeduced_p))
7628         return error_mark_node;
7629       break;
7630
7631     case FUNCTION_DECL:
7632     case VAR_DECL:
7633       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7634           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7635                                      pfd->visited, pfd->include_nondeduced_p))
7636         return error_mark_node;
7637       /* Fall through.  */
7638
7639     case PARM_DECL:
7640     case CONST_DECL:
7641       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7642           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7643                                      pfd->visited, pfd->include_nondeduced_p))
7644         return error_mark_node;
7645       if (DECL_CONTEXT (t)
7646           && pfd->include_nondeduced_p
7647           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7648                                      pfd->visited, pfd->include_nondeduced_p))
7649         return error_mark_node;
7650       break;
7651
7652     case BOUND_TEMPLATE_TEMPLATE_PARM:
7653       /* Record template parameters such as `T' inside `TT<T>'.  */
7654       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7655                                   pfd->include_nondeduced_p))
7656         return error_mark_node;
7657       /* Fall through.  */
7658
7659     case TEMPLATE_TEMPLATE_PARM:
7660     case TEMPLATE_TYPE_PARM:
7661     case TEMPLATE_PARM_INDEX:
7662       if (fn && (*fn)(t, data))
7663         return error_mark_node;
7664       else if (!fn)
7665         return error_mark_node;
7666       break;
7667
7668     case TEMPLATE_DECL:
7669       /* A template template parameter is encountered.  */
7670       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7671           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7672                                      pfd->include_nondeduced_p))
7673         return error_mark_node;
7674
7675       /* Already substituted template template parameter */
7676       *walk_subtrees = 0;
7677       break;
7678
7679     case TYPENAME_TYPE:
7680       if (!fn
7681           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7682                                      data, pfd->visited, 
7683                                      pfd->include_nondeduced_p))
7684         return error_mark_node;
7685       break;
7686
7687     case CONSTRUCTOR:
7688       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7689           && pfd->include_nondeduced_p
7690           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7691                                      (TREE_TYPE (t)), fn, data,
7692                                      pfd->visited, pfd->include_nondeduced_p))
7693         return error_mark_node;
7694       break;
7695
7696     case INDIRECT_REF:
7697     case COMPONENT_REF:
7698       /* If there's no type, then this thing must be some expression
7699          involving template parameters.  */
7700       if (!fn && !TREE_TYPE (t))
7701         return error_mark_node;
7702       break;
7703
7704     case MODOP_EXPR:
7705     case CAST_EXPR:
7706     case IMPLICIT_CONV_EXPR:
7707     case REINTERPRET_CAST_EXPR:
7708     case CONST_CAST_EXPR:
7709     case STATIC_CAST_EXPR:
7710     case DYNAMIC_CAST_EXPR:
7711     case ARROW_EXPR:
7712     case DOTSTAR_EXPR:
7713     case TYPEID_EXPR:
7714     case PSEUDO_DTOR_EXPR:
7715       if (!fn)
7716         return error_mark_node;
7717       break;
7718
7719     default:
7720       break;
7721     }
7722
7723   /* We didn't find any template parameters we liked.  */
7724   return NULL_TREE;
7725 }
7726
7727 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7728    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7729    call FN with the parameter and the DATA.
7730    If FN returns nonzero, the iteration is terminated, and
7731    for_each_template_parm returns 1.  Otherwise, the iteration
7732    continues.  If FN never returns a nonzero value, the value
7733    returned by for_each_template_parm is 0.  If FN is NULL, it is
7734    considered to be the function which always returns 1.
7735
7736    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7737    parameters that occur in non-deduced contexts.  When false, only
7738    visits those template parameters that can be deduced.  */
7739
7740 static int
7741 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7742                         struct pointer_set_t *visited,
7743                         bool include_nondeduced_p)
7744 {
7745   struct pair_fn_data pfd;
7746   int result;
7747
7748   /* Set up.  */
7749   pfd.fn = fn;
7750   pfd.data = data;
7751   pfd.include_nondeduced_p = include_nondeduced_p;
7752
7753   /* Walk the tree.  (Conceptually, we would like to walk without
7754      duplicates, but for_each_template_parm_r recursively calls
7755      for_each_template_parm, so we would need to reorganize a fair
7756      bit to use walk_tree_without_duplicates, so we keep our own
7757      visited list.)  */
7758   if (visited)
7759     pfd.visited = visited;
7760   else
7761     pfd.visited = pointer_set_create ();
7762   result = cp_walk_tree (&t,
7763                          for_each_template_parm_r,
7764                          &pfd,
7765                          pfd.visited) != NULL_TREE;
7766
7767   /* Clean up.  */
7768   if (!visited)
7769     {
7770       pointer_set_destroy (pfd.visited);
7771       pfd.visited = 0;
7772     }
7773
7774   return result;
7775 }
7776
7777 /* Returns true if T depends on any template parameter.  */
7778
7779 int
7780 uses_template_parms (tree t)
7781 {
7782   bool dependent_p;
7783   int saved_processing_template_decl;
7784
7785   saved_processing_template_decl = processing_template_decl;
7786   if (!saved_processing_template_decl)
7787     processing_template_decl = 1;
7788   if (TYPE_P (t))
7789     dependent_p = dependent_type_p (t);
7790   else if (TREE_CODE (t) == TREE_VEC)
7791     dependent_p = any_dependent_template_arguments_p (t);
7792   else if (TREE_CODE (t) == TREE_LIST)
7793     dependent_p = (uses_template_parms (TREE_VALUE (t))
7794                    || uses_template_parms (TREE_CHAIN (t)));
7795   else if (TREE_CODE (t) == TYPE_DECL)
7796     dependent_p = dependent_type_p (TREE_TYPE (t));
7797   else if (DECL_P (t)
7798            || EXPR_P (t)
7799            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7800            || TREE_CODE (t) == OVERLOAD
7801            || TREE_CODE (t) == BASELINK
7802            || TREE_CODE (t) == IDENTIFIER_NODE
7803            || TREE_CODE (t) == TRAIT_EXPR
7804            || TREE_CODE (t) == CONSTRUCTOR
7805            || CONSTANT_CLASS_P (t))
7806     dependent_p = (type_dependent_expression_p (t)
7807                    || value_dependent_expression_p (t));
7808   else
7809     {
7810       gcc_assert (t == error_mark_node);
7811       dependent_p = false;
7812     }
7813
7814   processing_template_decl = saved_processing_template_decl;
7815
7816   return dependent_p;
7817 }
7818
7819 /* Returns true if T depends on any template parameter with level LEVEL.  */
7820
7821 int
7822 uses_template_parms_level (tree t, int level)
7823 {
7824   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7825                                  /*include_nondeduced_p=*/true);
7826 }
7827
7828 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7829    ill-formed translation unit, i.e. a variable or function that isn't
7830    usable in a constant expression.  */
7831
7832 static inline bool
7833 neglectable_inst_p (tree d)
7834 {
7835   return (DECL_P (d)
7836           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7837                : decl_maybe_constant_var_p (d)));
7838 }
7839
7840 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7841    neglectable and instantiated from within an erroneous instantiation.  */
7842
7843 static bool
7844 limit_bad_template_recursion (tree decl)
7845 {
7846   struct tinst_level *lev = current_tinst_level;
7847   int errs = errorcount + sorrycount;
7848   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7849     return false;
7850
7851   for (; lev; lev = lev->next)
7852     if (neglectable_inst_p (lev->decl))
7853       break;
7854
7855   return (lev && errs > lev->errors);
7856 }
7857
7858 static int tinst_depth;
7859 extern int max_tinst_depth;
7860 #ifdef GATHER_STATISTICS
7861 int depth_reached;
7862 #endif
7863 static GTY(()) struct tinst_level *last_error_tinst_level;
7864
7865 /* We're starting to instantiate D; record the template instantiation context
7866    for diagnostics and to restore it later.  */
7867
7868 int
7869 push_tinst_level (tree d)
7870 {
7871   struct tinst_level *new_level;
7872
7873   if (tinst_depth >= max_tinst_depth)
7874     {
7875       last_error_tinst_level = current_tinst_level;
7876       if (TREE_CODE (d) == TREE_LIST)
7877         error ("template instantiation depth exceeds maximum of %d (use "
7878                "-ftemplate-depth= to increase the maximum) substituting %qS",
7879                max_tinst_depth, d);
7880       else
7881         error ("template instantiation depth exceeds maximum of %d (use "
7882                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7883                max_tinst_depth, d);
7884
7885       print_instantiation_context ();
7886
7887       return 0;
7888     }
7889
7890   /* If the current instantiation caused problems, don't let it instantiate
7891      anything else.  Do allow deduction substitution and decls usable in
7892      constant expressions.  */
7893   if (limit_bad_template_recursion (d))
7894     return 0;
7895
7896   new_level = ggc_alloc_tinst_level ();
7897   new_level->decl = d;
7898   new_level->locus = input_location;
7899   new_level->errors = errorcount+sorrycount;
7900   new_level->in_system_header_p = in_system_header;
7901   new_level->next = current_tinst_level;
7902   current_tinst_level = new_level;
7903
7904   ++tinst_depth;
7905 #ifdef GATHER_STATISTICS
7906   if (tinst_depth > depth_reached)
7907     depth_reached = tinst_depth;
7908 #endif
7909
7910   return 1;
7911 }
7912
7913 /* We're done instantiating this template; return to the instantiation
7914    context.  */
7915
7916 void
7917 pop_tinst_level (void)
7918 {
7919   /* Restore the filename and line number stashed away when we started
7920      this instantiation.  */
7921   input_location = current_tinst_level->locus;
7922   current_tinst_level = current_tinst_level->next;
7923   --tinst_depth;
7924 }
7925
7926 /* We're instantiating a deferred template; restore the template
7927    instantiation context in which the instantiation was requested, which
7928    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7929
7930 static tree
7931 reopen_tinst_level (struct tinst_level *level)
7932 {
7933   struct tinst_level *t;
7934
7935   tinst_depth = 0;
7936   for (t = level; t; t = t->next)
7937     ++tinst_depth;
7938
7939   current_tinst_level = level;
7940   pop_tinst_level ();
7941   if (current_tinst_level)
7942     current_tinst_level->errors = errorcount+sorrycount;
7943   return level->decl;
7944 }
7945
7946 /* Returns the TINST_LEVEL which gives the original instantiation
7947    context.  */
7948
7949 struct tinst_level *
7950 outermost_tinst_level (void)
7951 {
7952   struct tinst_level *level = current_tinst_level;
7953   if (level)
7954     while (level->next)
7955       level = level->next;
7956   return level;
7957 }
7958
7959 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7960
7961 bool
7962 parameter_of_template_p (tree parm, tree templ)
7963 {
7964   tree parms;
7965   int i;
7966
7967   if (!parm || !templ)
7968     return false;
7969
7970   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7971   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7972
7973   parms = DECL_TEMPLATE_PARMS (templ);
7974   parms = INNERMOST_TEMPLATE_PARMS (parms);
7975
7976   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7977     {
7978       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7979       if (parm == p
7980           || (DECL_INITIAL (parm)
7981               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7982         return true;
7983     }
7984
7985   return false;
7986 }
7987
7988 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7989    vector of template arguments, as for tsubst.
7990
7991    Returns an appropriate tsubst'd friend declaration.  */
7992
7993 static tree
7994 tsubst_friend_function (tree decl, tree args)
7995 {
7996   tree new_friend;
7997
7998   if (TREE_CODE (decl) == FUNCTION_DECL
7999       && DECL_TEMPLATE_INSTANTIATION (decl)
8000       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8001     /* This was a friend declared with an explicit template
8002        argument list, e.g.:
8003
8004        friend void f<>(T);
8005
8006        to indicate that f was a template instantiation, not a new
8007        function declaration.  Now, we have to figure out what
8008        instantiation of what template.  */
8009     {
8010       tree template_id, arglist, fns;
8011       tree new_args;
8012       tree tmpl;
8013       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8014
8015       /* Friend functions are looked up in the containing namespace scope.
8016          We must enter that scope, to avoid finding member functions of the
8017          current class with same name.  */
8018       push_nested_namespace (ns);
8019       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8020                          tf_warning_or_error, NULL_TREE,
8021                          /*integral_constant_expression_p=*/false);
8022       pop_nested_namespace (ns);
8023       arglist = tsubst (DECL_TI_ARGS (decl), args,
8024                         tf_warning_or_error, NULL_TREE);
8025       template_id = lookup_template_function (fns, arglist);
8026
8027       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8028       tmpl = determine_specialization (template_id, new_friend,
8029                                        &new_args,
8030                                        /*need_member_template=*/0,
8031                                        TREE_VEC_LENGTH (args),
8032                                        tsk_none);
8033       return instantiate_template (tmpl, new_args, tf_error);
8034     }
8035
8036   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8037
8038   /* The NEW_FRIEND will look like an instantiation, to the
8039      compiler, but is not an instantiation from the point of view of
8040      the language.  For example, we might have had:
8041
8042      template <class T> struct S {
8043        template <class U> friend void f(T, U);
8044      };
8045
8046      Then, in S<int>, template <class U> void f(int, U) is not an
8047      instantiation of anything.  */
8048   if (new_friend == error_mark_node)
8049     return error_mark_node;
8050
8051   DECL_USE_TEMPLATE (new_friend) = 0;
8052   if (TREE_CODE (decl) == TEMPLATE_DECL)
8053     {
8054       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8055       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8056         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8057     }
8058
8059   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8060      is not a template instantiation and should not be mangled like
8061      one.  Therefore, we forget the mangling here; we'll recompute it
8062      later if we need it.  */
8063   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8064     {
8065       SET_DECL_RTL (new_friend, NULL);
8066       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8067     }
8068
8069   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8070     {
8071       tree old_decl;
8072       tree new_friend_template_info;
8073       tree new_friend_result_template_info;
8074       tree ns;
8075       int  new_friend_is_defn;
8076
8077       /* We must save some information from NEW_FRIEND before calling
8078          duplicate decls since that function will free NEW_FRIEND if
8079          possible.  */
8080       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8081       new_friend_is_defn =
8082             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8083                            (template_for_substitution (new_friend)))
8084              != NULL_TREE);
8085       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8086         {
8087           /* This declaration is a `primary' template.  */
8088           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8089
8090           new_friend_result_template_info
8091             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8092         }
8093       else
8094         new_friend_result_template_info = NULL_TREE;
8095
8096       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8097       if (new_friend_is_defn)
8098         DECL_INITIAL (new_friend) = error_mark_node;
8099
8100       /* Inside pushdecl_namespace_level, we will push into the
8101          current namespace. However, the friend function should go
8102          into the namespace of the template.  */
8103       ns = decl_namespace_context (new_friend);
8104       push_nested_namespace (ns);
8105       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8106       pop_nested_namespace (ns);
8107
8108       if (old_decl == error_mark_node)
8109         return error_mark_node;
8110
8111       if (old_decl != new_friend)
8112         {
8113           /* This new friend declaration matched an existing
8114              declaration.  For example, given:
8115
8116                template <class T> void f(T);
8117                template <class U> class C {
8118                  template <class T> friend void f(T) {}
8119                };
8120
8121              the friend declaration actually provides the definition
8122              of `f', once C has been instantiated for some type.  So,
8123              old_decl will be the out-of-class template declaration,
8124              while new_friend is the in-class definition.
8125
8126              But, if `f' was called before this point, the
8127              instantiation of `f' will have DECL_TI_ARGS corresponding
8128              to `T' but not to `U', references to which might appear
8129              in the definition of `f'.  Previously, the most general
8130              template for an instantiation of `f' was the out-of-class
8131              version; now it is the in-class version.  Therefore, we
8132              run through all specialization of `f', adding to their
8133              DECL_TI_ARGS appropriately.  In particular, they need a
8134              new set of outer arguments, corresponding to the
8135              arguments for this class instantiation.
8136
8137              The same situation can arise with something like this:
8138
8139                friend void f(int);
8140                template <class T> class C {
8141                  friend void f(T) {}
8142                };
8143
8144              when `C<int>' is instantiated.  Now, `f(int)' is defined
8145              in the class.  */
8146
8147           if (!new_friend_is_defn)
8148             /* On the other hand, if the in-class declaration does
8149                *not* provide a definition, then we don't want to alter
8150                existing definitions.  We can just leave everything
8151                alone.  */
8152             ;
8153           else
8154             {
8155               tree new_template = TI_TEMPLATE (new_friend_template_info);
8156               tree new_args = TI_ARGS (new_friend_template_info);
8157
8158               /* Overwrite whatever template info was there before, if
8159                  any, with the new template information pertaining to
8160                  the declaration.  */
8161               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8162
8163               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8164                 {
8165                   /* We should have called reregister_specialization in
8166                      duplicate_decls.  */
8167                   gcc_assert (retrieve_specialization (new_template,
8168                                                        new_args, 0)
8169                               == old_decl);
8170
8171                   /* Instantiate it if the global has already been used.  */
8172                   if (DECL_ODR_USED (old_decl))
8173                     instantiate_decl (old_decl, /*defer_ok=*/true,
8174                                       /*expl_inst_class_mem_p=*/false);
8175                 }
8176               else
8177                 {
8178                   tree t;
8179
8180                   /* Indicate that the old function template is a partial
8181                      instantiation.  */
8182                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8183                     = new_friend_result_template_info;
8184
8185                   gcc_assert (new_template
8186                               == most_general_template (new_template));
8187                   gcc_assert (new_template != old_decl);
8188
8189                   /* Reassign any specializations already in the hash table
8190                      to the new more general template, and add the
8191                      additional template args.  */
8192                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8193                        t != NULL_TREE;
8194                        t = TREE_CHAIN (t))
8195                     {
8196                       tree spec = TREE_VALUE (t);
8197                       spec_entry elt;
8198
8199                       elt.tmpl = old_decl;
8200                       elt.args = DECL_TI_ARGS (spec);
8201                       elt.spec = NULL_TREE;
8202
8203                       htab_remove_elt (decl_specializations, &elt);
8204
8205                       DECL_TI_ARGS (spec)
8206                         = add_outermost_template_args (new_args,
8207                                                        DECL_TI_ARGS (spec));
8208
8209                       register_specialization
8210                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8211
8212                     }
8213                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8214                 }
8215             }
8216
8217           /* The information from NEW_FRIEND has been merged into OLD_DECL
8218              by duplicate_decls.  */
8219           new_friend = old_decl;
8220         }
8221     }
8222   else
8223     {
8224       tree context = DECL_CONTEXT (new_friend);
8225       bool dependent_p;
8226
8227       /* In the code
8228            template <class T> class C {
8229              template <class U> friend void C1<U>::f (); // case 1
8230              friend void C2<T>::f ();                    // case 2
8231            };
8232          we only need to make sure CONTEXT is a complete type for
8233          case 2.  To distinguish between the two cases, we note that
8234          CONTEXT of case 1 remains dependent type after tsubst while
8235          this isn't true for case 2.  */
8236       ++processing_template_decl;
8237       dependent_p = dependent_type_p (context);
8238       --processing_template_decl;
8239
8240       if (!dependent_p
8241           && !complete_type_or_else (context, NULL_TREE))
8242         return error_mark_node;
8243
8244       if (COMPLETE_TYPE_P (context))
8245         {
8246           /* Check to see that the declaration is really present, and,
8247              possibly obtain an improved declaration.  */
8248           tree fn = check_classfn (context,
8249                                    new_friend, NULL_TREE);
8250
8251           if (fn)
8252             new_friend = fn;
8253         }
8254     }
8255
8256   return new_friend;
8257 }
8258
8259 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8260    template arguments, as for tsubst.
8261
8262    Returns an appropriate tsubst'd friend type or error_mark_node on
8263    failure.  */
8264
8265 static tree
8266 tsubst_friend_class (tree friend_tmpl, tree args)
8267 {
8268   tree friend_type;
8269   tree tmpl;
8270   tree context;
8271
8272   context = CP_DECL_CONTEXT (friend_tmpl);
8273
8274   if (context != global_namespace)
8275     {
8276       if (TREE_CODE (context) == NAMESPACE_DECL)
8277         push_nested_namespace (context);
8278       else
8279         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8280     }
8281
8282   /* Look for a class template declaration.  We look for hidden names
8283      because two friend declarations of the same template are the
8284      same.  For example, in:
8285
8286        struct A { 
8287          template <typename> friend class F;
8288        };
8289        template <typename> struct B { 
8290          template <typename> friend class F;
8291        };
8292
8293      both F templates are the same.  */
8294   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8295                            /*block_p=*/true, 0, 
8296                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8297
8298   /* But, if we don't find one, it might be because we're in a
8299      situation like this:
8300
8301        template <class T>
8302        struct S {
8303          template <class U>
8304          friend struct S;
8305        };
8306
8307      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8308      for `S<int>', not the TEMPLATE_DECL.  */
8309   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8310     {
8311       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8312       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8313     }
8314
8315   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8316     {
8317       /* The friend template has already been declared.  Just
8318          check to see that the declarations match, and install any new
8319          default parameters.  We must tsubst the default parameters,
8320          of course.  We only need the innermost template parameters
8321          because that is all that redeclare_class_template will look
8322          at.  */
8323       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8324           > TMPL_ARGS_DEPTH (args))
8325         {
8326           tree parms;
8327           location_t saved_input_location;
8328           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8329                                          args, tf_warning_or_error);
8330
8331           saved_input_location = input_location;
8332           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8333           redeclare_class_template (TREE_TYPE (tmpl), parms);
8334           input_location = saved_input_location;
8335           
8336         }
8337
8338       friend_type = TREE_TYPE (tmpl);
8339     }
8340   else
8341     {
8342       /* The friend template has not already been declared.  In this
8343          case, the instantiation of the template class will cause the
8344          injection of this template into the global scope.  */
8345       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8346       if (tmpl == error_mark_node)
8347         return error_mark_node;
8348
8349       /* The new TMPL is not an instantiation of anything, so we
8350          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8351          the new type because that is supposed to be the corresponding
8352          template decl, i.e., TMPL.  */
8353       DECL_USE_TEMPLATE (tmpl) = 0;
8354       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8355       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8356       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8357         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8358
8359       /* Inject this template into the global scope.  */
8360       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8361     }
8362
8363   if (context != global_namespace)
8364     {
8365       if (TREE_CODE (context) == NAMESPACE_DECL)
8366         pop_nested_namespace (context);
8367       else
8368         pop_nested_class ();
8369     }
8370
8371   return friend_type;
8372 }
8373
8374 /* Returns zero if TYPE cannot be completed later due to circularity.
8375    Otherwise returns one.  */
8376
8377 static int
8378 can_complete_type_without_circularity (tree type)
8379 {
8380   if (type == NULL_TREE || type == error_mark_node)
8381     return 0;
8382   else if (COMPLETE_TYPE_P (type))
8383     return 1;
8384   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8385     return can_complete_type_without_circularity (TREE_TYPE (type));
8386   else if (CLASS_TYPE_P (type)
8387            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8388     return 0;
8389   else
8390     return 1;
8391 }
8392
8393 /* Apply any attributes which had to be deferred until instantiation
8394    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8395    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8396
8397 static void
8398 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8399                                 tree args, tsubst_flags_t complain, tree in_decl)
8400 {
8401   tree last_dep = NULL_TREE;
8402   tree t;
8403   tree *p;
8404
8405   for (t = attributes; t; t = TREE_CHAIN (t))
8406     if (ATTR_IS_DEPENDENT (t))
8407       {
8408         last_dep = t;
8409         attributes = copy_list (attributes);
8410         break;
8411       }
8412
8413   if (DECL_P (*decl_p))
8414     {
8415       if (TREE_TYPE (*decl_p) == error_mark_node)
8416         return;
8417       p = &DECL_ATTRIBUTES (*decl_p);
8418     }
8419   else
8420     p = &TYPE_ATTRIBUTES (*decl_p);
8421
8422   if (last_dep)
8423     {
8424       tree late_attrs = NULL_TREE;
8425       tree *q = &late_attrs;
8426
8427       for (*p = attributes; *p; )
8428         {
8429           t = *p;
8430           if (ATTR_IS_DEPENDENT (t))
8431             {
8432               *p = TREE_CHAIN (t);
8433               TREE_CHAIN (t) = NULL_TREE;
8434               /* If the first attribute argument is an identifier, don't
8435                  pass it through tsubst.  Attributes like mode, format,
8436                  cleanup and several target specific attributes expect it
8437                  unmodified.  */
8438               if (TREE_VALUE (t)
8439                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8440                   && TREE_VALUE (TREE_VALUE (t))
8441                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8442                       == IDENTIFIER_NODE))
8443                 {
8444                   tree chain
8445                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8446                                    in_decl,
8447                                    /*integral_constant_expression_p=*/false);
8448                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8449                     TREE_VALUE (t)
8450                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8451                                    chain);
8452                 }
8453               else
8454                 TREE_VALUE (t)
8455                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8456                                  /*integral_constant_expression_p=*/false);
8457               *q = t;
8458               q = &TREE_CHAIN (t);
8459             }
8460           else
8461             p = &TREE_CHAIN (t);
8462         }
8463
8464       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8465     }
8466 }
8467
8468 /* Perform (or defer) access check for typedefs that were referenced
8469    from within the template TMPL code.
8470    This is a subroutine of instantiate_template and instantiate_class_template.
8471    TMPL is the template to consider and TARGS is the list of arguments of
8472    that template.  */
8473
8474 static void
8475 perform_typedefs_access_check (tree tmpl, tree targs)
8476 {
8477   location_t saved_location;
8478   int i;
8479   qualified_typedef_usage_t *iter;
8480
8481   if (!tmpl
8482       || (!CLASS_TYPE_P (tmpl)
8483           && TREE_CODE (tmpl) != FUNCTION_DECL))
8484     return;
8485
8486   saved_location = input_location;
8487   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8488                     get_types_needing_access_check (tmpl),
8489                     i, iter)
8490     {
8491       tree type_decl = iter->typedef_decl;
8492       tree type_scope = iter->context;
8493
8494       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8495         continue;
8496
8497       if (uses_template_parms (type_decl))
8498         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8499       if (uses_template_parms (type_scope))
8500         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8501
8502       /* Make access check error messages point to the location
8503          of the use of the typedef.  */
8504       input_location = iter->locus;
8505       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8506                                      type_decl, type_decl);
8507     }
8508     input_location = saved_location;
8509 }
8510
8511 static tree
8512 instantiate_class_template_1 (tree type)
8513 {
8514   tree templ, args, pattern, t, member;
8515   tree typedecl;
8516   tree pbinfo;
8517   tree base_list;
8518   unsigned int saved_maximum_field_alignment;
8519
8520   if (type == error_mark_node)
8521     return error_mark_node;
8522
8523   if (COMPLETE_OR_OPEN_TYPE_P (type)
8524       || uses_template_parms (type))
8525     return type;
8526
8527   /* Figure out which template is being instantiated.  */
8528   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8529   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8530
8531   /* Determine what specialization of the original template to
8532      instantiate.  */
8533   t = most_specialized_class (type, templ, tf_warning_or_error);
8534   if (t == error_mark_node)
8535     {
8536       TYPE_BEING_DEFINED (type) = 1;
8537       return error_mark_node;
8538     }
8539   else if (t)
8540     {
8541       /* This TYPE is actually an instantiation of a partial
8542          specialization.  We replace the innermost set of ARGS with
8543          the arguments appropriate for substitution.  For example,
8544          given:
8545
8546            template <class T> struct S {};
8547            template <class T> struct S<T*> {};
8548
8549          and supposing that we are instantiating S<int*>, ARGS will
8550          presently be {int*} -- but we need {int}.  */
8551       pattern = TREE_TYPE (t);
8552       args = TREE_PURPOSE (t);
8553     }
8554   else
8555     {
8556       pattern = TREE_TYPE (templ);
8557       args = CLASSTYPE_TI_ARGS (type);
8558     }
8559
8560   /* If the template we're instantiating is incomplete, then clearly
8561      there's nothing we can do.  */
8562   if (!COMPLETE_TYPE_P (pattern))
8563     return type;
8564
8565   /* If we've recursively instantiated too many templates, stop.  */
8566   if (! push_tinst_level (type))
8567     return type;
8568
8569   /* Now we're really doing the instantiation.  Mark the type as in
8570      the process of being defined.  */
8571   TYPE_BEING_DEFINED (type) = 1;
8572
8573   /* We may be in the middle of deferred access check.  Disable
8574      it now.  */
8575   push_deferring_access_checks (dk_no_deferred);
8576
8577   push_to_top_level ();
8578   /* Use #pragma pack from the template context.  */
8579   saved_maximum_field_alignment = maximum_field_alignment;
8580   maximum_field_alignment = TYPE_PRECISION (pattern);
8581
8582   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8583
8584   /* Set the input location to the most specialized template definition.
8585      This is needed if tsubsting causes an error.  */
8586   typedecl = TYPE_MAIN_DECL (pattern);
8587   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8588     DECL_SOURCE_LOCATION (typedecl);
8589
8590   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8591   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8592   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8593   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8594   if (ANON_AGGR_TYPE_P (pattern))
8595     SET_ANON_AGGR_TYPE_P (type);
8596   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8597     {
8598       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8599       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8600     }
8601   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8602
8603   pbinfo = TYPE_BINFO (pattern);
8604
8605   /* We should never instantiate a nested class before its enclosing
8606      class; we need to look up the nested class by name before we can
8607      instantiate it, and that lookup should instantiate the enclosing
8608      class.  */
8609   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8610               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8611
8612   base_list = NULL_TREE;
8613   if (BINFO_N_BASE_BINFOS (pbinfo))
8614     {
8615       tree pbase_binfo;
8616       tree pushed_scope;
8617       int i;
8618
8619       /* We must enter the scope containing the type, as that is where
8620          the accessibility of types named in dependent bases are
8621          looked up from.  */
8622       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8623
8624       /* Substitute into each of the bases to determine the actual
8625          basetypes.  */
8626       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8627         {
8628           tree base;
8629           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8630           tree expanded_bases = NULL_TREE;
8631           int idx, len = 1;
8632
8633           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8634             {
8635               expanded_bases = 
8636                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8637                                        args, tf_error, NULL_TREE);
8638               if (expanded_bases == error_mark_node)
8639                 continue;
8640
8641               len = TREE_VEC_LENGTH (expanded_bases);
8642             }
8643
8644           for (idx = 0; idx < len; idx++)
8645             {
8646               if (expanded_bases)
8647                 /* Extract the already-expanded base class.  */
8648                 base = TREE_VEC_ELT (expanded_bases, idx);
8649               else
8650                 /* Substitute to figure out the base class.  */
8651                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8652                                NULL_TREE);
8653
8654               if (base == error_mark_node)
8655                 continue;
8656
8657               base_list = tree_cons (access, base, base_list);
8658               if (BINFO_VIRTUAL_P (pbase_binfo))
8659                 TREE_TYPE (base_list) = integer_type_node;
8660             }
8661         }
8662
8663       /* The list is now in reverse order; correct that.  */
8664       base_list = nreverse (base_list);
8665
8666       if (pushed_scope)
8667         pop_scope (pushed_scope);
8668     }
8669   /* Now call xref_basetypes to set up all the base-class
8670      information.  */
8671   xref_basetypes (type, base_list);
8672
8673   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8674                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8675                                   args, tf_error, NULL_TREE);
8676   fixup_attribute_variants (type);
8677
8678   /* Now that our base classes are set up, enter the scope of the
8679      class, so that name lookups into base classes, etc. will work
8680      correctly.  This is precisely analogous to what we do in
8681      begin_class_definition when defining an ordinary non-template
8682      class, except we also need to push the enclosing classes.  */
8683   push_nested_class (type);
8684
8685   /* Now members are processed in the order of declaration.  */
8686   for (member = CLASSTYPE_DECL_LIST (pattern);
8687        member; member = TREE_CHAIN (member))
8688     {
8689       tree t = TREE_VALUE (member);
8690
8691       if (TREE_PURPOSE (member))
8692         {
8693           if (TYPE_P (t))
8694             {
8695               /* Build new CLASSTYPE_NESTED_UTDS.  */
8696
8697               tree newtag;
8698               bool class_template_p;
8699
8700               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8701                                   && TYPE_LANG_SPECIFIC (t)
8702                                   && CLASSTYPE_IS_TEMPLATE (t));
8703               /* If the member is a class template, then -- even after
8704                  substitution -- there may be dependent types in the
8705                  template argument list for the class.  We increment
8706                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8707                  that function will assume that no types are dependent
8708                  when outside of a template.  */
8709               if (class_template_p)
8710                 ++processing_template_decl;
8711               newtag = tsubst (t, args, tf_error, NULL_TREE);
8712               if (class_template_p)
8713                 --processing_template_decl;
8714               if (newtag == error_mark_node)
8715                 continue;
8716
8717               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8718                 {
8719                   tree name = TYPE_IDENTIFIER (t);
8720
8721                   if (class_template_p)
8722                     /* Unfortunately, lookup_template_class sets
8723                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8724                        instantiation (i.e., for the type of a member
8725                        template class nested within a template class.)
8726                        This behavior is required for
8727                        maybe_process_partial_specialization to work
8728                        correctly, but is not accurate in this case;
8729                        the TAG is not an instantiation of anything.
8730                        (The corresponding TEMPLATE_DECL is an
8731                        instantiation, but the TYPE is not.) */
8732                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8733
8734                   /* Now, we call pushtag to put this NEWTAG into the scope of
8735                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8736                      pushtag calling push_template_decl.  We don't have to do
8737                      this for enums because it will already have been done in
8738                      tsubst_enum.  */
8739                   if (name)
8740                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8741                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8742                 }
8743             }
8744           else if (TREE_CODE (t) == FUNCTION_DECL
8745                    || DECL_FUNCTION_TEMPLATE_P (t))
8746             {
8747               /* Build new TYPE_METHODS.  */
8748               tree r;
8749
8750               if (TREE_CODE (t) == TEMPLATE_DECL)
8751                 ++processing_template_decl;
8752               r = tsubst (t, args, tf_error, NULL_TREE);
8753               if (TREE_CODE (t) == TEMPLATE_DECL)
8754                 --processing_template_decl;
8755               set_current_access_from_decl (r);
8756               finish_member_declaration (r);
8757               /* Instantiate members marked with attribute used.  */
8758               if (r != error_mark_node && DECL_PRESERVE_P (r))
8759                 mark_used (r);
8760             }
8761           else
8762             {
8763               /* Build new TYPE_FIELDS.  */
8764               if (TREE_CODE (t) == STATIC_ASSERT)
8765                 {
8766                   tree condition = 
8767                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8768                                  tf_warning_or_error, NULL_TREE,
8769                                  /*integral_constant_expression_p=*/true);
8770                   finish_static_assert (condition,
8771                                         STATIC_ASSERT_MESSAGE (t), 
8772                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8773                                         /*member_p=*/true);
8774                 }
8775               else if (TREE_CODE (t) != CONST_DECL)
8776                 {
8777                   tree r;
8778
8779                   /* The file and line for this declaration, to
8780                      assist in error message reporting.  Since we
8781                      called push_tinst_level above, we don't need to
8782                      restore these.  */
8783                   input_location = DECL_SOURCE_LOCATION (t);
8784
8785                   if (TREE_CODE (t) == TEMPLATE_DECL)
8786                     ++processing_template_decl;
8787                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8788                   if (TREE_CODE (t) == TEMPLATE_DECL)
8789                     --processing_template_decl;
8790                   if (TREE_CODE (r) == VAR_DECL)
8791                     {
8792                       /* In [temp.inst]:
8793
8794                            [t]he initialization (and any associated
8795                            side-effects) of a static data member does
8796                            not occur unless the static data member is
8797                            itself used in a way that requires the
8798                            definition of the static data member to
8799                            exist.
8800
8801                          Therefore, we do not substitute into the
8802                          initialized for the static data member here.  */
8803                       finish_static_data_member_decl
8804                         (r,
8805                          /*init=*/NULL_TREE,
8806                          /*init_const_expr_p=*/false,
8807                          /*asmspec_tree=*/NULL_TREE,
8808                          /*flags=*/0);
8809                       /* Instantiate members marked with attribute used.  */
8810                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8811                         mark_used (r);
8812                     }
8813                   else if (TREE_CODE (r) == FIELD_DECL)
8814                     {
8815                       /* Determine whether R has a valid type and can be
8816                          completed later.  If R is invalid, then it is
8817                          replaced by error_mark_node so that it will not be
8818                          added to TYPE_FIELDS.  */
8819                       tree rtype = TREE_TYPE (r);
8820                       if (can_complete_type_without_circularity (rtype))
8821                         complete_type (rtype);
8822
8823                       if (!COMPLETE_TYPE_P (rtype))
8824                         {
8825                           cxx_incomplete_type_error (r, rtype);
8826                           r = error_mark_node;
8827                         }
8828                     }
8829
8830                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8831                      such a thing will already have been added to the field
8832                      list by tsubst_enum in finish_member_declaration in the
8833                      CLASSTYPE_NESTED_UTDS case above.  */
8834                   if (!(TREE_CODE (r) == TYPE_DECL
8835                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8836                         && DECL_ARTIFICIAL (r)))
8837                     {
8838                       set_current_access_from_decl (r);
8839                       finish_member_declaration (r);
8840                     }
8841                 }
8842             }
8843         }
8844       else
8845         {
8846           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8847             {
8848               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8849
8850               tree friend_type = t;
8851               bool adjust_processing_template_decl = false;
8852
8853               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8854                 {
8855                   /* template <class T> friend class C;  */
8856                   friend_type = tsubst_friend_class (friend_type, args);
8857                   adjust_processing_template_decl = true;
8858                 }
8859               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8860                 {
8861                   /* template <class T> friend class C::D;  */
8862                   friend_type = tsubst (friend_type, args,
8863                                         tf_warning_or_error, NULL_TREE);
8864                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8865                     friend_type = TREE_TYPE (friend_type);
8866                   adjust_processing_template_decl = true;
8867                 }
8868               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8869                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8870                 {
8871                   /* This could be either
8872
8873                        friend class T::C;
8874
8875                      when dependent_type_p is false or
8876
8877                        template <class U> friend class T::C;
8878
8879                      otherwise.  */
8880                   friend_type = tsubst (friend_type, args,
8881                                         tf_warning_or_error, NULL_TREE);
8882                   /* Bump processing_template_decl for correct
8883                      dependent_type_p calculation.  */
8884                   ++processing_template_decl;
8885                   if (dependent_type_p (friend_type))
8886                     adjust_processing_template_decl = true;
8887                   --processing_template_decl;
8888                 }
8889               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8890                        && hidden_name_p (TYPE_NAME (friend_type)))
8891                 {
8892                   /* friend class C;
8893
8894                      where C hasn't been declared yet.  Let's lookup name
8895                      from namespace scope directly, bypassing any name that
8896                      come from dependent base class.  */
8897                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8898
8899                   /* The call to xref_tag_from_type does injection for friend
8900                      classes.  */
8901                   push_nested_namespace (ns);
8902                   friend_type =
8903                     xref_tag_from_type (friend_type, NULL_TREE,
8904                                         /*tag_scope=*/ts_current);
8905                   pop_nested_namespace (ns);
8906                 }
8907               else if (uses_template_parms (friend_type))
8908                 /* friend class C<T>;  */
8909                 friend_type = tsubst (friend_type, args,
8910                                       tf_warning_or_error, NULL_TREE);
8911               /* Otherwise it's
8912
8913                    friend class C;
8914
8915                  where C is already declared or
8916
8917                    friend class C<int>;
8918
8919                  We don't have to do anything in these cases.  */
8920
8921               if (adjust_processing_template_decl)
8922                 /* Trick make_friend_class into realizing that the friend
8923                    we're adding is a template, not an ordinary class.  It's
8924                    important that we use make_friend_class since it will
8925                    perform some error-checking and output cross-reference
8926                    information.  */
8927                 ++processing_template_decl;
8928
8929               if (friend_type != error_mark_node)
8930                 make_friend_class (type, friend_type, /*complain=*/false);
8931
8932               if (adjust_processing_template_decl)
8933                 --processing_template_decl;
8934             }
8935           else
8936             {
8937               /* Build new DECL_FRIENDLIST.  */
8938               tree r;
8939
8940               /* The file and line for this declaration, to
8941                  assist in error message reporting.  Since we
8942                  called push_tinst_level above, we don't need to
8943                  restore these.  */
8944               input_location = DECL_SOURCE_LOCATION (t);
8945
8946               if (TREE_CODE (t) == TEMPLATE_DECL)
8947                 {
8948                   ++processing_template_decl;
8949                   push_deferring_access_checks (dk_no_check);
8950                 }
8951
8952               r = tsubst_friend_function (t, args);
8953               add_friend (type, r, /*complain=*/false);
8954               if (TREE_CODE (t) == TEMPLATE_DECL)
8955                 {
8956                   pop_deferring_access_checks ();
8957                   --processing_template_decl;
8958                 }
8959             }
8960         }
8961     }
8962
8963   if (CLASSTYPE_LAMBDA_EXPR (type))
8964     {
8965       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8966       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8967         {
8968           apply_lambda_return_type (lambda, void_type_node);
8969           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8970         }
8971       instantiate_decl (lambda_function (type), false, false);
8972       maybe_add_lambda_conv_op (type);
8973     }
8974
8975   /* Set the file and line number information to whatever is given for
8976      the class itself.  This puts error messages involving generated
8977      implicit functions at a predictable point, and the same point
8978      that would be used for non-template classes.  */
8979   input_location = DECL_SOURCE_LOCATION (typedecl);
8980
8981   unreverse_member_declarations (type);
8982   finish_struct_1 (type);
8983   TYPE_BEING_DEFINED (type) = 0;
8984
8985   /* We don't instantiate default arguments for member functions.  14.7.1:
8986
8987      The implicit instantiation of a class template specialization causes
8988      the implicit instantiation of the declarations, but not of the
8989      definitions or default arguments, of the class member functions,
8990      member classes, static data members and member templates....  */
8991
8992   /* Some typedefs referenced from within the template code need to be access
8993      checked at template instantiation time, i.e now. These types were
8994      added to the template at parsing time. Let's get those and perform
8995      the access checks then.  */
8996   perform_typedefs_access_check (pattern, args);
8997   perform_deferred_access_checks ();
8998   pop_nested_class ();
8999   maximum_field_alignment = saved_maximum_field_alignment;
9000   pop_from_top_level ();
9001   pop_deferring_access_checks ();
9002   pop_tinst_level ();
9003
9004   /* The vtable for a template class can be emitted in any translation
9005      unit in which the class is instantiated.  When there is no key
9006      method, however, finish_struct_1 will already have added TYPE to
9007      the keyed_classes list.  */
9008   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9009     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9010
9011   return type;
9012 }
9013
9014 /* Wrapper for instantiate_class_template_1.  */
9015
9016 tree
9017 instantiate_class_template (tree type)
9018 {
9019   tree ret;
9020   timevar_push (TV_TEMPLATE_INST);
9021   ret = instantiate_class_template_1 (type);
9022   timevar_pop (TV_TEMPLATE_INST);
9023   return ret;
9024 }
9025
9026 static tree
9027 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9028 {
9029   tree r;
9030
9031   if (!t)
9032     r = t;
9033   else if (TYPE_P (t))
9034     r = tsubst (t, args, complain, in_decl);
9035   else
9036     {
9037       if (!(complain & tf_warning))
9038         ++c_inhibit_evaluation_warnings;
9039       r = tsubst_expr (t, args, complain, in_decl,
9040                        /*integral_constant_expression_p=*/true);
9041       if (!(complain & tf_warning))
9042         --c_inhibit_evaluation_warnings;
9043       /* Preserve the raw-reference nature of T.  */
9044       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9045           && REFERENCE_REF_P (r))
9046         r = TREE_OPERAND (r, 0);
9047     }
9048   return r;
9049 }
9050
9051 /* Given a function parameter pack TMPL_PARM and some function parameters
9052    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9053    and set *SPEC_P to point at the next point in the list.  */
9054
9055 static tree
9056 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9057 {
9058   /* Collect all of the extra "packed" parameters into an
9059      argument pack.  */
9060   tree parmvec;
9061   tree parmtypevec;
9062   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9063   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9064   tree spec_parm = *spec_p;
9065   int i, len;
9066
9067   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9068     if (tmpl_parm
9069         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9070       break;
9071
9072   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9073   parmvec = make_tree_vec (len);
9074   parmtypevec = make_tree_vec (len);
9075   spec_parm = *spec_p;
9076   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9077     {
9078       TREE_VEC_ELT (parmvec, i) = spec_parm;
9079       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9080     }
9081
9082   /* Build the argument packs.  */
9083   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9084   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9085   TREE_TYPE (argpack) = argtypepack;
9086   *spec_p = spec_parm;
9087
9088   return argpack;
9089 }
9090
9091 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9092    NONTYPE_ARGUMENT_PACK.  */
9093
9094 static tree
9095 make_fnparm_pack (tree spec_parm)
9096 {
9097   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9098 }
9099
9100 /* Substitute ARGS into T, which is an pack expansion
9101    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9102    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9103    (if only a partial substitution could be performed) or
9104    ERROR_MARK_NODE if there was an error.  */
9105 tree
9106 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9107                        tree in_decl)
9108 {
9109   tree pattern;
9110   tree pack, packs = NULL_TREE;
9111   bool unsubstituted_packs = false;
9112   int i, len = -1;
9113   tree result;
9114   htab_t saved_local_specializations = NULL;
9115
9116   gcc_assert (PACK_EXPANSION_P (t));
9117   pattern = PACK_EXPANSION_PATTERN (t);
9118
9119   /* Determine the argument packs that will instantiate the parameter
9120      packs used in the expansion expression. While we're at it,
9121      compute the number of arguments to be expanded and make sure it
9122      is consistent.  */
9123   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9124        pack = TREE_CHAIN (pack))
9125     {
9126       tree parm_pack = TREE_VALUE (pack);
9127       tree arg_pack = NULL_TREE;
9128       tree orig_arg = NULL_TREE;
9129
9130       if (TREE_CODE (parm_pack) == PARM_DECL)
9131         {
9132           if (!cp_unevaluated_operand)
9133             arg_pack = retrieve_local_specialization (parm_pack);
9134           else
9135             {
9136               /* We can't rely on local_specializations for a parameter
9137                  name used later in a function declaration (such as in a
9138                  late-specified return type).  Even if it exists, it might
9139                  have the wrong value for a recursive call.  Just make a
9140                  dummy decl, since it's only used for its type.  */
9141               arg_pack = tsubst_decl (parm_pack, args, complain);
9142               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9143                 /* Partial instantiation of the parm_pack, we can't build
9144                    up an argument pack yet.  */
9145                 arg_pack = NULL_TREE;
9146               else
9147                 arg_pack = make_fnparm_pack (arg_pack);
9148             }
9149         }
9150       else
9151         {
9152           int level, idx, levels;
9153           template_parm_level_and_index (parm_pack, &level, &idx);
9154
9155           levels = TMPL_ARGS_DEPTH (args);
9156           if (level <= levels)
9157             arg_pack = TMPL_ARG (args, level, idx);
9158         }
9159
9160       orig_arg = arg_pack;
9161       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9162         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9163       
9164       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9165         /* This can only happen if we forget to expand an argument
9166            pack somewhere else. Just return an error, silently.  */
9167         {
9168           result = make_tree_vec (1);
9169           TREE_VEC_ELT (result, 0) = error_mark_node;
9170           return result;
9171         }
9172
9173       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9174         /* The argument pack that the parameter maps to is just an
9175            expansion of the parameter itself, such as one would find
9176            in the implicit typedef of a class inside the class itself.
9177            Consider this parameter "unsubstituted", so that we will
9178            maintain the outer pack expansion.  */
9179         arg_pack = NULL_TREE;
9180           
9181       if (arg_pack)
9182         {
9183           int my_len = 
9184             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9185
9186           /* Don't bother trying to do a partial substitution with
9187              incomplete packs; we'll try again after deduction.  */
9188           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9189             return t;
9190
9191           if (len < 0)
9192             len = my_len;
9193           else if (len != my_len)
9194             {
9195               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9196                 error ("mismatched argument pack lengths while expanding "
9197                        "%<%T%>",
9198                        pattern);
9199               else
9200                 error ("mismatched argument pack lengths while expanding "
9201                        "%<%E%>",
9202                        pattern);
9203               return error_mark_node;
9204             }
9205
9206           /* Keep track of the parameter packs and their corresponding
9207              argument packs.  */
9208           packs = tree_cons (parm_pack, arg_pack, packs);
9209           TREE_TYPE (packs) = orig_arg;
9210         }
9211       else
9212         {
9213           /* We can't substitute for this parameter pack.  */
9214           unsubstituted_packs = true;
9215           break;
9216         }
9217     }
9218
9219   /* We cannot expand this expansion expression, because we don't have
9220      all of the argument packs we need. Substitute into the pattern
9221      and return a PACK_EXPANSION_*. The caller will need to deal with
9222      that.  */
9223   if (unsubstituted_packs)
9224     {
9225       tree new_pat;
9226       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9227         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9228                                /*integral_constant_expression_p=*/false);
9229       else
9230         new_pat = tsubst (pattern, args, complain, in_decl);
9231       return make_pack_expansion (new_pat);
9232     }
9233
9234   /* We could not find any argument packs that work.  */
9235   if (len < 0)
9236     return error_mark_node;
9237
9238   if (cp_unevaluated_operand)
9239     {
9240       /* We're in a late-specified return type, so create our own local
9241          specializations table; the current table is either NULL or (in the
9242          case of recursive unification) might have bindings that we don't
9243          want to use or alter.  */
9244       saved_local_specializations = local_specializations;
9245       local_specializations = htab_create (37,
9246                                            hash_local_specialization,
9247                                            eq_local_specializations,
9248                                            NULL);
9249     }
9250
9251   /* For each argument in each argument pack, substitute into the
9252      pattern.  */
9253   result = make_tree_vec (len);
9254   for (i = 0; i < len; ++i)
9255     {
9256       /* For parameter pack, change the substitution of the parameter
9257          pack to the ith argument in its argument pack, then expand
9258          the pattern.  */
9259       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9260         {
9261           tree parm = TREE_PURPOSE (pack);
9262           tree arg;
9263
9264           /* Select the Ith argument from the pack.  */
9265           if (TREE_CODE (parm) == PARM_DECL)
9266             {
9267               if (i == 0)
9268                 {
9269                   arg = make_node (ARGUMENT_PACK_SELECT);
9270                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9271                   mark_used (parm);
9272                   register_local_specialization (arg, parm);
9273                 }
9274               else
9275                 arg = retrieve_local_specialization (parm);
9276             }
9277           else
9278             {
9279               int idx, level;
9280               template_parm_level_and_index (parm, &level, &idx);
9281
9282               if (i == 0)
9283                 {
9284                   arg = make_node (ARGUMENT_PACK_SELECT);
9285                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9286                   /* Update the corresponding argument.  */
9287                   TMPL_ARG (args, level, idx) = arg;
9288                 }
9289               else
9290                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9291                 arg = TMPL_ARG (args, level, idx);
9292             }
9293           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9294         }
9295
9296       /* Substitute into the PATTERN with the altered arguments.  */
9297       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9298         TREE_VEC_ELT (result, i) = 
9299           tsubst_expr (pattern, args, complain, in_decl,
9300                        /*integral_constant_expression_p=*/false);
9301       else
9302         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9303
9304       if (TREE_VEC_ELT (result, i) == error_mark_node)
9305         {
9306           result = error_mark_node;
9307           break;
9308         }
9309     }
9310
9311   /* Update ARGS to restore the substitution from parameter packs to
9312      their argument packs.  */
9313   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9314     {
9315       tree parm = TREE_PURPOSE (pack);
9316
9317       if (TREE_CODE (parm) == PARM_DECL)
9318         register_local_specialization (TREE_TYPE (pack), parm);
9319       else
9320         {
9321           int idx, level;
9322           template_parm_level_and_index (parm, &level, &idx);
9323           
9324           /* Update the corresponding argument.  */
9325           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9326             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9327               TREE_TYPE (pack);
9328           else
9329             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9330         }
9331     }
9332
9333   if (saved_local_specializations)
9334     {
9335       htab_delete (local_specializations);
9336       local_specializations = saved_local_specializations;
9337     }
9338   
9339   return result;
9340 }
9341
9342 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9343    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9344    parameter packs; all parms generated from a function parameter pack will
9345    have the same DECL_PARM_INDEX.  */
9346
9347 tree
9348 get_pattern_parm (tree parm, tree tmpl)
9349 {
9350   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9351   tree patparm;
9352
9353   if (DECL_ARTIFICIAL (parm))
9354     {
9355       for (patparm = DECL_ARGUMENTS (pattern);
9356            patparm; patparm = DECL_CHAIN (patparm))
9357         if (DECL_ARTIFICIAL (patparm)
9358             && DECL_NAME (parm) == DECL_NAME (patparm))
9359           break;
9360     }
9361   else
9362     {
9363       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9364       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9365       gcc_assert (DECL_PARM_INDEX (patparm)
9366                   == DECL_PARM_INDEX (parm));
9367     }
9368
9369   return patparm;
9370 }
9371
9372 /* Substitute ARGS into the vector or list of template arguments T.  */
9373
9374 static tree
9375 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9376 {
9377   tree orig_t = t;
9378   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9379   tree *elts;
9380
9381   if (t == error_mark_node)
9382     return error_mark_node;
9383
9384   len = TREE_VEC_LENGTH (t);
9385   elts = XALLOCAVEC (tree, len);
9386
9387   for (i = 0; i < len; i++)
9388     {
9389       tree orig_arg = TREE_VEC_ELT (t, i);
9390       tree new_arg;
9391
9392       if (TREE_CODE (orig_arg) == TREE_VEC)
9393         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9394       else if (PACK_EXPANSION_P (orig_arg))
9395         {
9396           /* Substitute into an expansion expression.  */
9397           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9398
9399           if (TREE_CODE (new_arg) == TREE_VEC)
9400             /* Add to the expanded length adjustment the number of
9401                expanded arguments. We subtract one from this
9402                measurement, because the argument pack expression
9403                itself is already counted as 1 in
9404                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9405                the argument pack is empty.  */
9406             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9407         }
9408       else if (ARGUMENT_PACK_P (orig_arg))
9409         {
9410           /* Substitute into each of the arguments.  */
9411           new_arg = TYPE_P (orig_arg)
9412             ? cxx_make_type (TREE_CODE (orig_arg))
9413             : make_node (TREE_CODE (orig_arg));
9414           
9415           SET_ARGUMENT_PACK_ARGS (
9416             new_arg,
9417             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9418                                   args, complain, in_decl));
9419
9420           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9421             new_arg = error_mark_node;
9422
9423           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9424             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9425                                           complain, in_decl);
9426             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9427
9428             if (TREE_TYPE (new_arg) == error_mark_node)
9429               new_arg = error_mark_node;
9430           }
9431         }
9432       else
9433         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9434
9435       if (new_arg == error_mark_node)
9436         return error_mark_node;
9437
9438       elts[i] = new_arg;
9439       if (new_arg != orig_arg)
9440         need_new = 1;
9441     }
9442
9443   if (!need_new)
9444     return t;
9445
9446   /* Make space for the expanded arguments coming from template
9447      argument packs.  */
9448   t = make_tree_vec (len + expanded_len_adjust);
9449   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9450      arguments for a member template.
9451      In that case each TREE_VEC in ORIG_T represents a level of template
9452      arguments, and ORIG_T won't carry any non defaulted argument count.
9453      It will rather be the nested TREE_VECs that will carry one.
9454      In other words, ORIG_T carries a non defaulted argument count only
9455      if it doesn't contain any nested TREE_VEC.  */
9456   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9457     {
9458       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9459       count += expanded_len_adjust;
9460       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9461     }
9462   for (i = 0, out = 0; i < len; i++)
9463     {
9464       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9465            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9466           && TREE_CODE (elts[i]) == TREE_VEC)
9467         {
9468           int idx;
9469
9470           /* Now expand the template argument pack "in place".  */
9471           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9472             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9473         }
9474       else
9475         {
9476           TREE_VEC_ELT (t, out) = elts[i];
9477           out++;
9478         }
9479     }
9480
9481   return t;
9482 }
9483
9484 /* Return the result of substituting ARGS into the template parameters
9485    given by PARMS.  If there are m levels of ARGS and m + n levels of
9486    PARMS, then the result will contain n levels of PARMS.  For
9487    example, if PARMS is `template <class T> template <class U>
9488    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9489    result will be `template <int*, double, class V>'.  */
9490
9491 static tree
9492 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9493 {
9494   tree r = NULL_TREE;
9495   tree* new_parms;
9496
9497   /* When substituting into a template, we must set
9498      PROCESSING_TEMPLATE_DECL as the template parameters may be
9499      dependent if they are based on one-another, and the dependency
9500      predicates are short-circuit outside of templates.  */
9501   ++processing_template_decl;
9502
9503   for (new_parms = &r;
9504        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9505        new_parms = &(TREE_CHAIN (*new_parms)),
9506          parms = TREE_CHAIN (parms))
9507     {
9508       tree new_vec =
9509         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9510       int i;
9511
9512       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9513         {
9514           tree tuple;
9515
9516           if (parms == error_mark_node)
9517             continue;
9518
9519           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9520
9521           if (tuple == error_mark_node)
9522             continue;
9523
9524           TREE_VEC_ELT (new_vec, i) =
9525             tsubst_template_parm (tuple, args, complain);
9526         }
9527
9528       *new_parms =
9529         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9530                              - TMPL_ARGS_DEPTH (args)),
9531                    new_vec, NULL_TREE);
9532     }
9533
9534   --processing_template_decl;
9535
9536   return r;
9537 }
9538
9539 /* Return the result of substituting ARGS into one template parameter
9540    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9541    parameter and which TREE_PURPOSE is the default argument of the
9542    template parameter.  */
9543
9544 static tree
9545 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9546 {
9547   tree default_value, parm_decl;
9548
9549   if (args == NULL_TREE
9550       || t == NULL_TREE
9551       || t == error_mark_node)
9552     return t;
9553
9554   gcc_assert (TREE_CODE (t) == TREE_LIST);
9555
9556   default_value = TREE_PURPOSE (t);
9557   parm_decl = TREE_VALUE (t);
9558
9559   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9560   if (TREE_CODE (parm_decl) == PARM_DECL
9561       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9562     parm_decl = error_mark_node;
9563   default_value = tsubst_template_arg (default_value, args,
9564                                        complain, NULL_TREE);
9565
9566   return build_tree_list (default_value, parm_decl);
9567 }
9568
9569 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9570    type T.  If T is not an aggregate or enumeration type, it is
9571    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9572    ENTERING_SCOPE is nonzero, T is the context for a template which
9573    we are presently tsubst'ing.  Return the substituted value.  */
9574
9575 static tree
9576 tsubst_aggr_type (tree t,
9577                   tree args,
9578                   tsubst_flags_t complain,
9579                   tree in_decl,
9580                   int entering_scope)
9581 {
9582   if (t == NULL_TREE)
9583     return NULL_TREE;
9584
9585   switch (TREE_CODE (t))
9586     {
9587     case RECORD_TYPE:
9588       if (TYPE_PTRMEMFUNC_P (t))
9589         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9590
9591       /* Else fall through.  */
9592     case ENUMERAL_TYPE:
9593     case UNION_TYPE:
9594       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9595         {
9596           tree argvec;
9597           tree context;
9598           tree r;
9599           int saved_unevaluated_operand;
9600           int saved_inhibit_evaluation_warnings;
9601
9602           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9603           saved_unevaluated_operand = cp_unevaluated_operand;
9604           cp_unevaluated_operand = 0;
9605           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9606           c_inhibit_evaluation_warnings = 0;
9607
9608           /* First, determine the context for the type we are looking
9609              up.  */
9610           context = TYPE_CONTEXT (t);
9611           if (context && TYPE_P (context))
9612             {
9613               context = tsubst_aggr_type (context, args, complain,
9614                                           in_decl, /*entering_scope=*/1);
9615               /* If context is a nested class inside a class template,
9616                  it may still need to be instantiated (c++/33959).  */
9617               context = complete_type (context);
9618             }
9619
9620           /* Then, figure out what arguments are appropriate for the
9621              type we are trying to find.  For example, given:
9622
9623                template <class T> struct S;
9624                template <class T, class U> void f(T, U) { S<U> su; }
9625
9626              and supposing that we are instantiating f<int, double>,
9627              then our ARGS will be {int, double}, but, when looking up
9628              S we only want {double}.  */
9629           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9630                                          complain, in_decl);
9631           if (argvec == error_mark_node)
9632             r = error_mark_node;
9633           else
9634             {
9635               r = lookup_template_class (t, argvec, in_decl, context,
9636                                          entering_scope, complain);
9637               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9638             }
9639
9640           cp_unevaluated_operand = saved_unevaluated_operand;
9641           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9642
9643           return r;
9644         }
9645       else
9646         /* This is not a template type, so there's nothing to do.  */
9647         return t;
9648
9649     default:
9650       return tsubst (t, args, complain, in_decl);
9651     }
9652 }
9653
9654 /* Substitute into the default argument ARG (a default argument for
9655    FN), which has the indicated TYPE.  */
9656
9657 tree
9658 tsubst_default_argument (tree fn, tree type, tree arg)
9659 {
9660   tree saved_class_ptr = NULL_TREE;
9661   tree saved_class_ref = NULL_TREE;
9662
9663   /* This can happen in invalid code.  */
9664   if (TREE_CODE (arg) == DEFAULT_ARG)
9665     return arg;
9666
9667   /* This default argument came from a template.  Instantiate the
9668      default argument here, not in tsubst.  In the case of
9669      something like:
9670
9671        template <class T>
9672        struct S {
9673          static T t();
9674          void f(T = t());
9675        };
9676
9677      we must be careful to do name lookup in the scope of S<T>,
9678      rather than in the current class.  */
9679   push_access_scope (fn);
9680   /* The "this" pointer is not valid in a default argument.  */
9681   if (cfun)
9682     {
9683       saved_class_ptr = current_class_ptr;
9684       cp_function_chain->x_current_class_ptr = NULL_TREE;
9685       saved_class_ref = current_class_ref;
9686       cp_function_chain->x_current_class_ref = NULL_TREE;
9687     }
9688
9689   push_deferring_access_checks(dk_no_deferred);
9690   /* The default argument expression may cause implicitly defined
9691      member functions to be synthesized, which will result in garbage
9692      collection.  We must treat this situation as if we were within
9693      the body of function so as to avoid collecting live data on the
9694      stack.  */
9695   ++function_depth;
9696   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9697                      tf_warning_or_error, NULL_TREE,
9698                      /*integral_constant_expression_p=*/false);
9699   --function_depth;
9700   pop_deferring_access_checks();
9701
9702   /* Restore the "this" pointer.  */
9703   if (cfun)
9704     {
9705       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9706       cp_function_chain->x_current_class_ref = saved_class_ref;
9707     }
9708
9709   /* Make sure the default argument is reasonable.  */
9710   arg = check_default_argument (type, arg);
9711
9712   pop_access_scope (fn);
9713
9714   return arg;
9715 }
9716
9717 /* Substitute into all the default arguments for FN.  */
9718
9719 static void
9720 tsubst_default_arguments (tree fn)
9721 {
9722   tree arg;
9723   tree tmpl_args;
9724
9725   tmpl_args = DECL_TI_ARGS (fn);
9726
9727   /* If this function is not yet instantiated, we certainly don't need
9728      its default arguments.  */
9729   if (uses_template_parms (tmpl_args))
9730     return;
9731   /* Don't do this again for clones.  */
9732   if (DECL_CLONED_FUNCTION_P (fn))
9733     return;
9734
9735   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9736        arg;
9737        arg = TREE_CHAIN (arg))
9738     if (TREE_PURPOSE (arg))
9739       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9740                                                     TREE_VALUE (arg),
9741                                                     TREE_PURPOSE (arg));
9742 }
9743
9744 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9745    result of the substitution.  Issue error and warning messages under
9746    control of COMPLAIN.  */
9747
9748 static tree
9749 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9750 {
9751 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9752   location_t saved_loc;
9753   tree r = NULL_TREE;
9754   tree in_decl = t;
9755   hashval_t hash = 0;
9756
9757   /* Set the filename and linenumber to improve error-reporting.  */
9758   saved_loc = input_location;
9759   input_location = DECL_SOURCE_LOCATION (t);
9760
9761   switch (TREE_CODE (t))
9762     {
9763     case TEMPLATE_DECL:
9764       {
9765         /* We can get here when processing a member function template,
9766            member class template, or template template parameter.  */
9767         tree decl = DECL_TEMPLATE_RESULT (t);
9768         tree spec;
9769         tree tmpl_args;
9770         tree full_args;
9771
9772         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9773           {
9774             /* Template template parameter is treated here.  */
9775             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9776             if (new_type == error_mark_node)
9777               RETURN (error_mark_node);
9778
9779             r = copy_decl (t);
9780             DECL_CHAIN (r) = NULL_TREE;
9781             TREE_TYPE (r) = new_type;
9782             DECL_TEMPLATE_RESULT (r)
9783               = build_decl (DECL_SOURCE_LOCATION (decl),
9784                             TYPE_DECL, DECL_NAME (decl), new_type);
9785             DECL_TEMPLATE_PARMS (r)
9786               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9787                                        complain);
9788             TYPE_NAME (new_type) = r;
9789             break;
9790           }
9791
9792         /* We might already have an instance of this template.
9793            The ARGS are for the surrounding class type, so the
9794            full args contain the tsubst'd args for the context,
9795            plus the innermost args from the template decl.  */
9796         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9797           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9798           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9799         /* Because this is a template, the arguments will still be
9800            dependent, even after substitution.  If
9801            PROCESSING_TEMPLATE_DECL is not set, the dependency
9802            predicates will short-circuit.  */
9803         ++processing_template_decl;
9804         full_args = tsubst_template_args (tmpl_args, args,
9805                                           complain, in_decl);
9806         --processing_template_decl;
9807         if (full_args == error_mark_node)
9808           RETURN (error_mark_node);
9809
9810         /* If this is a default template template argument,
9811            tsubst might not have changed anything.  */
9812         if (full_args == tmpl_args)
9813           RETURN (t);
9814
9815         hash = hash_tmpl_and_args (t, full_args);
9816         spec = retrieve_specialization (t, full_args, hash);
9817         if (spec != NULL_TREE)
9818           {
9819             r = spec;
9820             break;
9821           }
9822
9823         /* Make a new template decl.  It will be similar to the
9824            original, but will record the current template arguments.
9825            We also create a new function declaration, which is just
9826            like the old one, but points to this new template, rather
9827            than the old one.  */
9828         r = copy_decl (t);
9829         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9830         DECL_CHAIN (r) = NULL_TREE;
9831
9832         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9833
9834         if (TREE_CODE (decl) == TYPE_DECL)
9835           {
9836             tree new_type;
9837             ++processing_template_decl;
9838             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9839             --processing_template_decl;
9840             if (new_type == error_mark_node)
9841               RETURN (error_mark_node);
9842
9843             TREE_TYPE (r) = new_type;
9844             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9845             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9846             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9847             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9848           }
9849         else
9850           {
9851             tree new_decl;
9852             ++processing_template_decl;
9853             new_decl = tsubst (decl, args, complain, in_decl);
9854             --processing_template_decl;
9855             if (new_decl == error_mark_node)
9856               RETURN (error_mark_node);
9857
9858             DECL_TEMPLATE_RESULT (r) = new_decl;
9859             DECL_TI_TEMPLATE (new_decl) = r;
9860             TREE_TYPE (r) = TREE_TYPE (new_decl);
9861             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9862             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9863           }
9864
9865         SET_DECL_IMPLICIT_INSTANTIATION (r);
9866         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9867         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9868
9869         /* The template parameters for this new template are all the
9870            template parameters for the old template, except the
9871            outermost level of parameters.  */
9872         DECL_TEMPLATE_PARMS (r)
9873           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9874                                    complain);
9875
9876         if (PRIMARY_TEMPLATE_P (t))
9877           DECL_PRIMARY_TEMPLATE (r) = r;
9878
9879         if (TREE_CODE (decl) != TYPE_DECL)
9880           /* Record this non-type partial instantiation.  */
9881           register_specialization (r, t,
9882                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9883                                    false, hash);
9884       }
9885       break;
9886
9887     case FUNCTION_DECL:
9888       {
9889         tree ctx;
9890         tree argvec = NULL_TREE;
9891         tree *friends;
9892         tree gen_tmpl;
9893         tree type;
9894         int member;
9895         int args_depth;
9896         int parms_depth;
9897
9898         /* Nobody should be tsubst'ing into non-template functions.  */
9899         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9900
9901         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9902           {
9903             tree spec;
9904             bool dependent_p;
9905
9906             /* If T is not dependent, just return it.  We have to
9907                increment PROCESSING_TEMPLATE_DECL because
9908                value_dependent_expression_p assumes that nothing is
9909                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9910             ++processing_template_decl;
9911             dependent_p = value_dependent_expression_p (t);
9912             --processing_template_decl;
9913             if (!dependent_p)
9914               RETURN (t);
9915
9916             /* Calculate the most general template of which R is a
9917                specialization, and the complete set of arguments used to
9918                specialize R.  */
9919             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9920             argvec = tsubst_template_args (DECL_TI_ARGS
9921                                           (DECL_TEMPLATE_RESULT
9922                                                  (DECL_TI_TEMPLATE (t))),
9923                                            args, complain, in_decl);
9924             if (argvec == error_mark_node)
9925               RETURN (error_mark_node);
9926
9927             /* Check to see if we already have this specialization.  */
9928             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9929             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9930
9931             if (spec)
9932               {
9933                 r = spec;
9934                 break;
9935               }
9936
9937             /* We can see more levels of arguments than parameters if
9938                there was a specialization of a member template, like
9939                this:
9940
9941                  template <class T> struct S { template <class U> void f(); }
9942                  template <> template <class U> void S<int>::f(U);
9943
9944                Here, we'll be substituting into the specialization,
9945                because that's where we can find the code we actually
9946                want to generate, but we'll have enough arguments for
9947                the most general template.
9948
9949                We also deal with the peculiar case:
9950
9951                  template <class T> struct S {
9952                    template <class U> friend void f();
9953                  };
9954                  template <class U> void f() {}
9955                  template S<int>;
9956                  template void f<double>();
9957
9958                Here, the ARGS for the instantiation of will be {int,
9959                double}.  But, we only need as many ARGS as there are
9960                levels of template parameters in CODE_PATTERN.  We are
9961                careful not to get fooled into reducing the ARGS in
9962                situations like:
9963
9964                  template <class T> struct S { template <class U> void f(U); }
9965                  template <class T> template <> void S<T>::f(int) {}
9966
9967                which we can spot because the pattern will be a
9968                specialization in this case.  */
9969             args_depth = TMPL_ARGS_DEPTH (args);
9970             parms_depth =
9971               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9972             if (args_depth > parms_depth
9973                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9974               args = get_innermost_template_args (args, parms_depth);
9975           }
9976         else
9977           {
9978             /* This special case arises when we have something like this:
9979
9980                  template <class T> struct S {
9981                    friend void f<int>(int, double);
9982                  };
9983
9984                Here, the DECL_TI_TEMPLATE for the friend declaration
9985                will be an IDENTIFIER_NODE.  We are being called from
9986                tsubst_friend_function, and we want only to create a
9987                new decl (R) with appropriate types so that we can call
9988                determine_specialization.  */
9989             gen_tmpl = NULL_TREE;
9990           }
9991
9992         if (DECL_CLASS_SCOPE_P (t))
9993           {
9994             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9995               member = 2;
9996             else
9997               member = 1;
9998             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9999                                     complain, t, /*entering_scope=*/1);
10000           }
10001         else
10002           {
10003             member = 0;
10004             ctx = DECL_CONTEXT (t);
10005           }
10006         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10007         if (type == error_mark_node)
10008           RETURN (error_mark_node);
10009
10010         /* We do NOT check for matching decls pushed separately at this
10011            point, as they may not represent instantiations of this
10012            template, and in any case are considered separate under the
10013            discrete model.  */
10014         r = copy_decl (t);
10015         DECL_USE_TEMPLATE (r) = 0;
10016         TREE_TYPE (r) = type;
10017         /* Clear out the mangled name and RTL for the instantiation.  */
10018         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10019         SET_DECL_RTL (r, NULL);
10020         /* Leave DECL_INITIAL set on deleted instantiations.  */
10021         if (!DECL_DELETED_FN (r))
10022           DECL_INITIAL (r) = NULL_TREE;
10023         DECL_CONTEXT (r) = ctx;
10024
10025         if (member && DECL_CONV_FN_P (r))
10026           /* Type-conversion operator.  Reconstruct the name, in
10027              case it's the name of one of the template's parameters.  */
10028           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10029
10030         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10031                                      complain, t);
10032         DECL_RESULT (r) = NULL_TREE;
10033
10034         TREE_STATIC (r) = 0;
10035         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10036         DECL_EXTERNAL (r) = 1;
10037         /* If this is an instantiation of a function with internal
10038            linkage, we already know what object file linkage will be
10039            assigned to the instantiation.  */
10040         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10041         DECL_DEFER_OUTPUT (r) = 0;
10042         DECL_CHAIN (r) = NULL_TREE;
10043         DECL_PENDING_INLINE_INFO (r) = 0;
10044         DECL_PENDING_INLINE_P (r) = 0;
10045         DECL_SAVED_TREE (r) = NULL_TREE;
10046         DECL_STRUCT_FUNCTION (r) = NULL;
10047         TREE_USED (r) = 0;
10048         /* We'll re-clone as appropriate in instantiate_template.  */
10049         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10050
10051         /* If we aren't complaining now, return on error before we register
10052            the specialization so that we'll complain eventually.  */
10053         if ((complain & tf_error) == 0
10054             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10055             && !grok_op_properties (r, /*complain=*/false))
10056           RETURN (error_mark_node);
10057
10058         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10059            this in the special friend case mentioned above where
10060            GEN_TMPL is NULL.  */
10061         if (gen_tmpl)
10062           {
10063             DECL_TEMPLATE_INFO (r)
10064               = build_template_info (gen_tmpl, argvec);
10065             SET_DECL_IMPLICIT_INSTANTIATION (r);
10066             register_specialization (r, gen_tmpl, argvec, false, hash);
10067
10068             /* We're not supposed to instantiate default arguments
10069                until they are called, for a template.  But, for a
10070                declaration like:
10071
10072                  template <class T> void f ()
10073                  { extern void g(int i = T()); }
10074
10075                we should do the substitution when the template is
10076                instantiated.  We handle the member function case in
10077                instantiate_class_template since the default arguments
10078                might refer to other members of the class.  */
10079             if (!member
10080                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10081                 && !uses_template_parms (argvec))
10082               tsubst_default_arguments (r);
10083           }
10084         else
10085           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10086
10087         /* Copy the list of befriending classes.  */
10088         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10089              *friends;
10090              friends = &TREE_CHAIN (*friends))
10091           {
10092             *friends = copy_node (*friends);
10093             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10094                                             args, complain,
10095                                             in_decl);
10096           }
10097
10098         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10099           {
10100             maybe_retrofit_in_chrg (r);
10101             if (DECL_CONSTRUCTOR_P (r))
10102               grok_ctor_properties (ctx, r);
10103             /* If this is an instantiation of a member template, clone it.
10104                If it isn't, that'll be handled by
10105                clone_constructors_and_destructors.  */
10106             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10107               clone_function_decl (r, /*update_method_vec_p=*/0);
10108           }
10109         else if ((complain & tf_error) != 0
10110                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10111                  && !grok_op_properties (r, /*complain=*/true))
10112           RETURN (error_mark_node);
10113
10114         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10115           SET_DECL_FRIEND_CONTEXT (r,
10116                                    tsubst (DECL_FRIEND_CONTEXT (t),
10117                                             args, complain, in_decl));
10118
10119         /* Possibly limit visibility based on template args.  */
10120         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10121         if (DECL_VISIBILITY_SPECIFIED (t))
10122           {
10123             DECL_VISIBILITY_SPECIFIED (r) = 0;
10124             DECL_ATTRIBUTES (r)
10125               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10126           }
10127         determine_visibility (r);
10128         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10129             && !processing_template_decl)
10130           defaulted_late_check (r);
10131
10132         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10133                                         args, complain, in_decl);
10134       }
10135       break;
10136
10137     case PARM_DECL:
10138       {
10139         tree type = NULL_TREE;
10140         int i, len = 1;
10141         tree expanded_types = NULL_TREE;
10142         tree prev_r = NULL_TREE;
10143         tree first_r = NULL_TREE;
10144
10145         if (FUNCTION_PARAMETER_PACK_P (t))
10146           {
10147             /* If there is a local specialization that isn't a
10148                parameter pack, it means that we're doing a "simple"
10149                substitution from inside tsubst_pack_expansion. Just
10150                return the local specialization (which will be a single
10151                parm).  */
10152             tree spec = retrieve_local_specialization (t);
10153             if (spec 
10154                 && TREE_CODE (spec) == PARM_DECL
10155                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10156               RETURN (spec);
10157
10158             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10159                the parameters in this function parameter pack.  */
10160             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10161                                                     complain, in_decl);
10162             if (TREE_CODE (expanded_types) == TREE_VEC)
10163               {
10164                 len = TREE_VEC_LENGTH (expanded_types);
10165
10166                 /* Zero-length parameter packs are boring. Just substitute
10167                    into the chain.  */
10168                 if (len == 0)
10169                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10170                                   TREE_CHAIN (t)));
10171               }
10172             else
10173               {
10174                 /* All we did was update the type. Make a note of that.  */
10175                 type = expanded_types;
10176                 expanded_types = NULL_TREE;
10177               }
10178           }
10179
10180         /* Loop through all of the parameter's we'll build. When T is
10181            a function parameter pack, LEN is the number of expanded
10182            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10183         r = NULL_TREE;
10184         for (i = 0; i < len; ++i)
10185           {
10186             prev_r = r;
10187             r = copy_node (t);
10188             if (DECL_TEMPLATE_PARM_P (t))
10189               SET_DECL_TEMPLATE_PARM_P (r);
10190
10191             if (expanded_types)
10192               /* We're on the Ith parameter of the function parameter
10193                  pack.  */
10194               {
10195                 /* An argument of a function parameter pack is not a parameter
10196                    pack.  */
10197                 FUNCTION_PARAMETER_PACK_P (r) = false;
10198
10199                 /* Get the Ith type.  */
10200                 type = TREE_VEC_ELT (expanded_types, i);
10201
10202                 if (DECL_NAME (r))
10203                   /* Rename the parameter to include the index.  */
10204                   DECL_NAME (r) =
10205                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10206               }
10207             else if (!type)
10208               /* We're dealing with a normal parameter.  */
10209               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10210
10211             type = type_decays_to (type);
10212             TREE_TYPE (r) = type;
10213             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10214
10215             if (DECL_INITIAL (r))
10216               {
10217                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10218                   DECL_INITIAL (r) = TREE_TYPE (r);
10219                 else
10220                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10221                                              complain, in_decl);
10222               }
10223
10224             DECL_CONTEXT (r) = NULL_TREE;
10225
10226             if (!DECL_TEMPLATE_PARM_P (r))
10227               DECL_ARG_TYPE (r) = type_passed_as (type);
10228
10229             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10230                                             args, complain, in_decl);
10231
10232             /* Keep track of the first new parameter we
10233                generate. That's what will be returned to the
10234                caller.  */
10235             if (!first_r)
10236               first_r = r;
10237
10238             /* Build a proper chain of parameters when substituting
10239                into a function parameter pack.  */
10240             if (prev_r)
10241               DECL_CHAIN (prev_r) = r;
10242           }
10243
10244         if (DECL_CHAIN (t))
10245           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10246                                    complain, DECL_CHAIN (t));
10247
10248         /* FIRST_R contains the start of the chain we've built.  */
10249         r = first_r;
10250       }
10251       break;
10252
10253     case FIELD_DECL:
10254       {
10255         tree type;
10256
10257         r = copy_decl (t);
10258         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10259         if (type == error_mark_node)
10260           RETURN (error_mark_node);
10261         TREE_TYPE (r) = type;
10262         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10263
10264         if (DECL_C_BIT_FIELD (r))
10265           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10266              non-bit-fields DECL_INITIAL is a non-static data member
10267              initializer, which gets deferred instantiation.  */
10268           DECL_INITIAL (r)
10269             = tsubst_expr (DECL_INITIAL (t), args,
10270                            complain, in_decl,
10271                            /*integral_constant_expression_p=*/true);
10272         /* We don't have to set DECL_CONTEXT here; it is set by
10273            finish_member_declaration.  */
10274         DECL_CHAIN (r) = NULL_TREE;
10275         if (VOID_TYPE_P (type))
10276           error ("instantiation of %q+D as type %qT", r, type);
10277
10278         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10279                                         args, complain, in_decl);
10280       }
10281       break;
10282
10283     case USING_DECL:
10284       /* We reach here only for member using decls.  */
10285       if (DECL_DEPENDENT_P (t))
10286         {
10287           r = do_class_using_decl
10288             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10289              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10290           if (!r)
10291             r = error_mark_node;
10292           else
10293             {
10294               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10295               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10296             }
10297         }
10298       else
10299         {
10300           r = copy_node (t);
10301           DECL_CHAIN (r) = NULL_TREE;
10302         }
10303       break;
10304
10305     case TYPE_DECL:
10306     case VAR_DECL:
10307       {
10308         tree argvec = NULL_TREE;
10309         tree gen_tmpl = NULL_TREE;
10310         tree spec;
10311         tree tmpl = NULL_TREE;
10312         tree ctx;
10313         tree type = NULL_TREE;
10314         bool local_p;
10315
10316         if (TREE_CODE (t) == TYPE_DECL
10317             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10318           {
10319             /* If this is the canonical decl, we don't have to
10320                mess with instantiations, and often we can't (for
10321                typename, template type parms and such).  Note that
10322                TYPE_NAME is not correct for the above test if
10323                we've copied the type for a typedef.  */
10324             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10325             if (type == error_mark_node)
10326               RETURN (error_mark_node);
10327             r = TYPE_NAME (type);
10328             break;
10329           }
10330
10331         /* Check to see if we already have the specialization we
10332            need.  */
10333         spec = NULL_TREE;
10334         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10335           {
10336             /* T is a static data member or namespace-scope entity.
10337                We have to substitute into namespace-scope variables
10338                (even though such entities are never templates) because
10339                of cases like:
10340                
10341                  template <class T> void f() { extern T t; }
10342
10343                where the entity referenced is not known until
10344                instantiation time.  */
10345             local_p = false;
10346             ctx = DECL_CONTEXT (t);
10347             if (DECL_CLASS_SCOPE_P (t))
10348               {
10349                 ctx = tsubst_aggr_type (ctx, args,
10350                                         complain,
10351                                         in_decl, /*entering_scope=*/1);
10352                 /* If CTX is unchanged, then T is in fact the
10353                    specialization we want.  That situation occurs when
10354                    referencing a static data member within in its own
10355                    class.  We can use pointer equality, rather than
10356                    same_type_p, because DECL_CONTEXT is always
10357                    canonical.  */
10358                 if (ctx == DECL_CONTEXT (t))
10359                   spec = t;
10360               }
10361
10362             if (!spec)
10363               {
10364                 tmpl = DECL_TI_TEMPLATE (t);
10365                 gen_tmpl = most_general_template (tmpl);
10366                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10367                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10368                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10369               }
10370           }
10371         else
10372           {
10373             /* A local variable.  */
10374             local_p = true;
10375             /* Subsequent calls to pushdecl will fill this in.  */
10376             ctx = NULL_TREE;
10377             spec = retrieve_local_specialization (t);
10378           }
10379         /* If we already have the specialization we need, there is
10380            nothing more to do.  */ 
10381         if (spec)
10382           {
10383             r = spec;
10384             break;
10385           }
10386
10387         /* Create a new node for the specialization we need.  */
10388         r = copy_decl (t);
10389         if (type == NULL_TREE)
10390           {
10391             if (is_typedef_decl (t))
10392               type = DECL_ORIGINAL_TYPE (t);
10393             else
10394               type = TREE_TYPE (t);
10395             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10396               type = strip_array_domain (type);
10397             type = tsubst (type, args, complain, in_decl);
10398           }
10399         if (TREE_CODE (r) == VAR_DECL)
10400           {
10401             /* Even if the original location is out of scope, the
10402                newly substituted one is not.  */
10403             DECL_DEAD_FOR_LOCAL (r) = 0;
10404             DECL_INITIALIZED_P (r) = 0;
10405             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10406             if (type == error_mark_node)
10407               RETURN (error_mark_node);
10408             if (TREE_CODE (type) == FUNCTION_TYPE)
10409               {
10410                 /* It may seem that this case cannot occur, since:
10411
10412                      typedef void f();
10413                      void g() { f x; }
10414
10415                    declares a function, not a variable.  However:
10416       
10417                      typedef void f();
10418                      template <typename T> void g() { T t; }
10419                      template void g<f>();
10420
10421                    is an attempt to declare a variable with function
10422                    type.  */
10423                 error ("variable %qD has function type",
10424                        /* R is not yet sufficiently initialized, so we
10425                           just use its name.  */
10426                        DECL_NAME (r));
10427                 RETURN (error_mark_node);
10428               }
10429             type = complete_type (type);
10430             /* Wait until cp_finish_decl to set this again, to handle
10431                circular dependency (template/instantiate6.C). */
10432             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10433             type = check_var_type (DECL_NAME (r), type);
10434
10435             if (DECL_HAS_VALUE_EXPR_P (t))
10436               {
10437                 tree ve = DECL_VALUE_EXPR (t);
10438                 ve = tsubst_expr (ve, args, complain, in_decl,
10439                                   /*constant_expression_p=*/false);
10440                 if (REFERENCE_REF_P (ve))
10441                   {
10442                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10443                     ve = TREE_OPERAND (ve, 0);
10444                   }
10445                 SET_DECL_VALUE_EXPR (r, ve);
10446               }
10447           }
10448         else if (DECL_SELF_REFERENCE_P (t))
10449           SET_DECL_SELF_REFERENCE_P (r);
10450         TREE_TYPE (r) = type;
10451         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10452         DECL_CONTEXT (r) = ctx;
10453         /* Clear out the mangled name and RTL for the instantiation.  */
10454         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10455         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10456           SET_DECL_RTL (r, NULL);
10457         /* The initializer must not be expanded until it is required;
10458            see [temp.inst].  */
10459         DECL_INITIAL (r) = NULL_TREE;
10460         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10461           SET_DECL_RTL (r, NULL);
10462         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10463         if (TREE_CODE (r) == VAR_DECL)
10464           {
10465             /* Possibly limit visibility based on template args.  */
10466             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10467             if (DECL_VISIBILITY_SPECIFIED (t))
10468               {
10469                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10470                 DECL_ATTRIBUTES (r)
10471                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10472               }
10473             determine_visibility (r);
10474           }
10475
10476         if (!local_p)
10477           {
10478             /* A static data member declaration is always marked
10479                external when it is declared in-class, even if an
10480                initializer is present.  We mimic the non-template
10481                processing here.  */
10482             DECL_EXTERNAL (r) = 1;
10483
10484             register_specialization (r, gen_tmpl, argvec, false, hash);
10485             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10486             SET_DECL_IMPLICIT_INSTANTIATION (r);
10487           }
10488         else if (cp_unevaluated_operand)
10489           {
10490             /* We're substituting this var in a decltype outside of its
10491                scope, such as for a lambda return type.  Don't add it to
10492                local_specializations, do perform auto deduction.  */
10493             tree auto_node = type_uses_auto (type);
10494             if (auto_node)
10495               {
10496                 tree init
10497                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10498                                  /*constant_expression_p=*/false);
10499                 init = resolve_nondeduced_context (init);
10500                 TREE_TYPE (r) = type
10501                   = do_auto_deduction (type, init, auto_node);
10502               }
10503           }
10504         else
10505           register_local_specialization (r, t);
10506
10507         DECL_CHAIN (r) = NULL_TREE;
10508
10509         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10510                                         /*flags=*/0,
10511                                         args, complain, in_decl);
10512
10513         /* Preserve a typedef that names a type.  */
10514         if (is_typedef_decl (r))
10515           {
10516             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10517             set_underlying_type (r);
10518           }
10519
10520         layout_decl (r, 0);
10521       }
10522       break;
10523
10524     default:
10525       gcc_unreachable ();
10526     }
10527 #undef RETURN
10528
10529  out:
10530   /* Restore the file and line information.  */
10531   input_location = saved_loc;
10532
10533   return r;
10534 }
10535
10536 /* Substitute into the ARG_TYPES of a function type.  */
10537
10538 static tree
10539 tsubst_arg_types (tree arg_types,
10540                   tree args,
10541                   tsubst_flags_t complain,
10542                   tree in_decl)
10543 {
10544   tree remaining_arg_types;
10545   tree type = NULL_TREE;
10546   int i = 1;
10547   tree expanded_args = NULL_TREE;
10548   tree default_arg;
10549
10550   if (!arg_types || arg_types == void_list_node)
10551     return arg_types;
10552
10553   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10554                                           args, complain, in_decl);
10555   if (remaining_arg_types == error_mark_node)
10556     return error_mark_node;
10557
10558   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10559     {
10560       /* For a pack expansion, perform substitution on the
10561          entire expression. Later on, we'll handle the arguments
10562          one-by-one.  */
10563       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10564                                             args, complain, in_decl);
10565
10566       if (TREE_CODE (expanded_args) == TREE_VEC)
10567         /* So that we'll spin through the parameters, one by one.  */
10568         i = TREE_VEC_LENGTH (expanded_args);
10569       else
10570         {
10571           /* We only partially substituted into the parameter
10572              pack. Our type is TYPE_PACK_EXPANSION.  */
10573           type = expanded_args;
10574           expanded_args = NULL_TREE;
10575         }
10576     }
10577
10578   while (i > 0) {
10579     --i;
10580     
10581     if (expanded_args)
10582       type = TREE_VEC_ELT (expanded_args, i);
10583     else if (!type)
10584       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10585
10586     if (type == error_mark_node)
10587       return error_mark_node;
10588     if (VOID_TYPE_P (type))
10589       {
10590         if (complain & tf_error)
10591           {
10592             error ("invalid parameter type %qT", type);
10593             if (in_decl)
10594               error ("in declaration %q+D", in_decl);
10595           }
10596         return error_mark_node;
10597     }
10598     
10599     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10600        top-level qualifiers as required.  */
10601     type = cv_unqualified (type_decays_to (type));
10602
10603     /* We do not substitute into default arguments here.  The standard
10604        mandates that they be instantiated only when needed, which is
10605        done in build_over_call.  */
10606     default_arg = TREE_PURPOSE (arg_types);
10607
10608     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10609       {
10610         /* We've instantiated a template before its default arguments
10611            have been parsed.  This can happen for a nested template
10612            class, and is not an error unless we require the default
10613            argument in a call of this function.  */
10614         remaining_arg_types = 
10615           tree_cons (default_arg, type, remaining_arg_types);
10616         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10617                        remaining_arg_types);
10618       }
10619     else
10620       remaining_arg_types = 
10621         hash_tree_cons (default_arg, type, remaining_arg_types);
10622   }
10623         
10624   return remaining_arg_types;
10625 }
10626
10627 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10628    *not* handle the exception-specification for FNTYPE, because the
10629    initial substitution of explicitly provided template parameters
10630    during argument deduction forbids substitution into the
10631    exception-specification:
10632
10633      [temp.deduct]
10634
10635      All references in the function type of the function template to  the
10636      corresponding template parameters are replaced by the specified tem-
10637      plate argument values.  If a substitution in a template parameter or
10638      in  the function type of the function template results in an invalid
10639      type, type deduction fails.  [Note: The equivalent  substitution  in
10640      exception specifications is done only when the function is instanti-
10641      ated, at which point a program is  ill-formed  if  the  substitution
10642      results in an invalid type.]  */
10643
10644 static tree
10645 tsubst_function_type (tree t,
10646                       tree args,
10647                       tsubst_flags_t complain,
10648                       tree in_decl)
10649 {
10650   tree return_type;
10651   tree arg_types;
10652   tree fntype;
10653
10654   /* The TYPE_CONTEXT is not used for function/method types.  */
10655   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10656
10657   /* Substitute the return type.  */
10658   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10659   if (return_type == error_mark_node)
10660     return error_mark_node;
10661   /* The standard does not presently indicate that creation of a
10662      function type with an invalid return type is a deduction failure.
10663      However, that is clearly analogous to creating an array of "void"
10664      or a reference to a reference.  This is core issue #486.  */
10665   if (TREE_CODE (return_type) == ARRAY_TYPE
10666       || TREE_CODE (return_type) == FUNCTION_TYPE)
10667     {
10668       if (complain & tf_error)
10669         {
10670           if (TREE_CODE (return_type) == ARRAY_TYPE)
10671             error ("function returning an array");
10672           else
10673             error ("function returning a function");
10674         }
10675       return error_mark_node;
10676     }
10677
10678   /* Substitute the argument types.  */
10679   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10680                                 complain, in_decl);
10681   if (arg_types == error_mark_node)
10682     return error_mark_node;
10683
10684   /* Construct a new type node and return it.  */
10685   if (TREE_CODE (t) == FUNCTION_TYPE)
10686     {
10687       fntype = build_function_type (return_type, arg_types);
10688       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10689     }
10690   else
10691     {
10692       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10693       if (! MAYBE_CLASS_TYPE_P (r))
10694         {
10695           /* [temp.deduct]
10696
10697              Type deduction may fail for any of the following
10698              reasons:
10699
10700              -- Attempting to create "pointer to member of T" when T
10701              is not a class type.  */
10702           if (complain & tf_error)
10703             error ("creating pointer to member function of non-class type %qT",
10704                       r);
10705           return error_mark_node;
10706         }
10707
10708       fntype = build_method_type_directly (r, return_type,
10709                                            TREE_CHAIN (arg_types));
10710     }
10711   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10712
10713   return fntype;
10714 }
10715
10716 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10717    ARGS into that specification, and return the substituted
10718    specification.  If there is no specification, return NULL_TREE.  */
10719
10720 static tree
10721 tsubst_exception_specification (tree fntype,
10722                                 tree args,
10723                                 tsubst_flags_t complain,
10724                                 tree in_decl,
10725                                 bool defer_ok)
10726 {
10727   tree specs;
10728   tree new_specs;
10729
10730   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10731   new_specs = NULL_TREE;
10732   if (specs && TREE_PURPOSE (specs))
10733     {
10734       /* A noexcept-specifier.  */
10735       tree expr = TREE_PURPOSE (specs);
10736       if (expr == boolean_true_node || expr == boolean_false_node)
10737         new_specs = expr;
10738       else if (defer_ok)
10739         {
10740           /* Defer instantiation of noexcept-specifiers to avoid
10741              excessive instantiations (c++/49107).  */
10742           new_specs = make_node (DEFERRED_NOEXCEPT);
10743           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10744             {
10745               /* We already partially instantiated this member template,
10746                  so combine the new args with the old.  */
10747               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10748                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10749               DEFERRED_NOEXCEPT_ARGS (new_specs)
10750                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10751             }
10752           else
10753             {
10754               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10755               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10756             }
10757         }
10758       else
10759         new_specs = tsubst_copy_and_build
10760           (expr, args, complain, in_decl, /*function_p=*/false,
10761            /*integral_constant_expression_p=*/true);
10762       new_specs = build_noexcept_spec (new_specs, complain);
10763     }
10764   else if (specs)
10765     {
10766       if (! TREE_VALUE (specs))
10767         new_specs = specs;
10768       else
10769         while (specs)
10770           {
10771             tree spec;
10772             int i, len = 1;
10773             tree expanded_specs = NULL_TREE;
10774
10775             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10776               {
10777                 /* Expand the pack expansion type.  */
10778                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10779                                                        args, complain,
10780                                                        in_decl);
10781
10782                 if (expanded_specs == error_mark_node)
10783                   return error_mark_node;
10784                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10785                   len = TREE_VEC_LENGTH (expanded_specs);
10786                 else
10787                   {
10788                     /* We're substituting into a member template, so
10789                        we got a TYPE_PACK_EXPANSION back.  Add that
10790                        expansion and move on.  */
10791                     gcc_assert (TREE_CODE (expanded_specs) 
10792                                 == TYPE_PACK_EXPANSION);
10793                     new_specs = add_exception_specifier (new_specs,
10794                                                          expanded_specs,
10795                                                          complain);
10796                     specs = TREE_CHAIN (specs);
10797                     continue;
10798                   }
10799               }
10800
10801             for (i = 0; i < len; ++i)
10802               {
10803                 if (expanded_specs)
10804                   spec = TREE_VEC_ELT (expanded_specs, i);
10805                 else
10806                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10807                 if (spec == error_mark_node)
10808                   return spec;
10809                 new_specs = add_exception_specifier (new_specs, spec, 
10810                                                      complain);
10811               }
10812
10813             specs = TREE_CHAIN (specs);
10814           }
10815     }
10816   return new_specs;
10817 }
10818
10819 /* Take the tree structure T and replace template parameters used
10820    therein with the argument vector ARGS.  IN_DECL is an associated
10821    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10822    Issue error and warning messages under control of COMPLAIN.  Note
10823    that we must be relatively non-tolerant of extensions here, in
10824    order to preserve conformance; if we allow substitutions that
10825    should not be allowed, we may allow argument deductions that should
10826    not succeed, and therefore report ambiguous overload situations
10827    where there are none.  In theory, we could allow the substitution,
10828    but indicate that it should have failed, and allow our caller to
10829    make sure that the right thing happens, but we don't try to do this
10830    yet.
10831
10832    This function is used for dealing with types, decls and the like;
10833    for expressions, use tsubst_expr or tsubst_copy.  */
10834
10835 tree
10836 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10837 {
10838   enum tree_code code;
10839   tree type, r;
10840
10841   if (t == NULL_TREE || t == error_mark_node
10842       || t == integer_type_node
10843       || t == void_type_node
10844       || t == char_type_node
10845       || t == unknown_type_node
10846       || TREE_CODE (t) == NAMESPACE_DECL
10847       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10848     return t;
10849
10850   if (DECL_P (t))
10851     return tsubst_decl (t, args, complain);
10852
10853   if (args == NULL_TREE)
10854     return t;
10855
10856   code = TREE_CODE (t);
10857
10858   if (code == IDENTIFIER_NODE)
10859     type = IDENTIFIER_TYPE_VALUE (t);
10860   else
10861     type = TREE_TYPE (t);
10862
10863   gcc_assert (type != unknown_type_node);
10864
10865   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10866      such as attribute aligned.  */
10867   if (TYPE_P (t)
10868       && typedef_variant_p (t))
10869     {
10870       tree decl = TYPE_NAME (t);
10871       
10872       if (DECL_CLASS_SCOPE_P (decl)
10873           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10874           && uses_template_parms (DECL_CONTEXT (decl)))
10875         {
10876           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10877           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10878           r = retrieve_specialization (tmpl, gen_args, 0);
10879         }
10880       else if (DECL_FUNCTION_SCOPE_P (decl)
10881                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10882                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10883         r = retrieve_local_specialization (decl);
10884       else
10885         /* The typedef is from a non-template context.  */
10886         return t;
10887
10888       if (r)
10889         {
10890           r = TREE_TYPE (r);
10891           r = cp_build_qualified_type_real
10892             (r, cp_type_quals (t) | cp_type_quals (r),
10893              complain | tf_ignore_bad_quals);
10894           return r;
10895         }
10896       /* Else we must be instantiating the typedef, so fall through.  */
10897     }
10898
10899   if (type
10900       && code != TYPENAME_TYPE
10901       && code != TEMPLATE_TYPE_PARM
10902       && code != IDENTIFIER_NODE
10903       && code != FUNCTION_TYPE
10904       && code != METHOD_TYPE)
10905     type = tsubst (type, args, complain, in_decl);
10906   if (type == error_mark_node)
10907     return error_mark_node;
10908
10909   switch (code)
10910     {
10911     case RECORD_TYPE:
10912     case UNION_TYPE:
10913     case ENUMERAL_TYPE:
10914       return tsubst_aggr_type (t, args, complain, in_decl,
10915                                /*entering_scope=*/0);
10916
10917     case ERROR_MARK:
10918     case IDENTIFIER_NODE:
10919     case VOID_TYPE:
10920     case REAL_TYPE:
10921     case COMPLEX_TYPE:
10922     case VECTOR_TYPE:
10923     case BOOLEAN_TYPE:
10924     case NULLPTR_TYPE:
10925     case LANG_TYPE:
10926       return t;
10927
10928     case INTEGER_TYPE:
10929       if (t == integer_type_node)
10930         return t;
10931
10932       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10933           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10934         return t;
10935
10936       {
10937         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10938
10939         max = tsubst_expr (omax, args, complain, in_decl,
10940                            /*integral_constant_expression_p=*/false);
10941
10942         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10943            needed.  */
10944         if (TREE_CODE (max) == NOP_EXPR
10945             && TREE_SIDE_EFFECTS (omax)
10946             && !TREE_TYPE (max))
10947           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10948
10949         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10950            with TREE_SIDE_EFFECTS that indicates this is not an integral
10951            constant expression.  */
10952         if (processing_template_decl
10953             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10954           {
10955             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10956             TREE_SIDE_EFFECTS (max) = 1;
10957           }
10958
10959         return compute_array_index_type (NULL_TREE, max, complain);
10960       }
10961
10962     case TEMPLATE_TYPE_PARM:
10963     case TEMPLATE_TEMPLATE_PARM:
10964     case BOUND_TEMPLATE_TEMPLATE_PARM:
10965     case TEMPLATE_PARM_INDEX:
10966       {
10967         int idx;
10968         int level;
10969         int levels;
10970         tree arg = NULL_TREE;
10971
10972         r = NULL_TREE;
10973
10974         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10975         template_parm_level_and_index (t, &level, &idx); 
10976
10977         levels = TMPL_ARGS_DEPTH (args);
10978         if (level <= levels)
10979           {
10980             arg = TMPL_ARG (args, level, idx);
10981
10982             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10983               /* See through ARGUMENT_PACK_SELECT arguments. */
10984               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10985           }
10986
10987         if (arg == error_mark_node)
10988           return error_mark_node;
10989         else if (arg != NULL_TREE)
10990           {
10991             if (ARGUMENT_PACK_P (arg))
10992               /* If ARG is an argument pack, we don't actually want to
10993                  perform a substitution here, because substitutions
10994                  for argument packs are only done
10995                  element-by-element. We can get to this point when
10996                  substituting the type of a non-type template
10997                  parameter pack, when that type actually contains
10998                  template parameter packs from an outer template, e.g.,
10999
11000                  template<typename... Types> struct A {
11001                    template<Types... Values> struct B { };
11002                  };  */
11003               return t;
11004
11005             if (code == TEMPLATE_TYPE_PARM)
11006               {
11007                 int quals;
11008                 gcc_assert (TYPE_P (arg));
11009
11010                 quals = cp_type_quals (arg) | cp_type_quals (t);
11011                   
11012                 return cp_build_qualified_type_real
11013                   (arg, quals, complain | tf_ignore_bad_quals);
11014               }
11015             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11016               {
11017                 /* We are processing a type constructed from a
11018                    template template parameter.  */
11019                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11020                                       args, complain, in_decl);
11021                 if (argvec == error_mark_node)
11022                   return error_mark_node;
11023
11024                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11025                    are resolving nested-types in the signature of a
11026                    member function templates.  Otherwise ARG is a
11027                    TEMPLATE_DECL and is the real template to be
11028                    instantiated.  */
11029                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11030                   arg = TYPE_NAME (arg);
11031
11032                 r = lookup_template_class (arg,
11033                                            argvec, in_decl,
11034                                            DECL_CONTEXT (arg),
11035                                             /*entering_scope=*/0,
11036                                            complain);
11037                 return cp_build_qualified_type_real
11038                   (r, cp_type_quals (t), complain);
11039               }
11040             else
11041               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11042               return convert_from_reference (unshare_expr (arg));
11043           }
11044
11045         if (level == 1)
11046           /* This can happen during the attempted tsubst'ing in
11047              unify.  This means that we don't yet have any information
11048              about the template parameter in question.  */
11049           return t;
11050
11051         /* If we get here, we must have been looking at a parm for a
11052            more deeply nested template.  Make a new version of this
11053            template parameter, but with a lower level.  */
11054         switch (code)
11055           {
11056           case TEMPLATE_TYPE_PARM:
11057           case TEMPLATE_TEMPLATE_PARM:
11058           case BOUND_TEMPLATE_TEMPLATE_PARM:
11059             if (cp_type_quals (t))
11060               {
11061                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11062                 r = cp_build_qualified_type_real
11063                   (r, cp_type_quals (t),
11064                    complain | (code == TEMPLATE_TYPE_PARM
11065                                ? tf_ignore_bad_quals : 0));
11066               }
11067             else
11068               {
11069                 r = copy_type (t);
11070                 TEMPLATE_TYPE_PARM_INDEX (r)
11071                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11072                                                 r, levels, args, complain);
11073                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11074                 TYPE_MAIN_VARIANT (r) = r;
11075                 TYPE_POINTER_TO (r) = NULL_TREE;
11076                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11077
11078                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11079                   /* We have reduced the level of the template
11080                      template parameter, but not the levels of its
11081                      template parameters, so canonical_type_parameter
11082                      will not be able to find the canonical template
11083                      template parameter for this level. Thus, we
11084                      require structural equality checking to compare
11085                      TEMPLATE_TEMPLATE_PARMs. */
11086                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11087                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11088                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11089                 else
11090                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11091
11092                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11093                   {
11094                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11095                                           complain, in_decl);
11096                     if (argvec == error_mark_node)
11097                       return error_mark_node;
11098
11099                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11100                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11101                   }
11102               }
11103             break;
11104
11105           case TEMPLATE_PARM_INDEX:
11106             r = reduce_template_parm_level (t, type, levels, args, complain);
11107             break;
11108
11109           default:
11110             gcc_unreachable ();
11111           }
11112
11113         return r;
11114       }
11115
11116     case TREE_LIST:
11117       {
11118         tree purpose, value, chain;
11119
11120         if (t == void_list_node)
11121           return t;
11122
11123         purpose = TREE_PURPOSE (t);
11124         if (purpose)
11125           {
11126             purpose = tsubst (purpose, args, complain, in_decl);
11127             if (purpose == error_mark_node)
11128               return error_mark_node;
11129           }
11130         value = TREE_VALUE (t);
11131         if (value)
11132           {
11133             value = tsubst (value, args, complain, in_decl);
11134             if (value == error_mark_node)
11135               return error_mark_node;
11136           }
11137         chain = TREE_CHAIN (t);
11138         if (chain && chain != void_type_node)
11139           {
11140             chain = tsubst (chain, args, complain, in_decl);
11141             if (chain == error_mark_node)
11142               return error_mark_node;
11143           }
11144         if (purpose == TREE_PURPOSE (t)
11145             && value == TREE_VALUE (t)
11146             && chain == TREE_CHAIN (t))
11147           return t;
11148         return hash_tree_cons (purpose, value, chain);
11149       }
11150
11151     case TREE_BINFO:
11152       /* We should never be tsubsting a binfo.  */
11153       gcc_unreachable ();
11154
11155     case TREE_VEC:
11156       /* A vector of template arguments.  */
11157       gcc_assert (!type);
11158       return tsubst_template_args (t, args, complain, in_decl);
11159
11160     case POINTER_TYPE:
11161     case REFERENCE_TYPE:
11162       {
11163         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11164           return t;
11165
11166         /* [temp.deduct]
11167
11168            Type deduction may fail for any of the following
11169            reasons:
11170
11171            -- Attempting to create a pointer to reference type.
11172            -- Attempting to create a reference to a reference type or
11173               a reference to void.
11174
11175           Core issue 106 says that creating a reference to a reference
11176           during instantiation is no longer a cause for failure. We
11177           only enforce this check in strict C++98 mode.  */
11178         if ((TREE_CODE (type) == REFERENCE_TYPE
11179              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11180             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11181           {
11182             static location_t last_loc;
11183
11184             /* We keep track of the last time we issued this error
11185                message to avoid spewing a ton of messages during a
11186                single bad template instantiation.  */
11187             if (complain & tf_error
11188                 && last_loc != input_location)
11189               {
11190                 if (TREE_CODE (type) == VOID_TYPE)
11191                   error ("forming reference to void");
11192                else if (code == POINTER_TYPE)
11193                  error ("forming pointer to reference type %qT", type);
11194                else
11195                   error ("forming reference to reference type %qT", type);
11196                 last_loc = input_location;
11197               }
11198
11199             return error_mark_node;
11200           }
11201         else if (code == POINTER_TYPE)
11202           {
11203             r = build_pointer_type (type);
11204             if (TREE_CODE (type) == METHOD_TYPE)
11205               r = build_ptrmemfunc_type (r);
11206           }
11207         else if (TREE_CODE (type) == REFERENCE_TYPE)
11208           /* In C++0x, during template argument substitution, when there is an
11209              attempt to create a reference to a reference type, reference
11210              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11211
11212              "If a template-argument for a template-parameter T names a type
11213              that is a reference to a type A, an attempt to create the type
11214              'lvalue reference to cv T' creates the type 'lvalue reference to
11215              A,' while an attempt to create the type type rvalue reference to
11216              cv T' creates the type T"
11217           */
11218           r = cp_build_reference_type
11219               (TREE_TYPE (type),
11220                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11221         else
11222           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11223         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11224
11225         if (r != error_mark_node)
11226           /* Will this ever be needed for TYPE_..._TO values?  */
11227           layout_type (r);
11228
11229         return r;
11230       }
11231     case OFFSET_TYPE:
11232       {
11233         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11234         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11235           {
11236             /* [temp.deduct]
11237
11238                Type deduction may fail for any of the following
11239                reasons:
11240
11241                -- Attempting to create "pointer to member of T" when T
11242                   is not a class type.  */
11243             if (complain & tf_error)
11244               error ("creating pointer to member of non-class type %qT", r);
11245             return error_mark_node;
11246           }
11247         if (TREE_CODE (type) == REFERENCE_TYPE)
11248           {
11249             if (complain & tf_error)
11250               error ("creating pointer to member reference type %qT", type);
11251             return error_mark_node;
11252           }
11253         if (TREE_CODE (type) == VOID_TYPE)
11254           {
11255             if (complain & tf_error)
11256               error ("creating pointer to member of type void");
11257             return error_mark_node;
11258           }
11259         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11260         if (TREE_CODE (type) == FUNCTION_TYPE)
11261           {
11262             /* The type of the implicit object parameter gets its
11263                cv-qualifiers from the FUNCTION_TYPE. */
11264             tree memptr;
11265             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11266             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11267             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11268                                                  complain);
11269           }
11270         else
11271           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11272                                                cp_type_quals (t),
11273                                                complain);
11274       }
11275     case FUNCTION_TYPE:
11276     case METHOD_TYPE:
11277       {
11278         tree fntype;
11279         tree specs;
11280         fntype = tsubst_function_type (t, args, complain, in_decl);
11281         if (fntype == error_mark_node)
11282           return error_mark_node;
11283
11284         /* Substitute the exception specification.  */
11285         specs = tsubst_exception_specification (t, args, complain,
11286                                                 in_decl, /*defer_ok*/true);
11287         if (specs == error_mark_node)
11288           return error_mark_node;
11289         if (specs)
11290           fntype = build_exception_variant (fntype, specs);
11291         return fntype;
11292       }
11293     case ARRAY_TYPE:
11294       {
11295         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11296         if (domain == error_mark_node)
11297           return error_mark_node;
11298
11299         /* As an optimization, we avoid regenerating the array type if
11300            it will obviously be the same as T.  */
11301         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11302           return t;
11303
11304         /* These checks should match the ones in grokdeclarator.
11305
11306            [temp.deduct]
11307
11308            The deduction may fail for any of the following reasons:
11309
11310            -- Attempting to create an array with an element type that
11311               is void, a function type, or a reference type, or [DR337]
11312               an abstract class type.  */
11313         if (TREE_CODE (type) == VOID_TYPE
11314             || TREE_CODE (type) == FUNCTION_TYPE
11315             || TREE_CODE (type) == REFERENCE_TYPE)
11316           {
11317             if (complain & tf_error)
11318               error ("creating array of %qT", type);
11319             return error_mark_node;
11320           }
11321         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11322           {
11323             if (complain & tf_error)
11324               error ("creating array of %qT, which is an abstract class type",
11325                      type);
11326             return error_mark_node;
11327           }
11328
11329         r = build_cplus_array_type (type, domain);
11330
11331         if (TYPE_USER_ALIGN (t))
11332           {
11333             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11334             TYPE_USER_ALIGN (r) = 1;
11335           }
11336
11337         return r;
11338       }
11339
11340     case TYPENAME_TYPE:
11341       {
11342         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11343                                      in_decl, /*entering_scope=*/1);
11344         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11345                               complain, in_decl);
11346
11347         if (ctx == error_mark_node || f == error_mark_node)
11348           return error_mark_node;
11349
11350         if (!MAYBE_CLASS_TYPE_P (ctx))
11351           {
11352             if (complain & tf_error)
11353               error ("%qT is not a class, struct, or union type", ctx);
11354             return error_mark_node;
11355           }
11356         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11357           {
11358             /* Normally, make_typename_type does not require that the CTX
11359                have complete type in order to allow things like:
11360
11361                  template <class T> struct S { typename S<T>::X Y; };
11362
11363                But, such constructs have already been resolved by this
11364                point, so here CTX really should have complete type, unless
11365                it's a partial instantiation.  */
11366             ctx = complete_type (ctx);
11367             if (!COMPLETE_TYPE_P (ctx))
11368               {
11369                 if (complain & tf_error)
11370                   cxx_incomplete_type_error (NULL_TREE, ctx);
11371                 return error_mark_node;
11372               }
11373           }
11374
11375         f = make_typename_type (ctx, f, typename_type,
11376                                 (complain & tf_error) | tf_keep_type_decl);
11377         if (f == error_mark_node)
11378           return f;
11379         if (TREE_CODE (f) == TYPE_DECL)
11380           {
11381             complain |= tf_ignore_bad_quals;
11382             f = TREE_TYPE (f);
11383           }
11384
11385         if (TREE_CODE (f) != TYPENAME_TYPE)
11386           {
11387             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11388               {
11389                 if (complain & tf_error)
11390                   error ("%qT resolves to %qT, which is not an enumeration type",
11391                          t, f);
11392                 else
11393                   return error_mark_node;
11394               }
11395             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11396               {
11397                 if (complain & tf_error)
11398                   error ("%qT resolves to %qT, which is is not a class type",
11399                          t, f);
11400                 else
11401                   return error_mark_node;
11402               }
11403           }
11404
11405         return cp_build_qualified_type_real
11406           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11407       }
11408
11409     case UNBOUND_CLASS_TEMPLATE:
11410       {
11411         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11412                                      in_decl, /*entering_scope=*/1);
11413         tree name = TYPE_IDENTIFIER (t);
11414         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11415
11416         if (ctx == error_mark_node || name == error_mark_node)
11417           return error_mark_node;
11418
11419         if (parm_list)
11420           parm_list = tsubst_template_parms (parm_list, args, complain);
11421         return make_unbound_class_template (ctx, name, parm_list, complain);
11422       }
11423
11424     case TYPEOF_TYPE:
11425       {
11426         tree type;
11427
11428         ++cp_unevaluated_operand;
11429         ++c_inhibit_evaluation_warnings;
11430
11431         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11432                             complain, in_decl,
11433                             /*integral_constant_expression_p=*/false);
11434
11435         --cp_unevaluated_operand;
11436         --c_inhibit_evaluation_warnings;
11437
11438         type = finish_typeof (type);
11439         return cp_build_qualified_type_real (type,
11440                                              cp_type_quals (t)
11441                                              | cp_type_quals (type),
11442                                              complain);
11443       }
11444
11445     case DECLTYPE_TYPE:
11446       {
11447         tree type;
11448
11449         ++cp_unevaluated_operand;
11450         ++c_inhibit_evaluation_warnings;
11451
11452         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11453                             complain, in_decl,
11454                             /*integral_constant_expression_p=*/false);
11455
11456         --cp_unevaluated_operand;
11457         --c_inhibit_evaluation_warnings;
11458
11459         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11460           type = lambda_capture_field_type (type);
11461         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11462           type = lambda_proxy_type (type);
11463         else
11464           type = finish_decltype_type
11465             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11466         return cp_build_qualified_type_real (type,
11467                                              cp_type_quals (t)
11468                                              | cp_type_quals (type),
11469                                              complain);
11470       }
11471
11472     case UNDERLYING_TYPE:
11473       {
11474         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11475                             complain, in_decl);
11476         return finish_underlying_type (type);
11477       }
11478
11479     case TYPE_ARGUMENT_PACK:
11480     case NONTYPE_ARGUMENT_PACK:
11481       {
11482         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11483         tree packed_out = 
11484           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11485                                 args,
11486                                 complain,
11487                                 in_decl);
11488         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11489
11490         /* For template nontype argument packs, also substitute into
11491            the type.  */
11492         if (code == NONTYPE_ARGUMENT_PACK)
11493           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11494
11495         return r;
11496       }
11497       break;
11498
11499     case INTEGER_CST:
11500     case REAL_CST:
11501     case STRING_CST:
11502     case PLUS_EXPR:
11503     case MINUS_EXPR:
11504     case NEGATE_EXPR:
11505     case NOP_EXPR:
11506     case INDIRECT_REF:
11507     case ADDR_EXPR:
11508     case CALL_EXPR:
11509     case ARRAY_REF:
11510     case SCOPE_REF:
11511       /* We should use one of the expression tsubsts for these codes.  */
11512       gcc_unreachable ();
11513
11514     default:
11515       sorry ("use of %qs in template", tree_code_name [(int) code]);
11516       return error_mark_node;
11517     }
11518 }
11519
11520 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11521    type of the expression on the left-hand side of the "." or "->"
11522    operator.  */
11523
11524 static tree
11525 tsubst_baselink (tree baselink, tree object_type,
11526                  tree args, tsubst_flags_t complain, tree in_decl)
11527 {
11528     tree name;
11529     tree qualifying_scope;
11530     tree fns;
11531     tree optype;
11532     tree template_args = 0;
11533     bool template_id_p = false;
11534
11535     /* A baselink indicates a function from a base class.  Both the
11536        BASELINK_ACCESS_BINFO and the base class referenced may
11537        indicate bases of the template class, rather than the
11538        instantiated class.  In addition, lookups that were not
11539        ambiguous before may be ambiguous now.  Therefore, we perform
11540        the lookup again.  */
11541     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11542     qualifying_scope = tsubst (qualifying_scope, args,
11543                                complain, in_decl);
11544     fns = BASELINK_FUNCTIONS (baselink);
11545     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11546     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11547       {
11548         template_id_p = true;
11549         template_args = TREE_OPERAND (fns, 1);
11550         fns = TREE_OPERAND (fns, 0);
11551         if (template_args)
11552           template_args = tsubst_template_args (template_args, args,
11553                                                 complain, in_decl);
11554       }
11555     name = DECL_NAME (get_first_fn (fns));
11556     if (IDENTIFIER_TYPENAME_P (name))
11557       name = mangle_conv_op_name_for_type (optype);
11558     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11559     if (!baselink)
11560       return error_mark_node;
11561
11562     /* If lookup found a single function, mark it as used at this
11563        point.  (If it lookup found multiple functions the one selected
11564        later by overload resolution will be marked as used at that
11565        point.)  */
11566     if (BASELINK_P (baselink))
11567       fns = BASELINK_FUNCTIONS (baselink);
11568     if (!template_id_p && !really_overloaded_fn (fns))
11569       mark_used (OVL_CURRENT (fns));
11570
11571     /* Add back the template arguments, if present.  */
11572     if (BASELINK_P (baselink) && template_id_p)
11573       BASELINK_FUNCTIONS (baselink)
11574         = build_nt (TEMPLATE_ID_EXPR,
11575                     BASELINK_FUNCTIONS (baselink),
11576                     template_args);
11577     /* Update the conversion operator type.  */
11578     BASELINK_OPTYPE (baselink) = optype;
11579
11580     if (!object_type)
11581       object_type = current_class_type;
11582     return adjust_result_of_qualified_name_lookup (baselink,
11583                                                    qualifying_scope,
11584                                                    object_type);
11585 }
11586
11587 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11588    true if the qualified-id will be a postfix-expression in-and-of
11589    itself; false if more of the postfix-expression follows the
11590    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11591    of "&".  */
11592
11593 static tree
11594 tsubst_qualified_id (tree qualified_id, tree args,
11595                      tsubst_flags_t complain, tree in_decl,
11596                      bool done, bool address_p)
11597 {
11598   tree expr;
11599   tree scope;
11600   tree name;
11601   bool is_template;
11602   tree template_args;
11603
11604   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11605
11606   /* Figure out what name to look up.  */
11607   name = TREE_OPERAND (qualified_id, 1);
11608   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11609     {
11610       is_template = true;
11611       template_args = TREE_OPERAND (name, 1);
11612       if (template_args)
11613         template_args = tsubst_template_args (template_args, args,
11614                                               complain, in_decl);
11615       name = TREE_OPERAND (name, 0);
11616     }
11617   else
11618     {
11619       is_template = false;
11620       template_args = NULL_TREE;
11621     }
11622
11623   /* Substitute into the qualifying scope.  When there are no ARGS, we
11624      are just trying to simplify a non-dependent expression.  In that
11625      case the qualifying scope may be dependent, and, in any case,
11626      substituting will not help.  */
11627   scope = TREE_OPERAND (qualified_id, 0);
11628   if (args)
11629     {
11630       scope = tsubst (scope, args, complain, in_decl);
11631       expr = tsubst_copy (name, args, complain, in_decl);
11632     }
11633   else
11634     expr = name;
11635
11636   if (dependent_scope_p (scope))
11637     {
11638       if (is_template)
11639         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11640       return build_qualified_name (NULL_TREE, scope, expr,
11641                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11642     }
11643
11644   if (!BASELINK_P (name) && !DECL_P (expr))
11645     {
11646       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11647         {
11648           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11649           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11650             {
11651               error ("qualifying type %qT does not match destructor name ~%qT",
11652                      scope, TREE_OPERAND (expr, 0));
11653               expr = error_mark_node;
11654             }
11655           else
11656             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11657                                           /*is_type_p=*/0, false);
11658         }
11659       else
11660         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11661       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11662                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11663         {
11664           if (complain & tf_error)
11665             {
11666               error ("dependent-name %qE is parsed as a non-type, but "
11667                      "instantiation yields a type", qualified_id);
11668               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11669             }
11670           return error_mark_node;
11671         }
11672     }
11673
11674   if (DECL_P (expr))
11675     {
11676       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11677                                            scope);
11678       /* Remember that there was a reference to this entity.  */
11679       mark_used (expr);
11680     }
11681
11682   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11683     {
11684       if (complain & tf_error)
11685         qualified_name_lookup_error (scope,
11686                                      TREE_OPERAND (qualified_id, 1),
11687                                      expr, input_location);
11688       return error_mark_node;
11689     }
11690
11691   if (is_template)
11692     expr = lookup_template_function (expr, template_args);
11693
11694   if (expr == error_mark_node && complain & tf_error)
11695     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11696                                  expr, input_location);
11697   else if (TYPE_P (scope))
11698     {
11699       expr = (adjust_result_of_qualified_name_lookup
11700               (expr, scope, current_class_type));
11701       expr = (finish_qualified_id_expr
11702               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11703                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11704                /*template_arg_p=*/false));
11705     }
11706
11707   /* Expressions do not generally have reference type.  */
11708   if (TREE_CODE (expr) != SCOPE_REF
11709       /* However, if we're about to form a pointer-to-member, we just
11710          want the referenced member referenced.  */
11711       && TREE_CODE (expr) != OFFSET_REF)
11712     expr = convert_from_reference (expr);
11713
11714   return expr;
11715 }
11716
11717 /* Like tsubst, but deals with expressions.  This function just replaces
11718    template parms; to finish processing the resultant expression, use
11719    tsubst_copy_and_build or tsubst_expr.  */
11720
11721 static tree
11722 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11723 {
11724   enum tree_code code;
11725   tree r;
11726
11727   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11728     return t;
11729
11730   code = TREE_CODE (t);
11731
11732   switch (code)
11733     {
11734     case PARM_DECL:
11735       r = retrieve_local_specialization (t);
11736
11737       if (r == NULL)
11738         {
11739           tree c;
11740
11741           /* We get here for a use of 'this' in an NSDMI.  */
11742           if (DECL_NAME (t) == this_identifier
11743               && at_function_scope_p ()
11744               && DECL_CONSTRUCTOR_P (current_function_decl))
11745             return current_class_ptr;
11746
11747           /* This can happen for a parameter name used later in a function
11748              declaration (such as in a late-specified return type).  Just
11749              make a dummy decl, since it's only used for its type.  */
11750           gcc_assert (cp_unevaluated_operand != 0);
11751           /* We copy T because want to tsubst the PARM_DECL only,
11752              not the following PARM_DECLs that are chained to T.  */
11753           c = copy_node (t);
11754           r = tsubst_decl (c, args, complain);
11755           /* Give it the template pattern as its context; its true context
11756              hasn't been instantiated yet and this is good enough for
11757              mangling.  */
11758           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11759         }
11760       
11761       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11762         r = ARGUMENT_PACK_SELECT_ARG (r);
11763       mark_used (r);
11764       return r;
11765
11766     case CONST_DECL:
11767       {
11768         tree enum_type;
11769         tree v;
11770
11771         if (DECL_TEMPLATE_PARM_P (t))
11772           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11773         /* There is no need to substitute into namespace-scope
11774            enumerators.  */
11775         if (DECL_NAMESPACE_SCOPE_P (t))
11776           return t;
11777         /* If ARGS is NULL, then T is known to be non-dependent.  */
11778         if (args == NULL_TREE)
11779           return integral_constant_value (t);
11780
11781         /* Unfortunately, we cannot just call lookup_name here.
11782            Consider:
11783
11784              template <int I> int f() {
11785              enum E { a = I };
11786              struct S { void g() { E e = a; } };
11787              };
11788
11789            When we instantiate f<7>::S::g(), say, lookup_name is not
11790            clever enough to find f<7>::a.  */
11791         enum_type
11792           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11793                               /*entering_scope=*/0);
11794
11795         for (v = TYPE_VALUES (enum_type);
11796              v != NULL_TREE;
11797              v = TREE_CHAIN (v))
11798           if (TREE_PURPOSE (v) == DECL_NAME (t))
11799             return TREE_VALUE (v);
11800
11801           /* We didn't find the name.  That should never happen; if
11802              name-lookup found it during preliminary parsing, we
11803              should find it again here during instantiation.  */
11804         gcc_unreachable ();
11805       }
11806       return t;
11807
11808     case FIELD_DECL:
11809       if (DECL_CONTEXT (t))
11810         {
11811           tree ctx;
11812
11813           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11814                                   /*entering_scope=*/1);
11815           if (ctx != DECL_CONTEXT (t))
11816             {
11817               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11818               if (!r)
11819                 {
11820                   if (complain & tf_error)
11821                     error ("using invalid field %qD", t);
11822                   return error_mark_node;
11823                 }
11824               return r;
11825             }
11826         }
11827
11828       return t;
11829
11830     case VAR_DECL:
11831     case FUNCTION_DECL:
11832       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11833           || local_variable_p (t))
11834         t = tsubst (t, args, complain, in_decl);
11835       mark_used (t);
11836       return t;
11837
11838     case OVERLOAD:
11839       /* An OVERLOAD will always be a non-dependent overload set; an
11840          overload set from function scope will just be represented with an
11841          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11842       gcc_assert (!uses_template_parms (t));
11843       return t;
11844
11845     case BASELINK:
11846       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11847
11848     case TEMPLATE_DECL:
11849       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11850         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11851                        args, complain, in_decl);
11852       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11853         return tsubst (t, args, complain, in_decl);
11854       else if (DECL_CLASS_SCOPE_P (t)
11855                && uses_template_parms (DECL_CONTEXT (t)))
11856         {
11857           /* Template template argument like the following example need
11858              special treatment:
11859
11860                template <template <class> class TT> struct C {};
11861                template <class T> struct D {
11862                  template <class U> struct E {};
11863                  C<E> c;                                // #1
11864                };
11865                D<int> d;                                // #2
11866
11867              We are processing the template argument `E' in #1 for
11868              the template instantiation #2.  Originally, `E' is a
11869              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11870              have to substitute this with one having context `D<int>'.  */
11871
11872           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11873           return lookup_field (context, DECL_NAME(t), 0, false);
11874         }
11875       else
11876         /* Ordinary template template argument.  */
11877         return t;
11878
11879     case CAST_EXPR:
11880     case REINTERPRET_CAST_EXPR:
11881     case CONST_CAST_EXPR:
11882     case STATIC_CAST_EXPR:
11883     case DYNAMIC_CAST_EXPR:
11884     case IMPLICIT_CONV_EXPR:
11885     case CONVERT_EXPR:
11886     case NOP_EXPR:
11887       return build1
11888         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11889          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11890
11891     case SIZEOF_EXPR:
11892       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11893         {
11894
11895           tree expanded;
11896           int len = 0;
11897
11898           ++cp_unevaluated_operand;
11899           ++c_inhibit_evaluation_warnings;
11900           /* We only want to compute the number of arguments.  */
11901           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11902                                             complain, in_decl);
11903           --cp_unevaluated_operand;
11904           --c_inhibit_evaluation_warnings;
11905
11906           if (TREE_CODE (expanded) == TREE_VEC)
11907             len = TREE_VEC_LENGTH (expanded);
11908
11909           if (expanded == error_mark_node)
11910             return error_mark_node;
11911           else if (PACK_EXPANSION_P (expanded)
11912                    || (TREE_CODE (expanded) == TREE_VEC
11913                        && len > 0
11914                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11915             {
11916               if (TREE_CODE (expanded) == TREE_VEC)
11917                 expanded = TREE_VEC_ELT (expanded, len - 1);
11918
11919               if (TYPE_P (expanded))
11920                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11921                                                    complain & tf_error);
11922               else
11923                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11924                                                    complain & tf_error);
11925             }
11926           else
11927             return build_int_cst (size_type_node, len);
11928         }
11929       /* Fall through */
11930
11931     case INDIRECT_REF:
11932     case NEGATE_EXPR:
11933     case TRUTH_NOT_EXPR:
11934     case BIT_NOT_EXPR:
11935     case ADDR_EXPR:
11936     case UNARY_PLUS_EXPR:      /* Unary + */
11937     case ALIGNOF_EXPR:
11938     case AT_ENCODE_EXPR:
11939     case ARROW_EXPR:
11940     case THROW_EXPR:
11941     case TYPEID_EXPR:
11942     case REALPART_EXPR:
11943     case IMAGPART_EXPR:
11944       return build1
11945         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11946          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11947
11948     case COMPONENT_REF:
11949       {
11950         tree object;
11951         tree name;
11952
11953         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11954         name = TREE_OPERAND (t, 1);
11955         if (TREE_CODE (name) == BIT_NOT_EXPR)
11956           {
11957             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11958                                 complain, in_decl);
11959             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11960           }
11961         else if (TREE_CODE (name) == SCOPE_REF
11962                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11963           {
11964             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11965                                      complain, in_decl);
11966             name = TREE_OPERAND (name, 1);
11967             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11968                                 complain, in_decl);
11969             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11970             name = build_qualified_name (/*type=*/NULL_TREE,
11971                                          base, name,
11972                                          /*template_p=*/false);
11973           }
11974         else if (TREE_CODE (name) == BASELINK)
11975           name = tsubst_baselink (name,
11976                                   non_reference (TREE_TYPE (object)),
11977                                   args, complain,
11978                                   in_decl);
11979         else
11980           name = tsubst_copy (name, args, complain, in_decl);
11981         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11982       }
11983
11984     case PLUS_EXPR:
11985     case MINUS_EXPR:
11986     case MULT_EXPR:
11987     case TRUNC_DIV_EXPR:
11988     case CEIL_DIV_EXPR:
11989     case FLOOR_DIV_EXPR:
11990     case ROUND_DIV_EXPR:
11991     case EXACT_DIV_EXPR:
11992     case BIT_AND_EXPR:
11993     case BIT_IOR_EXPR:
11994     case BIT_XOR_EXPR:
11995     case TRUNC_MOD_EXPR:
11996     case FLOOR_MOD_EXPR:
11997     case TRUTH_ANDIF_EXPR:
11998     case TRUTH_ORIF_EXPR:
11999     case TRUTH_AND_EXPR:
12000     case TRUTH_OR_EXPR:
12001     case RSHIFT_EXPR:
12002     case LSHIFT_EXPR:
12003     case RROTATE_EXPR:
12004     case LROTATE_EXPR:
12005     case EQ_EXPR:
12006     case NE_EXPR:
12007     case MAX_EXPR:
12008     case MIN_EXPR:
12009     case LE_EXPR:
12010     case GE_EXPR:
12011     case LT_EXPR:
12012     case GT_EXPR:
12013     case COMPOUND_EXPR:
12014     case DOTSTAR_EXPR:
12015     case MEMBER_REF:
12016     case PREDECREMENT_EXPR:
12017     case PREINCREMENT_EXPR:
12018     case POSTDECREMENT_EXPR:
12019     case POSTINCREMENT_EXPR:
12020       return build_nt
12021         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12022          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12023
12024     case SCOPE_REF:
12025       return build_qualified_name (/*type=*/NULL_TREE,
12026                                    tsubst_copy (TREE_OPERAND (t, 0),
12027                                                 args, complain, in_decl),
12028                                    tsubst_copy (TREE_OPERAND (t, 1),
12029                                                 args, complain, in_decl),
12030                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12031
12032     case ARRAY_REF:
12033       return build_nt
12034         (ARRAY_REF,
12035          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12036          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12037          NULL_TREE, NULL_TREE);
12038
12039     case CALL_EXPR:
12040       {
12041         int n = VL_EXP_OPERAND_LENGTH (t);
12042         tree result = build_vl_exp (CALL_EXPR, n);
12043         int i;
12044         for (i = 0; i < n; i++)
12045           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12046                                              complain, in_decl);
12047         return result;
12048       }
12049
12050     case COND_EXPR:
12051     case MODOP_EXPR:
12052     case PSEUDO_DTOR_EXPR:
12053       {
12054         r = build_nt
12055           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12056            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12057            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12058         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12059         return r;
12060       }
12061
12062     case NEW_EXPR:
12063       {
12064         r = build_nt
12065         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12066          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12067          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12068         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12069         return r;
12070       }
12071
12072     case DELETE_EXPR:
12073       {
12074         r = build_nt
12075         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12076          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12077         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12078         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12079         return r;
12080       }
12081
12082     case TEMPLATE_ID_EXPR:
12083       {
12084         /* Substituted template arguments */
12085         tree fn = TREE_OPERAND (t, 0);
12086         tree targs = TREE_OPERAND (t, 1);
12087
12088         fn = tsubst_copy (fn, args, complain, in_decl);
12089         if (targs)
12090           targs = tsubst_template_args (targs, args, complain, in_decl);
12091
12092         return lookup_template_function (fn, targs);
12093       }
12094
12095     case TREE_LIST:
12096       {
12097         tree purpose, value, chain;
12098
12099         if (t == void_list_node)
12100           return t;
12101
12102         purpose = TREE_PURPOSE (t);
12103         if (purpose)
12104           purpose = tsubst_copy (purpose, args, complain, in_decl);
12105         value = TREE_VALUE (t);
12106         if (value)
12107           value = tsubst_copy (value, args, complain, in_decl);
12108         chain = TREE_CHAIN (t);
12109         if (chain && chain != void_type_node)
12110           chain = tsubst_copy (chain, args, complain, in_decl);
12111         if (purpose == TREE_PURPOSE (t)
12112             && value == TREE_VALUE (t)
12113             && chain == TREE_CHAIN (t))
12114           return t;
12115         return tree_cons (purpose, value, chain);
12116       }
12117
12118     case RECORD_TYPE:
12119     case UNION_TYPE:
12120     case ENUMERAL_TYPE:
12121     case INTEGER_TYPE:
12122     case TEMPLATE_TYPE_PARM:
12123     case TEMPLATE_TEMPLATE_PARM:
12124     case BOUND_TEMPLATE_TEMPLATE_PARM:
12125     case TEMPLATE_PARM_INDEX:
12126     case POINTER_TYPE:
12127     case REFERENCE_TYPE:
12128     case OFFSET_TYPE:
12129     case FUNCTION_TYPE:
12130     case METHOD_TYPE:
12131     case ARRAY_TYPE:
12132     case TYPENAME_TYPE:
12133     case UNBOUND_CLASS_TEMPLATE:
12134     case TYPEOF_TYPE:
12135     case DECLTYPE_TYPE:
12136     case TYPE_DECL:
12137       return tsubst (t, args, complain, in_decl);
12138
12139     case IDENTIFIER_NODE:
12140       if (IDENTIFIER_TYPENAME_P (t))
12141         {
12142           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12143           return mangle_conv_op_name_for_type (new_type);
12144         }
12145       else
12146         return t;
12147
12148     case CONSTRUCTOR:
12149       /* This is handled by tsubst_copy_and_build.  */
12150       gcc_unreachable ();
12151
12152     case VA_ARG_EXPR:
12153       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12154                                           in_decl),
12155                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12156
12157     case CLEANUP_POINT_EXPR:
12158       /* We shouldn't have built any of these during initial template
12159          generation.  Instead, they should be built during instantiation
12160          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12161       gcc_unreachable ();
12162
12163     case OFFSET_REF:
12164       r = build2
12165         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12166          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12167          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12168       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12169       mark_used (TREE_OPERAND (r, 1));
12170       return r;
12171
12172     case EXPR_PACK_EXPANSION:
12173       error ("invalid use of pack expansion expression");
12174       return error_mark_node;
12175
12176     case NONTYPE_ARGUMENT_PACK:
12177       error ("use %<...%> to expand argument pack");
12178       return error_mark_node;
12179
12180     case INTEGER_CST:
12181     case REAL_CST:
12182     case STRING_CST:
12183     case COMPLEX_CST:
12184       {
12185         /* Instantiate any typedefs in the type.  */
12186         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12187         r = fold_convert (type, t);
12188         gcc_assert (TREE_CODE (r) == code);
12189         return r;
12190       }
12191
12192     case PTRMEM_CST:
12193       /* These can sometimes show up in a partial instantiation, but never
12194          involve template parms.  */
12195       gcc_assert (!uses_template_parms (t));
12196       return t;
12197
12198     default:
12199       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12200       gcc_checking_assert (false);
12201       return t;
12202     }
12203 }
12204
12205 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12206
12207 static tree
12208 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12209                     tree in_decl)
12210 {
12211   tree new_clauses = NULL, nc, oc;
12212
12213   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12214     {
12215       nc = copy_node (oc);
12216       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12217       new_clauses = nc;
12218
12219       switch (OMP_CLAUSE_CODE (nc))
12220         {
12221         case OMP_CLAUSE_LASTPRIVATE:
12222           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12223             {
12224               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12225               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12226                            in_decl, /*integral_constant_expression_p=*/false);
12227               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12228                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12229             }
12230           /* FALLTHRU */
12231         case OMP_CLAUSE_PRIVATE:
12232         case OMP_CLAUSE_SHARED:
12233         case OMP_CLAUSE_FIRSTPRIVATE:
12234         case OMP_CLAUSE_REDUCTION:
12235         case OMP_CLAUSE_COPYIN:
12236         case OMP_CLAUSE_COPYPRIVATE:
12237         case OMP_CLAUSE_IF:
12238         case OMP_CLAUSE_NUM_THREADS:
12239         case OMP_CLAUSE_SCHEDULE:
12240         case OMP_CLAUSE_COLLAPSE:
12241         case OMP_CLAUSE_FINAL:
12242           OMP_CLAUSE_OPERAND (nc, 0)
12243             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12244                            in_decl, /*integral_constant_expression_p=*/false);
12245           break;
12246         case OMP_CLAUSE_NOWAIT:
12247         case OMP_CLAUSE_ORDERED:
12248         case OMP_CLAUSE_DEFAULT:
12249         case OMP_CLAUSE_UNTIED:
12250         case OMP_CLAUSE_MERGEABLE:
12251           break;
12252         default:
12253           gcc_unreachable ();
12254         }
12255     }
12256
12257   return finish_omp_clauses (nreverse (new_clauses));
12258 }
12259
12260 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12261
12262 static tree
12263 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12264                           tree in_decl)
12265 {
12266 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12267
12268   tree purpose, value, chain;
12269
12270   if (t == NULL)
12271     return t;
12272
12273   if (TREE_CODE (t) != TREE_LIST)
12274     return tsubst_copy_and_build (t, args, complain, in_decl,
12275                                   /*function_p=*/false,
12276                                   /*integral_constant_expression_p=*/false);
12277
12278   if (t == void_list_node)
12279     return t;
12280
12281   purpose = TREE_PURPOSE (t);
12282   if (purpose)
12283     purpose = RECUR (purpose);
12284   value = TREE_VALUE (t);
12285   if (value && TREE_CODE (value) != LABEL_DECL)
12286     value = RECUR (value);
12287   chain = TREE_CHAIN (t);
12288   if (chain && chain != void_type_node)
12289     chain = RECUR (chain);
12290   return tree_cons (purpose, value, chain);
12291 #undef RECUR
12292 }
12293
12294 /* Substitute one OMP_FOR iterator.  */
12295
12296 static void
12297 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12298                          tree condv, tree incrv, tree *clauses,
12299                          tree args, tsubst_flags_t complain, tree in_decl,
12300                          bool integral_constant_expression_p)
12301 {
12302 #define RECUR(NODE)                             \
12303   tsubst_expr ((NODE), args, complain, in_decl, \
12304                integral_constant_expression_p)
12305   tree decl, init, cond, incr, auto_node;
12306
12307   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12308   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12309   decl = RECUR (TREE_OPERAND (init, 0));
12310   init = TREE_OPERAND (init, 1);
12311   auto_node = type_uses_auto (TREE_TYPE (decl));
12312   if (auto_node && init)
12313     {
12314       tree init_expr = init;
12315       if (TREE_CODE (init_expr) == DECL_EXPR)
12316         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12317       init_expr = RECUR (init_expr);
12318       TREE_TYPE (decl)
12319         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12320     }
12321   gcc_assert (!type_dependent_expression_p (decl));
12322
12323   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12324     {
12325       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12326       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12327       if (TREE_CODE (incr) == MODIFY_EXPR)
12328         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12329                                     RECUR (TREE_OPERAND (incr, 1)),
12330                                     complain);
12331       else
12332         incr = RECUR (incr);
12333       TREE_VEC_ELT (declv, i) = decl;
12334       TREE_VEC_ELT (initv, i) = init;
12335       TREE_VEC_ELT (condv, i) = cond;
12336       TREE_VEC_ELT (incrv, i) = incr;
12337       return;
12338     }
12339
12340   if (init && TREE_CODE (init) != DECL_EXPR)
12341     {
12342       tree c;
12343       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12344         {
12345           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12346                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12347               && OMP_CLAUSE_DECL (c) == decl)
12348             break;
12349           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12350                    && OMP_CLAUSE_DECL (c) == decl)
12351             error ("iteration variable %qD should not be firstprivate", decl);
12352           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12353                    && OMP_CLAUSE_DECL (c) == decl)
12354             error ("iteration variable %qD should not be reduction", decl);
12355         }
12356       if (c == NULL)
12357         {
12358           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12359           OMP_CLAUSE_DECL (c) = decl;
12360           c = finish_omp_clauses (c);
12361           if (c)
12362             {
12363               OMP_CLAUSE_CHAIN (c) = *clauses;
12364               *clauses = c;
12365             }
12366         }
12367     }
12368   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12369   if (COMPARISON_CLASS_P (cond))
12370     cond = build2 (TREE_CODE (cond), boolean_type_node,
12371                    RECUR (TREE_OPERAND (cond, 0)),
12372                    RECUR (TREE_OPERAND (cond, 1)));
12373   else
12374     cond = RECUR (cond);
12375   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12376   switch (TREE_CODE (incr))
12377     {
12378     case PREINCREMENT_EXPR:
12379     case PREDECREMENT_EXPR:
12380     case POSTINCREMENT_EXPR:
12381     case POSTDECREMENT_EXPR:
12382       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12383                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12384       break;
12385     case MODIFY_EXPR:
12386       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12387           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12388         {
12389           tree rhs = TREE_OPERAND (incr, 1);
12390           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12391                          RECUR (TREE_OPERAND (incr, 0)),
12392                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12393                                  RECUR (TREE_OPERAND (rhs, 0)),
12394                                  RECUR (TREE_OPERAND (rhs, 1))));
12395         }
12396       else
12397         incr = RECUR (incr);
12398       break;
12399     case MODOP_EXPR:
12400       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12401           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12402         {
12403           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12404           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12405                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12406                                  TREE_TYPE (decl), lhs,
12407                                  RECUR (TREE_OPERAND (incr, 2))));
12408         }
12409       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12410                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12411                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12412         {
12413           tree rhs = TREE_OPERAND (incr, 2);
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     default:
12424       incr = RECUR (incr);
12425       break;
12426     }
12427
12428   TREE_VEC_ELT (declv, i) = decl;
12429   TREE_VEC_ELT (initv, i) = init;
12430   TREE_VEC_ELT (condv, i) = cond;
12431   TREE_VEC_ELT (incrv, i) = incr;
12432 #undef RECUR
12433 }
12434
12435 /* Like tsubst_copy for expressions, etc. but also does semantic
12436    processing.  */
12437
12438 static tree
12439 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12440              bool integral_constant_expression_p)
12441 {
12442 #define RECUR(NODE)                             \
12443   tsubst_expr ((NODE), args, complain, in_decl, \
12444                integral_constant_expression_p)
12445
12446   tree stmt, tmp;
12447
12448   if (t == NULL_TREE || t == error_mark_node)
12449     return t;
12450
12451   if (EXPR_HAS_LOCATION (t))
12452     input_location = EXPR_LOCATION (t);
12453   if (STATEMENT_CODE_P (TREE_CODE (t)))
12454     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12455
12456   switch (TREE_CODE (t))
12457     {
12458     case STATEMENT_LIST:
12459       {
12460         tree_stmt_iterator i;
12461         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12462           RECUR (tsi_stmt (i));
12463         break;
12464       }
12465
12466     case CTOR_INITIALIZER:
12467       finish_mem_initializers (tsubst_initializer_list
12468                                (TREE_OPERAND (t, 0), args));
12469       break;
12470
12471     case RETURN_EXPR:
12472       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12473       break;
12474
12475     case EXPR_STMT:
12476       tmp = RECUR (EXPR_STMT_EXPR (t));
12477       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12478         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12479       else
12480         finish_expr_stmt (tmp);
12481       break;
12482
12483     case USING_STMT:
12484       do_using_directive (USING_STMT_NAMESPACE (t));
12485       break;
12486
12487     case DECL_EXPR:
12488       {
12489         tree decl, pattern_decl;
12490         tree init;
12491
12492         pattern_decl = decl = DECL_EXPR_DECL (t);
12493         if (TREE_CODE (decl) == LABEL_DECL)
12494           finish_label_decl (DECL_NAME (decl));
12495         else if (TREE_CODE (decl) == USING_DECL)
12496           {
12497             tree scope = USING_DECL_SCOPE (decl);
12498             tree name = DECL_NAME (decl);
12499             tree decl;
12500
12501             scope = tsubst (scope, args, complain, in_decl);
12502             decl = lookup_qualified_name (scope, name,
12503                                           /*is_type_p=*/false,
12504                                           /*complain=*/false);
12505             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12506               qualified_name_lookup_error (scope, name, decl, input_location);
12507             else
12508               do_local_using_decl (decl, scope, name);
12509           }
12510         else
12511           {
12512             init = DECL_INITIAL (decl);
12513             decl = tsubst (decl, args, complain, in_decl);
12514             if (decl != error_mark_node)
12515               {
12516                 /* By marking the declaration as instantiated, we avoid
12517                    trying to instantiate it.  Since instantiate_decl can't
12518                    handle local variables, and since we've already done
12519                    all that needs to be done, that's the right thing to
12520                    do.  */
12521                 if (TREE_CODE (decl) == VAR_DECL)
12522                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12523                 if (TREE_CODE (decl) == VAR_DECL
12524                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12525                   /* Anonymous aggregates are a special case.  */
12526                   finish_anon_union (decl);
12527                 else
12528                   {
12529                     int const_init = false;
12530                     maybe_push_decl (decl);
12531                     if (TREE_CODE (decl) == VAR_DECL
12532                         && DECL_PRETTY_FUNCTION_P (decl))
12533                       {
12534                         /* For __PRETTY_FUNCTION__ we have to adjust the
12535                            initializer.  */
12536                         const char *const name
12537                           = cxx_printable_name (current_function_decl, 2);
12538                         init = cp_fname_init (name, &TREE_TYPE (decl));
12539                       }
12540                     else
12541                       {
12542                         tree t = RECUR (init);
12543
12544                         if (init && !t)
12545                           {
12546                             /* If we had an initializer but it
12547                                instantiated to nothing,
12548                                value-initialize the object.  This will
12549                                only occur when the initializer was a
12550                                pack expansion where the parameter packs
12551                                used in that expansion were of length
12552                                zero.  */
12553                             init = build_value_init (TREE_TYPE (decl),
12554                                                      complain);
12555                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12556                               init = get_target_expr_sfinae (init, complain);
12557                           }
12558                         else
12559                           init = t;
12560                       }
12561
12562                     if (TREE_CODE (decl) == VAR_DECL)
12563                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12564                                     (pattern_decl));
12565                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12566                   }
12567               }
12568           }
12569
12570         /* A DECL_EXPR can also be used as an expression, in the condition
12571            clause of an if/for/while construct.  */
12572         return decl;
12573       }
12574
12575     case FOR_STMT:
12576       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12577       RECUR (FOR_INIT_STMT (t));
12578       finish_for_init_stmt (stmt);
12579       tmp = RECUR (FOR_COND (t));
12580       finish_for_cond (tmp, stmt);
12581       tmp = RECUR (FOR_EXPR (t));
12582       finish_for_expr (tmp, stmt);
12583       RECUR (FOR_BODY (t));
12584       finish_for_stmt (stmt);
12585       break;
12586
12587     case RANGE_FOR_STMT:
12588       {
12589         tree decl, expr;
12590         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12591         decl = RANGE_FOR_DECL (t);
12592         decl = tsubst (decl, args, complain, in_decl);
12593         maybe_push_decl (decl);
12594         expr = RECUR (RANGE_FOR_EXPR (t));
12595         stmt = cp_convert_range_for (stmt, decl, expr);
12596         RECUR (RANGE_FOR_BODY (t));
12597         finish_for_stmt (stmt);
12598       }
12599       break;
12600
12601     case WHILE_STMT:
12602       stmt = begin_while_stmt ();
12603       tmp = RECUR (WHILE_COND (t));
12604       finish_while_stmt_cond (tmp, stmt);
12605       RECUR (WHILE_BODY (t));
12606       finish_while_stmt (stmt);
12607       break;
12608
12609     case DO_STMT:
12610       stmt = begin_do_stmt ();
12611       RECUR (DO_BODY (t));
12612       finish_do_body (stmt);
12613       tmp = RECUR (DO_COND (t));
12614       finish_do_stmt (tmp, stmt);
12615       break;
12616
12617     case IF_STMT:
12618       stmt = begin_if_stmt ();
12619       tmp = RECUR (IF_COND (t));
12620       finish_if_stmt_cond (tmp, stmt);
12621       RECUR (THEN_CLAUSE (t));
12622       finish_then_clause (stmt);
12623
12624       if (ELSE_CLAUSE (t))
12625         {
12626           begin_else_clause (stmt);
12627           RECUR (ELSE_CLAUSE (t));
12628           finish_else_clause (stmt);
12629         }
12630
12631       finish_if_stmt (stmt);
12632       break;
12633
12634     case BIND_EXPR:
12635       if (BIND_EXPR_BODY_BLOCK (t))
12636         stmt = begin_function_body ();
12637       else
12638         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12639                                     ? BCS_TRY_BLOCK : 0);
12640
12641       RECUR (BIND_EXPR_BODY (t));
12642
12643       if (BIND_EXPR_BODY_BLOCK (t))
12644         finish_function_body (stmt);
12645       else
12646         finish_compound_stmt (stmt);
12647       break;
12648
12649     case BREAK_STMT:
12650       finish_break_stmt ();
12651       break;
12652
12653     case CONTINUE_STMT:
12654       finish_continue_stmt ();
12655       break;
12656
12657     case SWITCH_STMT:
12658       stmt = begin_switch_stmt ();
12659       tmp = RECUR (SWITCH_STMT_COND (t));
12660       finish_switch_cond (tmp, stmt);
12661       RECUR (SWITCH_STMT_BODY (t));
12662       finish_switch_stmt (stmt);
12663       break;
12664
12665     case CASE_LABEL_EXPR:
12666       finish_case_label (EXPR_LOCATION (t),
12667                          RECUR (CASE_LOW (t)),
12668                          RECUR (CASE_HIGH (t)));
12669       break;
12670
12671     case LABEL_EXPR:
12672       {
12673         tree decl = LABEL_EXPR_LABEL (t);
12674         tree label;
12675
12676         label = finish_label_stmt (DECL_NAME (decl));
12677         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12678           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12679       }
12680       break;
12681
12682     case GOTO_EXPR:
12683       tmp = GOTO_DESTINATION (t);
12684       if (TREE_CODE (tmp) != LABEL_DECL)
12685         /* Computed goto's must be tsubst'd into.  On the other hand,
12686            non-computed gotos must not be; the identifier in question
12687            will have no binding.  */
12688         tmp = RECUR (tmp);
12689       else
12690         tmp = DECL_NAME (tmp);
12691       finish_goto_stmt (tmp);
12692       break;
12693
12694     case ASM_EXPR:
12695       tmp = finish_asm_stmt
12696         (ASM_VOLATILE_P (t),
12697          RECUR (ASM_STRING (t)),
12698          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12699          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12700          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12701          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12702       {
12703         tree asm_expr = tmp;
12704         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12705           asm_expr = TREE_OPERAND (asm_expr, 0);
12706         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12707       }
12708       break;
12709
12710     case TRY_BLOCK:
12711       if (CLEANUP_P (t))
12712         {
12713           stmt = begin_try_block ();
12714           RECUR (TRY_STMTS (t));
12715           finish_cleanup_try_block (stmt);
12716           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12717         }
12718       else
12719         {
12720           tree compound_stmt = NULL_TREE;
12721
12722           if (FN_TRY_BLOCK_P (t))
12723             stmt = begin_function_try_block (&compound_stmt);
12724           else
12725             stmt = begin_try_block ();
12726
12727           RECUR (TRY_STMTS (t));
12728
12729           if (FN_TRY_BLOCK_P (t))
12730             finish_function_try_block (stmt);
12731           else
12732             finish_try_block (stmt);
12733
12734           RECUR (TRY_HANDLERS (t));
12735           if (FN_TRY_BLOCK_P (t))
12736             finish_function_handler_sequence (stmt, compound_stmt);
12737           else
12738             finish_handler_sequence (stmt);
12739         }
12740       break;
12741
12742     case HANDLER:
12743       {
12744         tree decl = HANDLER_PARMS (t);
12745
12746         if (decl)
12747           {
12748             decl = tsubst (decl, args, complain, in_decl);
12749             /* Prevent instantiate_decl from trying to instantiate
12750                this variable.  We've already done all that needs to be
12751                done.  */
12752             if (decl != error_mark_node)
12753               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12754           }
12755         stmt = begin_handler ();
12756         finish_handler_parms (decl, stmt);
12757         RECUR (HANDLER_BODY (t));
12758         finish_handler (stmt);
12759       }
12760       break;
12761
12762     case TAG_DEFN:
12763       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12764       break;
12765
12766     case STATIC_ASSERT:
12767       {
12768         tree condition = 
12769           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12770                        args,
12771                        complain, in_decl,
12772                        /*integral_constant_expression_p=*/true);
12773         finish_static_assert (condition,
12774                               STATIC_ASSERT_MESSAGE (t),
12775                               STATIC_ASSERT_SOURCE_LOCATION (t),
12776                               /*member_p=*/false);
12777       }
12778       break;
12779
12780     case OMP_PARALLEL:
12781       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12782                                 args, complain, in_decl);
12783       stmt = begin_omp_parallel ();
12784       RECUR (OMP_PARALLEL_BODY (t));
12785       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12786         = OMP_PARALLEL_COMBINED (t);
12787       break;
12788
12789     case OMP_TASK:
12790       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12791                                 args, complain, in_decl);
12792       stmt = begin_omp_task ();
12793       RECUR (OMP_TASK_BODY (t));
12794       finish_omp_task (tmp, stmt);
12795       break;
12796
12797     case OMP_FOR:
12798       {
12799         tree clauses, body, pre_body;
12800         tree declv, initv, condv, incrv;
12801         int i;
12802
12803         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12804                                       args, complain, in_decl);
12805         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12806         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12807         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12808         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12809
12810         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12811           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12812                                    &clauses, args, complain, in_decl,
12813                                    integral_constant_expression_p);
12814
12815         stmt = begin_omp_structured_block ();
12816
12817         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12818           if (TREE_VEC_ELT (initv, i) == NULL
12819               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12820             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12821           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12822             {
12823               tree init = RECUR (TREE_VEC_ELT (initv, i));
12824               gcc_assert (init == TREE_VEC_ELT (declv, i));
12825               TREE_VEC_ELT (initv, i) = NULL_TREE;
12826             }
12827           else
12828             {
12829               tree decl_expr = TREE_VEC_ELT (initv, i);
12830               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12831               gcc_assert (init != NULL);
12832               TREE_VEC_ELT (initv, i) = RECUR (init);
12833               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12834               RECUR (decl_expr);
12835               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12836             }
12837
12838         pre_body = push_stmt_list ();
12839         RECUR (OMP_FOR_PRE_BODY (t));
12840         pre_body = pop_stmt_list (pre_body);
12841
12842         body = push_stmt_list ();
12843         RECUR (OMP_FOR_BODY (t));
12844         body = pop_stmt_list (body);
12845
12846         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12847                             body, pre_body, clauses);
12848
12849         add_stmt (finish_omp_structured_block (stmt));
12850       }
12851       break;
12852
12853     case OMP_SECTIONS:
12854     case OMP_SINGLE:
12855       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12856       stmt = push_stmt_list ();
12857       RECUR (OMP_BODY (t));
12858       stmt = pop_stmt_list (stmt);
12859
12860       t = copy_node (t);
12861       OMP_BODY (t) = stmt;
12862       OMP_CLAUSES (t) = tmp;
12863       add_stmt (t);
12864       break;
12865
12866     case OMP_SECTION:
12867     case OMP_CRITICAL:
12868     case OMP_MASTER:
12869     case OMP_ORDERED:
12870       stmt = push_stmt_list ();
12871       RECUR (OMP_BODY (t));
12872       stmt = pop_stmt_list (stmt);
12873
12874       t = copy_node (t);
12875       OMP_BODY (t) = stmt;
12876       add_stmt (t);
12877       break;
12878
12879     case OMP_ATOMIC:
12880       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12881       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12882         {
12883           tree op1 = TREE_OPERAND (t, 1);
12884           tree rhs1 = NULL_TREE;
12885           tree lhs, rhs;
12886           if (TREE_CODE (op1) == COMPOUND_EXPR)
12887             {
12888               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12889               op1 = TREE_OPERAND (op1, 1);
12890             }
12891           lhs = RECUR (TREE_OPERAND (op1, 0));
12892           rhs = RECUR (TREE_OPERAND (op1, 1));
12893           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12894                              NULL_TREE, NULL_TREE, rhs1);
12895         }
12896       else
12897         {
12898           tree op1 = TREE_OPERAND (t, 1);
12899           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12900           tree rhs1 = NULL_TREE;
12901           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12902           enum tree_code opcode = NOP_EXPR;
12903           if (code == OMP_ATOMIC_READ)
12904             {
12905               v = RECUR (TREE_OPERAND (op1, 0));
12906               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12907             }
12908           else if (code == OMP_ATOMIC_CAPTURE_OLD
12909                    || code == OMP_ATOMIC_CAPTURE_NEW)
12910             {
12911               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12912               v = RECUR (TREE_OPERAND (op1, 0));
12913               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12914               if (TREE_CODE (op11) == COMPOUND_EXPR)
12915                 {
12916                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12917                   op11 = TREE_OPERAND (op11, 1);
12918                 }
12919               lhs = RECUR (TREE_OPERAND (op11, 0));
12920               rhs = RECUR (TREE_OPERAND (op11, 1));
12921               opcode = TREE_CODE (op11);
12922             }
12923           else
12924             {
12925               code = OMP_ATOMIC;
12926               lhs = RECUR (TREE_OPERAND (op1, 0));
12927               rhs = RECUR (TREE_OPERAND (op1, 1));
12928             }
12929           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12930         }
12931       break;
12932
12933     case EXPR_PACK_EXPANSION:
12934       error ("invalid use of pack expansion expression");
12935       return error_mark_node;
12936
12937     case NONTYPE_ARGUMENT_PACK:
12938       error ("use %<...%> to expand argument pack");
12939       return error_mark_node;
12940
12941     default:
12942       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12943
12944       return tsubst_copy_and_build (t, args, complain, in_decl,
12945                                     /*function_p=*/false,
12946                                     integral_constant_expression_p);
12947     }
12948
12949   return NULL_TREE;
12950 #undef RECUR
12951 }
12952
12953 /* T is a postfix-expression that is not being used in a function
12954    call.  Return the substituted version of T.  */
12955
12956 static tree
12957 tsubst_non_call_postfix_expression (tree t, tree args,
12958                                     tsubst_flags_t complain,
12959                                     tree in_decl)
12960 {
12961   if (TREE_CODE (t) == SCOPE_REF)
12962     t = tsubst_qualified_id (t, args, complain, in_decl,
12963                              /*done=*/false, /*address_p=*/false);
12964   else
12965     t = tsubst_copy_and_build (t, args, complain, in_decl,
12966                                /*function_p=*/false,
12967                                /*integral_constant_expression_p=*/false);
12968
12969   return t;
12970 }
12971
12972 /* Like tsubst but deals with expressions and performs semantic
12973    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12974
12975 tree
12976 tsubst_copy_and_build (tree t,
12977                        tree args,
12978                        tsubst_flags_t complain,
12979                        tree in_decl,
12980                        bool function_p,
12981                        bool integral_constant_expression_p)
12982 {
12983 #define RECUR(NODE)                                             \
12984   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12985                          /*function_p=*/false,                  \
12986                          integral_constant_expression_p)
12987
12988   tree op1;
12989
12990   if (t == NULL_TREE || t == error_mark_node)
12991     return t;
12992
12993   switch (TREE_CODE (t))
12994     {
12995     case USING_DECL:
12996       t = DECL_NAME (t);
12997       /* Fall through.  */
12998     case IDENTIFIER_NODE:
12999       {
13000         tree decl;
13001         cp_id_kind idk;
13002         bool non_integral_constant_expression_p;
13003         const char *error_msg;
13004
13005         if (IDENTIFIER_TYPENAME_P (t))
13006           {
13007             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13008             t = mangle_conv_op_name_for_type (new_type);
13009           }
13010
13011         /* Look up the name.  */
13012         decl = lookup_name (t);
13013
13014         /* By convention, expressions use ERROR_MARK_NODE to indicate
13015            failure, not NULL_TREE.  */
13016         if (decl == NULL_TREE)
13017           decl = error_mark_node;
13018
13019         decl = finish_id_expression (t, decl, NULL_TREE,
13020                                      &idk,
13021                                      integral_constant_expression_p,
13022                                      /*allow_non_integral_constant_expression_p=*/false,
13023                                      &non_integral_constant_expression_p,
13024                                      /*template_p=*/false,
13025                                      /*done=*/true,
13026                                      /*address_p=*/false,
13027                                      /*template_arg_p=*/false,
13028                                      &error_msg,
13029                                      input_location);
13030         if (error_msg)
13031           error (error_msg);
13032         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13033           {
13034             if (complain & tf_error)
13035               unqualified_name_lookup_error (decl);
13036             decl = error_mark_node;
13037           }
13038         return decl;
13039       }
13040
13041     case TEMPLATE_ID_EXPR:
13042       {
13043         tree object;
13044         tree templ = RECUR (TREE_OPERAND (t, 0));
13045         tree targs = TREE_OPERAND (t, 1);
13046
13047         if (targs)
13048           targs = tsubst_template_args (targs, args, complain, in_decl);
13049
13050         if (TREE_CODE (templ) == COMPONENT_REF)
13051           {
13052             object = TREE_OPERAND (templ, 0);
13053             templ = TREE_OPERAND (templ, 1);
13054           }
13055         else
13056           object = NULL_TREE;
13057         templ = lookup_template_function (templ, targs);
13058
13059         if (object)
13060           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13061                          object, templ, NULL_TREE);
13062         else
13063           return baselink_for_fns (templ);
13064       }
13065
13066     case INDIRECT_REF:
13067       {
13068         tree r = RECUR (TREE_OPERAND (t, 0));
13069
13070         if (REFERENCE_REF_P (t))
13071           {
13072             /* A type conversion to reference type will be enclosed in
13073                such an indirect ref, but the substitution of the cast
13074                will have also added such an indirect ref.  */
13075             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13076               r = convert_from_reference (r);
13077           }
13078         else
13079           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13080         return r;
13081       }
13082
13083     case NOP_EXPR:
13084       return build_nop
13085         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13086          RECUR (TREE_OPERAND (t, 0)));
13087
13088     case IMPLICIT_CONV_EXPR:
13089       {
13090         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13091         tree expr = RECUR (TREE_OPERAND (t, 0));
13092         int flags = LOOKUP_IMPLICIT;
13093         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13094           flags = LOOKUP_NORMAL;
13095         return perform_implicit_conversion_flags (type, expr, complain,
13096                                                   flags);
13097       }
13098
13099     case CONVERT_EXPR:
13100       return build1
13101         (CONVERT_EXPR,
13102          tsubst (TREE_TYPE (t), args, complain, in_decl),
13103          RECUR (TREE_OPERAND (t, 0)));
13104
13105     case CAST_EXPR:
13106     case REINTERPRET_CAST_EXPR:
13107     case CONST_CAST_EXPR:
13108     case DYNAMIC_CAST_EXPR:
13109     case STATIC_CAST_EXPR:
13110       {
13111         tree type;
13112         tree op;
13113
13114         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13115         if (integral_constant_expression_p
13116             && !cast_valid_in_integral_constant_expression_p (type))
13117           {
13118             if (complain & tf_error)
13119               error ("a cast to a type other than an integral or "
13120                      "enumeration type cannot appear in a constant-expression");
13121             return error_mark_node; 
13122           }
13123
13124         op = RECUR (TREE_OPERAND (t, 0));
13125
13126         switch (TREE_CODE (t))
13127           {
13128           case CAST_EXPR:
13129             return build_functional_cast (type, op, complain);
13130           case REINTERPRET_CAST_EXPR:
13131             return build_reinterpret_cast (type, op, complain);
13132           case CONST_CAST_EXPR:
13133             return build_const_cast (type, op, complain);
13134           case DYNAMIC_CAST_EXPR:
13135             return build_dynamic_cast (type, op, complain);
13136           case STATIC_CAST_EXPR:
13137             return build_static_cast (type, op, complain);
13138           default:
13139             gcc_unreachable ();
13140           }
13141       }
13142
13143     case POSTDECREMENT_EXPR:
13144     case POSTINCREMENT_EXPR:
13145       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13146                                                 args, complain, in_decl);
13147       return build_x_unary_op (TREE_CODE (t), op1, complain);
13148
13149     case PREDECREMENT_EXPR:
13150     case PREINCREMENT_EXPR:
13151     case NEGATE_EXPR:
13152     case BIT_NOT_EXPR:
13153     case ABS_EXPR:
13154     case TRUTH_NOT_EXPR:
13155     case UNARY_PLUS_EXPR:  /* Unary + */
13156     case REALPART_EXPR:
13157     case IMAGPART_EXPR:
13158       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13159                                complain);
13160
13161     case ADDR_EXPR:
13162       op1 = TREE_OPERAND (t, 0);
13163       if (TREE_CODE (op1) == LABEL_DECL)
13164         return finish_label_address_expr (DECL_NAME (op1),
13165                                           EXPR_LOCATION (op1));
13166       if (TREE_CODE (op1) == SCOPE_REF)
13167         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13168                                    /*done=*/true, /*address_p=*/true);
13169       else
13170         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13171                                                   in_decl);
13172       return build_x_unary_op (ADDR_EXPR, op1, complain);
13173
13174     case PLUS_EXPR:
13175     case MINUS_EXPR:
13176     case MULT_EXPR:
13177     case TRUNC_DIV_EXPR:
13178     case CEIL_DIV_EXPR:
13179     case FLOOR_DIV_EXPR:
13180     case ROUND_DIV_EXPR:
13181     case EXACT_DIV_EXPR:
13182     case BIT_AND_EXPR:
13183     case BIT_IOR_EXPR:
13184     case BIT_XOR_EXPR:
13185     case TRUNC_MOD_EXPR:
13186     case FLOOR_MOD_EXPR:
13187     case TRUTH_ANDIF_EXPR:
13188     case TRUTH_ORIF_EXPR:
13189     case TRUTH_AND_EXPR:
13190     case TRUTH_OR_EXPR:
13191     case RSHIFT_EXPR:
13192     case LSHIFT_EXPR:
13193     case RROTATE_EXPR:
13194     case LROTATE_EXPR:
13195     case EQ_EXPR:
13196     case NE_EXPR:
13197     case MAX_EXPR:
13198     case MIN_EXPR:
13199     case LE_EXPR:
13200     case GE_EXPR:
13201     case LT_EXPR:
13202     case GT_EXPR:
13203     case MEMBER_REF:
13204     case DOTSTAR_EXPR:
13205       return build_x_binary_op
13206         (TREE_CODE (t),
13207          RECUR (TREE_OPERAND (t, 0)),
13208          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13209           ? ERROR_MARK
13210           : TREE_CODE (TREE_OPERAND (t, 0))),
13211          RECUR (TREE_OPERAND (t, 1)),
13212          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13213           ? ERROR_MARK
13214           : TREE_CODE (TREE_OPERAND (t, 1))),
13215          /*overload=*/NULL,
13216          complain);
13217
13218     case SCOPE_REF:
13219       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13220                                   /*address_p=*/false);
13221     case ARRAY_REF:
13222       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13223                                                 args, complain, in_decl);
13224       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13225
13226     case SIZEOF_EXPR:
13227       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13228         return tsubst_copy (t, args, complain, in_decl);
13229       /* Fall through */
13230       
13231     case ALIGNOF_EXPR:
13232       op1 = TREE_OPERAND (t, 0);
13233       if (!args)
13234         {
13235           /* When there are no ARGS, we are trying to evaluate a
13236              non-dependent expression from the parser.  Trying to do
13237              the substitutions may not work.  */
13238           if (!TYPE_P (op1))
13239             op1 = TREE_TYPE (op1);
13240         }
13241       else
13242         {
13243           ++cp_unevaluated_operand;
13244           ++c_inhibit_evaluation_warnings;
13245           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13246                                        /*function_p=*/false,
13247                                        /*integral_constant_expression_p=*/false);
13248           --cp_unevaluated_operand;
13249           --c_inhibit_evaluation_warnings;
13250         }
13251       if (TYPE_P (op1))
13252         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13253                                            complain & tf_error);
13254       else
13255         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13256                                            complain & tf_error);
13257
13258     case AT_ENCODE_EXPR:
13259       {
13260         op1 = TREE_OPERAND (t, 0);
13261         ++cp_unevaluated_operand;
13262         ++c_inhibit_evaluation_warnings;
13263         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13264                                      /*function_p=*/false,
13265                                      /*integral_constant_expression_p=*/false);
13266         --cp_unevaluated_operand;
13267         --c_inhibit_evaluation_warnings;
13268         return objc_build_encode_expr (op1);
13269       }
13270
13271     case NOEXCEPT_EXPR:
13272       op1 = TREE_OPERAND (t, 0);
13273       ++cp_unevaluated_operand;
13274       ++c_inhibit_evaluation_warnings;
13275       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13276                                    /*function_p=*/false,
13277                                    /*integral_constant_expression_p=*/false);
13278       --cp_unevaluated_operand;
13279       --c_inhibit_evaluation_warnings;
13280       return finish_noexcept_expr (op1, complain);
13281
13282     case MODOP_EXPR:
13283       {
13284         tree r = build_x_modify_expr
13285           (RECUR (TREE_OPERAND (t, 0)),
13286            TREE_CODE (TREE_OPERAND (t, 1)),
13287            RECUR (TREE_OPERAND (t, 2)),
13288            complain);
13289         /* TREE_NO_WARNING must be set if either the expression was
13290            parenthesized or it uses an operator such as >>= rather
13291            than plain assignment.  In the former case, it was already
13292            set and must be copied.  In the latter case,
13293            build_x_modify_expr sets it and it must not be reset
13294            here.  */
13295         if (TREE_NO_WARNING (t))
13296           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13297         return r;
13298       }
13299
13300     case ARROW_EXPR:
13301       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13302                                                 args, complain, in_decl);
13303       /* Remember that there was a reference to this entity.  */
13304       if (DECL_P (op1))
13305         mark_used (op1);
13306       return build_x_arrow (op1);
13307
13308     case NEW_EXPR:
13309       {
13310         tree placement = RECUR (TREE_OPERAND (t, 0));
13311         tree init = RECUR (TREE_OPERAND (t, 3));
13312         VEC(tree,gc) *placement_vec;
13313         VEC(tree,gc) *init_vec;
13314         tree ret;
13315
13316         if (placement == NULL_TREE)
13317           placement_vec = NULL;
13318         else
13319           {
13320             placement_vec = make_tree_vector ();
13321             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13322               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13323           }
13324
13325         /* If there was an initializer in the original tree, but it
13326            instantiated to an empty list, then we should pass a
13327            non-NULL empty vector to tell build_new that it was an
13328            empty initializer() rather than no initializer.  This can
13329            only happen when the initializer is a pack expansion whose
13330            parameter packs are of length zero.  */
13331         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13332           init_vec = NULL;
13333         else
13334           {
13335             init_vec = make_tree_vector ();
13336             if (init == void_zero_node)
13337               gcc_assert (init_vec != NULL);
13338             else
13339               {
13340                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13341                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13342               }
13343           }
13344
13345         ret = build_new (&placement_vec,
13346                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13347                          RECUR (TREE_OPERAND (t, 2)),
13348                          &init_vec,
13349                          NEW_EXPR_USE_GLOBAL (t),
13350                          complain);
13351
13352         if (placement_vec != NULL)
13353           release_tree_vector (placement_vec);
13354         if (init_vec != NULL)
13355           release_tree_vector (init_vec);
13356
13357         return ret;
13358       }
13359
13360     case DELETE_EXPR:
13361      return delete_sanity
13362        (RECUR (TREE_OPERAND (t, 0)),
13363         RECUR (TREE_OPERAND (t, 1)),
13364         DELETE_EXPR_USE_VEC (t),
13365         DELETE_EXPR_USE_GLOBAL (t),
13366         complain);
13367
13368     case COMPOUND_EXPR:
13369       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13370                                     RECUR (TREE_OPERAND (t, 1)),
13371                                     complain);
13372
13373     case CALL_EXPR:
13374       {
13375         tree function;
13376         VEC(tree,gc) *call_args;
13377         unsigned int nargs, i;
13378         bool qualified_p;
13379         bool koenig_p;
13380         tree ret;
13381
13382         function = CALL_EXPR_FN (t);
13383         /* When we parsed the expression,  we determined whether or
13384            not Koenig lookup should be performed.  */
13385         koenig_p = KOENIG_LOOKUP_P (t);
13386         if (TREE_CODE (function) == SCOPE_REF)
13387           {
13388             qualified_p = true;
13389             function = tsubst_qualified_id (function, args, complain, in_decl,
13390                                             /*done=*/false,
13391                                             /*address_p=*/false);
13392           }
13393         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13394           {
13395             /* Do nothing; calling tsubst_copy_and_build on an identifier
13396                would incorrectly perform unqualified lookup again.
13397
13398                Note that we can also have an IDENTIFIER_NODE if the earlier
13399                unqualified lookup found a member function; in that case
13400                koenig_p will be false and we do want to do the lookup
13401                again to find the instantiated member function.
13402
13403                FIXME but doing that causes c++/15272, so we need to stop
13404                using IDENTIFIER_NODE in that situation.  */
13405             qualified_p = false;
13406           }
13407         else
13408           {
13409             if (TREE_CODE (function) == COMPONENT_REF)
13410               {
13411                 tree op = TREE_OPERAND (function, 1);
13412
13413                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13414                                || (BASELINK_P (op)
13415                                    && BASELINK_QUALIFIED_P (op)));
13416               }
13417             else
13418               qualified_p = false;
13419
13420             function = tsubst_copy_and_build (function, args, complain,
13421                                               in_decl,
13422                                               !qualified_p,
13423                                               integral_constant_expression_p);
13424
13425             if (BASELINK_P (function))
13426               qualified_p = true;
13427           }
13428
13429         nargs = call_expr_nargs (t);
13430         call_args = make_tree_vector ();
13431         for (i = 0; i < nargs; ++i)
13432           {
13433             tree arg = CALL_EXPR_ARG (t, i);
13434
13435             if (!PACK_EXPANSION_P (arg))
13436               VEC_safe_push (tree, gc, call_args,
13437                              RECUR (CALL_EXPR_ARG (t, i)));
13438             else
13439               {
13440                 /* Expand the pack expansion and push each entry onto
13441                    CALL_ARGS.  */
13442                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13443                 if (TREE_CODE (arg) == TREE_VEC)
13444                   {
13445                     unsigned int len, j;
13446
13447                     len = TREE_VEC_LENGTH (arg);
13448                     for (j = 0; j < len; ++j)
13449                       {
13450                         tree value = TREE_VEC_ELT (arg, j);
13451                         if (value != NULL_TREE)
13452                           value = convert_from_reference (value);
13453                         VEC_safe_push (tree, gc, call_args, value);
13454                       }
13455                   }
13456                 else
13457                   {
13458                     /* A partial substitution.  Add one entry.  */
13459                     VEC_safe_push (tree, gc, call_args, arg);
13460                   }
13461               }
13462           }
13463
13464         /* We do not perform argument-dependent lookup if normal
13465            lookup finds a non-function, in accordance with the
13466            expected resolution of DR 218.  */
13467         if (koenig_p
13468             && ((is_overloaded_fn (function)
13469                  /* If lookup found a member function, the Koenig lookup is
13470                     not appropriate, even if an unqualified-name was used
13471                     to denote the function.  */
13472                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13473                 || TREE_CODE (function) == IDENTIFIER_NODE)
13474             /* Only do this when substitution turns a dependent call
13475                into a non-dependent call.  */
13476             && type_dependent_expression_p_push (t)
13477             && !any_type_dependent_arguments_p (call_args))
13478           function = perform_koenig_lookup (function, call_args, false,
13479                                             tf_none);
13480
13481         if (TREE_CODE (function) == IDENTIFIER_NODE
13482             && !any_type_dependent_arguments_p (call_args))
13483           {
13484             if (koenig_p && (complain & tf_warning_or_error))
13485               {
13486                 /* For backwards compatibility and good diagnostics, try
13487                    the unqualified lookup again if we aren't in SFINAE
13488                    context.  */
13489                 tree unq = (tsubst_copy_and_build
13490                             (function, args, complain, in_decl, true,
13491                              integral_constant_expression_p));
13492                 if (unq != function)
13493                   {
13494                     tree fn = unq;
13495                     if (TREE_CODE (fn) == COMPONENT_REF)
13496                       fn = TREE_OPERAND (fn, 1);
13497                     if (is_overloaded_fn (fn))
13498                       fn = get_first_fn (fn);
13499                     permerror (EXPR_LOC_OR_HERE (t),
13500                                "%qD was not declared in this scope, "
13501                                "and no declarations were found by "
13502                                "argument-dependent lookup at the point "
13503                                "of instantiation", function);
13504                     if (DECL_CLASS_SCOPE_P (fn))
13505                       {
13506                         inform (EXPR_LOC_OR_HERE (t),
13507                                 "declarations in dependent base %qT are "
13508                                 "not found by unqualified lookup",
13509                                 DECL_CLASS_CONTEXT (fn));
13510                         if (current_class_ptr)
13511                           inform (EXPR_LOC_OR_HERE (t),
13512                                   "use %<this->%D%> instead", function);
13513                         else
13514                           inform (EXPR_LOC_OR_HERE (t),
13515                                   "use %<%T::%D%> instead",
13516                                   current_class_name, function);
13517                       }
13518                     else
13519                       inform (0, "%q+D declared here, later in the "
13520                                 "translation unit", fn);
13521                     function = unq;
13522                   }
13523               }
13524             if (TREE_CODE (function) == IDENTIFIER_NODE)
13525               {
13526                 unqualified_name_lookup_error (function);
13527                 release_tree_vector (call_args);
13528                 return error_mark_node;
13529               }
13530           }
13531
13532         /* Remember that there was a reference to this entity.  */
13533         if (DECL_P (function))
13534           mark_used (function);
13535
13536         if (TREE_CODE (function) == OFFSET_REF)
13537           ret = build_offset_ref_call_from_tree (function, &call_args);
13538         else if (TREE_CODE (function) == COMPONENT_REF)
13539           {
13540             tree instance = TREE_OPERAND (function, 0);
13541             tree fn = TREE_OPERAND (function, 1);
13542
13543             if (processing_template_decl
13544                 && (type_dependent_expression_p (instance)
13545                     || (!BASELINK_P (fn)
13546                         && TREE_CODE (fn) != FIELD_DECL)
13547                     || type_dependent_expression_p (fn)
13548                     || any_type_dependent_arguments_p (call_args)))
13549               ret = build_nt_call_vec (function, call_args);
13550             else if (!BASELINK_P (fn))
13551               ret = finish_call_expr (function, &call_args,
13552                                        /*disallow_virtual=*/false,
13553                                        /*koenig_p=*/false,
13554                                        complain);
13555             else
13556               ret = (build_new_method_call
13557                       (instance, fn,
13558                        &call_args, NULL_TREE,
13559                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13560                        /*fn_p=*/NULL,
13561                        complain));
13562           }
13563         else
13564           ret = finish_call_expr (function, &call_args,
13565                                   /*disallow_virtual=*/qualified_p,
13566                                   koenig_p,
13567                                   complain);
13568
13569         release_tree_vector (call_args);
13570
13571         return ret;
13572       }
13573
13574     case COND_EXPR:
13575       return build_x_conditional_expr
13576         (RECUR (TREE_OPERAND (t, 0)),
13577          RECUR (TREE_OPERAND (t, 1)),
13578          RECUR (TREE_OPERAND (t, 2)),
13579          complain);
13580
13581     case PSEUDO_DTOR_EXPR:
13582       return finish_pseudo_destructor_expr
13583         (RECUR (TREE_OPERAND (t, 0)),
13584          RECUR (TREE_OPERAND (t, 1)),
13585          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13586
13587     case TREE_LIST:
13588       {
13589         tree purpose, value, chain;
13590
13591         if (t == void_list_node)
13592           return t;
13593
13594         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13595             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13596           {
13597             /* We have pack expansions, so expand those and
13598                create a new list out of it.  */
13599             tree purposevec = NULL_TREE;
13600             tree valuevec = NULL_TREE;
13601             tree chain;
13602             int i, len = -1;
13603
13604             /* Expand the argument expressions.  */
13605             if (TREE_PURPOSE (t))
13606               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13607                                                  complain, in_decl);
13608             if (TREE_VALUE (t))
13609               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13610                                                complain, in_decl);
13611
13612             /* Build the rest of the list.  */
13613             chain = TREE_CHAIN (t);
13614             if (chain && chain != void_type_node)
13615               chain = RECUR (chain);
13616
13617             /* Determine the number of arguments.  */
13618             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13619               {
13620                 len = TREE_VEC_LENGTH (purposevec);
13621                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13622               }
13623             else if (TREE_CODE (valuevec) == TREE_VEC)
13624               len = TREE_VEC_LENGTH (valuevec);
13625             else
13626               {
13627                 /* Since we only performed a partial substitution into
13628                    the argument pack, we only return a single list
13629                    node.  */
13630                 if (purposevec == TREE_PURPOSE (t)
13631                     && valuevec == TREE_VALUE (t)
13632                     && chain == TREE_CHAIN (t))
13633                   return t;
13634
13635                 return tree_cons (purposevec, valuevec, chain);
13636               }
13637             
13638             /* Convert the argument vectors into a TREE_LIST */
13639             i = len;
13640             while (i > 0)
13641               {
13642                 /* Grab the Ith values.  */
13643                 i--;
13644                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13645                                      : NULL_TREE;
13646                 value 
13647                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13648                              : NULL_TREE;
13649
13650                 /* Build the list (backwards).  */
13651                 chain = tree_cons (purpose, value, chain);
13652               }
13653
13654             return chain;
13655           }
13656
13657         purpose = TREE_PURPOSE (t);
13658         if (purpose)
13659           purpose = RECUR (purpose);
13660         value = TREE_VALUE (t);
13661         if (value)
13662           value = RECUR (value);
13663         chain = TREE_CHAIN (t);
13664         if (chain && chain != void_type_node)
13665           chain = RECUR (chain);
13666         if (purpose == TREE_PURPOSE (t)
13667             && value == TREE_VALUE (t)
13668             && chain == TREE_CHAIN (t))
13669           return t;
13670         return tree_cons (purpose, value, chain);
13671       }
13672
13673     case COMPONENT_REF:
13674       {
13675         tree object;
13676         tree object_type;
13677         tree member;
13678
13679         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13680                                                      args, complain, in_decl);
13681         /* Remember that there was a reference to this entity.  */
13682         if (DECL_P (object))
13683           mark_used (object);
13684         object_type = TREE_TYPE (object);
13685
13686         member = TREE_OPERAND (t, 1);
13687         if (BASELINK_P (member))
13688           member = tsubst_baselink (member,
13689                                     non_reference (TREE_TYPE (object)),
13690                                     args, complain, in_decl);
13691         else
13692           member = tsubst_copy (member, args, complain, in_decl);
13693         if (member == error_mark_node)
13694           return error_mark_node;
13695
13696         if (object_type && !CLASS_TYPE_P (object_type))
13697           {
13698             if (SCALAR_TYPE_P (object_type))
13699               {
13700                 tree s = NULL_TREE;
13701                 tree dtor = member;
13702
13703                 if (TREE_CODE (dtor) == SCOPE_REF)
13704                   {
13705                     s = TREE_OPERAND (dtor, 0);
13706                     dtor = TREE_OPERAND (dtor, 1);
13707                   }
13708                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13709                   {
13710                     dtor = TREE_OPERAND (dtor, 0);
13711                     if (TYPE_P (dtor))
13712                       return finish_pseudo_destructor_expr (object, s, dtor);
13713                   }
13714               }
13715           }
13716         else if (TREE_CODE (member) == SCOPE_REF
13717                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13718           {
13719             tree tmpl;
13720             tree args;
13721
13722             /* Lookup the template functions now that we know what the
13723                scope is.  */
13724             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13725             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13726             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13727                                             /*is_type_p=*/false,
13728                                             /*complain=*/false);
13729             if (BASELINK_P (member))
13730               {
13731                 BASELINK_FUNCTIONS (member)
13732                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13733                               args);
13734                 member = (adjust_result_of_qualified_name_lookup
13735                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13736                            object_type));
13737               }
13738             else
13739               {
13740                 qualified_name_lookup_error (object_type, tmpl, member,
13741                                              input_location);
13742                 return error_mark_node;
13743               }
13744           }
13745         else if (TREE_CODE (member) == SCOPE_REF
13746                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13747                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13748           {
13749             if (complain & tf_error)
13750               {
13751                 if (TYPE_P (TREE_OPERAND (member, 0)))
13752                   error ("%qT is not a class or namespace",
13753                          TREE_OPERAND (member, 0));
13754                 else
13755                   error ("%qD is not a class or namespace",
13756                          TREE_OPERAND (member, 0));
13757               }
13758             return error_mark_node;
13759           }
13760         else if (TREE_CODE (member) == FIELD_DECL)
13761           return finish_non_static_data_member (member, object, NULL_TREE);
13762
13763         return finish_class_member_access_expr (object, member,
13764                                                 /*template_p=*/false,
13765                                                 complain);
13766       }
13767
13768     case THROW_EXPR:
13769       return build_throw
13770         (RECUR (TREE_OPERAND (t, 0)));
13771
13772     case CONSTRUCTOR:
13773       {
13774         VEC(constructor_elt,gc) *n;
13775         constructor_elt *ce;
13776         unsigned HOST_WIDE_INT idx;
13777         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13778         bool process_index_p;
13779         int newlen;
13780         bool need_copy_p = false;
13781         tree r;
13782
13783         if (type == error_mark_node)
13784           return error_mark_node;
13785
13786         /* digest_init will do the wrong thing if we let it.  */
13787         if (type && TYPE_PTRMEMFUNC_P (type))
13788           return t;
13789
13790         /* We do not want to process the index of aggregate
13791            initializers as they are identifier nodes which will be
13792            looked up by digest_init.  */
13793         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13794
13795         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13796         newlen = VEC_length (constructor_elt, n);
13797         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13798           {
13799             if (ce->index && process_index_p)
13800               ce->index = RECUR (ce->index);
13801
13802             if (PACK_EXPANSION_P (ce->value))
13803               {
13804                 /* Substitute into the pack expansion.  */
13805                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13806                                                   in_decl);
13807
13808                 if (ce->value == error_mark_node
13809                     || PACK_EXPANSION_P (ce->value))
13810                   ;
13811                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13812                   /* Just move the argument into place.  */
13813                   ce->value = TREE_VEC_ELT (ce->value, 0);
13814                 else
13815                   {
13816                     /* Update the length of the final CONSTRUCTOR
13817                        arguments vector, and note that we will need to
13818                        copy.*/
13819                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13820                     need_copy_p = true;
13821                   }
13822               }
13823             else
13824               ce->value = RECUR (ce->value);
13825           }
13826
13827         if (need_copy_p)
13828           {
13829             VEC(constructor_elt,gc) *old_n = n;
13830
13831             n = VEC_alloc (constructor_elt, gc, newlen);
13832             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13833               {
13834                 if (TREE_CODE (ce->value) == TREE_VEC)
13835                   {
13836                     int i, len = TREE_VEC_LENGTH (ce->value);
13837                     for (i = 0; i < len; ++i)
13838                       CONSTRUCTOR_APPEND_ELT (n, 0,
13839                                               TREE_VEC_ELT (ce->value, i));
13840                   }
13841                 else
13842                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13843               }
13844           }
13845
13846         r = build_constructor (init_list_type_node, n);
13847         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13848
13849         if (TREE_HAS_CONSTRUCTOR (t))
13850           return finish_compound_literal (type, r, complain);
13851
13852         TREE_TYPE (r) = type;
13853         return r;
13854       }
13855
13856     case TYPEID_EXPR:
13857       {
13858         tree operand_0 = TREE_OPERAND (t, 0);
13859         if (TYPE_P (operand_0))
13860           {
13861             operand_0 = tsubst (operand_0, args, complain, in_decl);
13862             return get_typeid (operand_0);
13863           }
13864         else
13865           {
13866             operand_0 = RECUR (operand_0);
13867             return build_typeid (operand_0);
13868           }
13869       }
13870
13871     case VAR_DECL:
13872       if (!args)
13873         return t;
13874       /* Fall through */
13875
13876     case PARM_DECL:
13877       {
13878         tree r = tsubst_copy (t, args, complain, in_decl);
13879
13880         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13881           /* If the original type was a reference, we'll be wrapped in
13882              the appropriate INDIRECT_REF.  */
13883           r = convert_from_reference (r);
13884         return r;
13885       }
13886
13887     case VA_ARG_EXPR:
13888       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13889                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13890
13891     case OFFSETOF_EXPR:
13892       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13893
13894     case TRAIT_EXPR:
13895       {
13896         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13897                                   complain, in_decl);
13898
13899         tree type2 = TRAIT_EXPR_TYPE2 (t);
13900         if (type2)
13901           type2 = tsubst_copy (type2, args, complain, in_decl);
13902         
13903         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13904       }
13905
13906     case STMT_EXPR:
13907       {
13908         tree old_stmt_expr = cur_stmt_expr;
13909         tree stmt_expr = begin_stmt_expr ();
13910
13911         cur_stmt_expr = stmt_expr;
13912         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13913                      integral_constant_expression_p);
13914         stmt_expr = finish_stmt_expr (stmt_expr, false);
13915         cur_stmt_expr = old_stmt_expr;
13916
13917         /* If the resulting list of expression statement is empty,
13918            fold it further into void_zero_node.  */
13919         if (empty_expr_stmt_p (stmt_expr))
13920           stmt_expr = void_zero_node;
13921
13922         return stmt_expr;
13923       }
13924
13925     case CONST_DECL:
13926       t = tsubst_copy (t, args, complain, in_decl);
13927       /* As in finish_id_expression, we resolve enumeration constants
13928          to their underlying values.  */
13929       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
13930         {
13931           used_types_insert (TREE_TYPE (t));
13932           return DECL_INITIAL (t);
13933         }
13934       return t;
13935
13936     case LAMBDA_EXPR:
13937       {
13938         tree r = build_lambda_expr ();
13939
13940         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
13941         LAMBDA_EXPR_CLOSURE (r) = type;
13942         CLASSTYPE_LAMBDA_EXPR (type) = r;
13943
13944         LAMBDA_EXPR_LOCATION (r)
13945           = LAMBDA_EXPR_LOCATION (t);
13946         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13947           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13948         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13949         LAMBDA_EXPR_DISCRIMINATOR (r)
13950           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13951         LAMBDA_EXPR_EXTRA_SCOPE (r)
13952           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13953         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
13954           {
13955             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
13956             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
13957           }
13958         else
13959           LAMBDA_EXPR_RETURN_TYPE (r)
13960             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13961
13962         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13963                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13964
13965         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13966         determine_visibility (TYPE_NAME (type));
13967         /* Now that we know visibility, instantiate the type so we have a
13968            declaration of the op() for later calls to lambda_function.  */
13969         complete_type (type);
13970
13971         /* The capture list refers to closure members, so this needs to
13972            wait until after we finish instantiating the type.  */
13973         LAMBDA_EXPR_CAPTURE_LIST (r)
13974           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13975
13976         return build_lambda_object (r);
13977       }
13978
13979     case TARGET_EXPR:
13980       /* We can get here for a constant initializer of non-dependent type.
13981          FIXME stop folding in cp_parser_initializer_clause.  */
13982       gcc_assert (TREE_CONSTANT (t));
13983       {
13984         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13985         TREE_CONSTANT (r) = true;
13986         return r;
13987       }
13988
13989     default:
13990       /* Handle Objective-C++ constructs, if appropriate.  */
13991       {
13992         tree subst
13993           = objcp_tsubst_copy_and_build (t, args, complain,
13994                                          in_decl, /*function_p=*/false);
13995         if (subst)
13996           return subst;
13997       }
13998       return tsubst_copy (t, args, complain, in_decl);
13999     }
14000
14001 #undef RECUR
14002 }
14003
14004 /* Verify that the instantiated ARGS are valid. For type arguments,
14005    make sure that the type's linkage is ok. For non-type arguments,
14006    make sure they are constants if they are integral or enumerations.
14007    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14008
14009 static bool
14010 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14011 {
14012   if (ARGUMENT_PACK_P (t))
14013     {
14014       tree vec = ARGUMENT_PACK_ARGS (t);
14015       int len = TREE_VEC_LENGTH (vec);
14016       bool result = false;
14017       int i;
14018
14019       for (i = 0; i < len; ++i)
14020         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14021           result = true;
14022       return result;
14023     }
14024   else if (TYPE_P (t))
14025     {
14026       /* [basic.link]: A name with no linkage (notably, the name
14027          of a class or enumeration declared in a local scope)
14028          shall not be used to declare an entity with linkage.
14029          This implies that names with no linkage cannot be used as
14030          template arguments
14031
14032          DR 757 relaxes this restriction for C++0x.  */
14033       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14034                  : no_linkage_check (t, /*relaxed_p=*/false));
14035
14036       if (nt)
14037         {
14038           /* DR 488 makes use of a type with no linkage cause
14039              type deduction to fail.  */
14040           if (complain & tf_error)
14041             {
14042               if (TYPE_ANONYMOUS_P (nt))
14043                 error ("%qT is/uses anonymous type", t);
14044               else
14045                 error ("template argument for %qD uses local type %qT",
14046                        tmpl, t);
14047             }
14048           return true;
14049         }
14050       /* In order to avoid all sorts of complications, we do not
14051          allow variably-modified types as template arguments.  */
14052       else if (variably_modified_type_p (t, NULL_TREE))
14053         {
14054           if (complain & tf_error)
14055             error ("%qT is a variably modified type", t);
14056           return true;
14057         }
14058     }
14059   /* A non-type argument of integral or enumerated type must be a
14060      constant.  */
14061   else if (TREE_TYPE (t)
14062            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14063            && !TREE_CONSTANT (t))
14064     {
14065       if (complain & tf_error)
14066         error ("integral expression %qE is not constant", t);
14067       return true;
14068     }
14069   return false;
14070 }
14071
14072 static bool
14073 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14074 {
14075   int ix, len = DECL_NTPARMS (tmpl);
14076   bool result = false;
14077
14078   for (ix = 0; ix != len; ix++)
14079     {
14080       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14081         result = true;
14082     }
14083   if (result && (complain & tf_error))
14084     error ("  trying to instantiate %qD", tmpl);
14085   return result;
14086 }
14087
14088 /* In C++0x, it's possible to have a function template whose type depends
14089    on itself recursively.  This is most obvious with decltype, but can also
14090    occur with enumeration scope (c++/48969).  So we need to catch infinite
14091    recursion and reject the substitution at deduction time; this function
14092    will return error_mark_node for any repeated substitution.
14093
14094    This also catches excessive recursion such as when f<N> depends on
14095    f<N-1> across all integers, and returns error_mark_node for all the
14096    substitutions back up to the initial one.
14097
14098    This is, of course, not reentrant.  */
14099
14100 static tree
14101 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14102 {
14103   static bool excessive_deduction_depth;
14104   static int deduction_depth;
14105   struct pending_template *old_last_pend = last_pending_template;
14106   struct tinst_level *old_error_tinst = last_error_tinst_level;
14107
14108   tree fntype = TREE_TYPE (fn);
14109   tree tinst;
14110   tree r;
14111
14112   if (excessive_deduction_depth)
14113     return error_mark_node;
14114
14115   tinst = build_tree_list (fn, targs);
14116   if (!push_tinst_level (tinst))
14117     {
14118       excessive_deduction_depth = true;
14119       ggc_free (tinst);
14120       return error_mark_node;
14121     }
14122
14123   input_location = DECL_SOURCE_LOCATION (fn);
14124   ++deduction_depth;
14125   push_deduction_access_scope (fn);
14126   r = tsubst (fntype, targs, complain, NULL_TREE);
14127   pop_deduction_access_scope (fn);
14128   --deduction_depth;
14129
14130   if (excessive_deduction_depth)
14131     {
14132       r = error_mark_node;
14133       if (deduction_depth == 0)
14134         /* Reset once we're all the way out.  */
14135         excessive_deduction_depth = false;
14136     }
14137
14138   pop_tinst_level ();
14139   /* We can't free this if a pending_template entry or last_error_tinst_level
14140      is pointing at it.  */
14141   if (last_pending_template == old_last_pend
14142       && last_error_tinst_level == old_error_tinst)
14143     ggc_free (tinst);
14144   return r;
14145 }
14146
14147 /* Instantiate the indicated variable or function template TMPL with
14148    the template arguments in TARG_PTR.  */
14149
14150 static tree
14151 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14152 {
14153   tree targ_ptr = orig_args;
14154   tree fndecl;
14155   tree gen_tmpl;
14156   tree spec;
14157   HOST_WIDE_INT saved_processing_template_decl;
14158
14159   if (tmpl == error_mark_node)
14160     return error_mark_node;
14161
14162   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14163
14164   /* If this function is a clone, handle it specially.  */
14165   if (DECL_CLONED_FUNCTION_P (tmpl))
14166     {
14167       tree spec;
14168       tree clone;
14169
14170       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14171          DECL_CLONED_FUNCTION.  */
14172       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14173                                    targ_ptr, complain);
14174       if (spec == error_mark_node)
14175         return error_mark_node;
14176
14177       /* Look for the clone.  */
14178       FOR_EACH_CLONE (clone, spec)
14179         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14180           return clone;
14181       /* We should always have found the clone by now.  */
14182       gcc_unreachable ();
14183       return NULL_TREE;
14184     }
14185
14186   /* Check to see if we already have this specialization.  */
14187   gen_tmpl = most_general_template (tmpl);
14188   if (tmpl != gen_tmpl)
14189     /* The TMPL is a partial instantiation.  To get a full set of
14190        arguments we must add the arguments used to perform the
14191        partial instantiation.  */
14192     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14193                                             targ_ptr);
14194
14195   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14196      but it doesn't seem to be on the hot path.  */
14197   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14198
14199   gcc_assert (tmpl == gen_tmpl
14200               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14201                   == spec)
14202               || fndecl == NULL_TREE);
14203
14204   if (spec != NULL_TREE)
14205     return spec;
14206
14207   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14208                                complain))
14209     return error_mark_node;
14210
14211   /* We are building a FUNCTION_DECL, during which the access of its
14212      parameters and return types have to be checked.  However this
14213      FUNCTION_DECL which is the desired context for access checking
14214      is not built yet.  We solve this chicken-and-egg problem by
14215      deferring all checks until we have the FUNCTION_DECL.  */
14216   push_deferring_access_checks (dk_deferred);
14217
14218   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14219      (because, for example, we have encountered a non-dependent
14220      function call in the body of a template function and must now
14221      determine which of several overloaded functions will be called),
14222      within the instantiation itself we are not processing a
14223      template.  */  
14224   saved_processing_template_decl = processing_template_decl;
14225   processing_template_decl = 0;
14226   /* Substitute template parameters to obtain the specialization.  */
14227   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14228                    targ_ptr, complain, gen_tmpl);
14229   processing_template_decl = saved_processing_template_decl;
14230   if (fndecl == error_mark_node)
14231     return error_mark_node;
14232
14233   /* Now we know the specialization, compute access previously
14234      deferred.  */
14235   push_access_scope (fndecl);
14236
14237   /* Some typedefs referenced from within the template code need to be access
14238      checked at template instantiation time, i.e now. These types were
14239      added to the template at parsing time. Let's get those and perfom
14240      the acces checks then.  */
14241   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14242   perform_deferred_access_checks ();
14243   pop_access_scope (fndecl);
14244   pop_deferring_access_checks ();
14245
14246   /* The DECL_TI_TEMPLATE should always be the immediate parent
14247      template, not the most general template.  */
14248   DECL_TI_TEMPLATE (fndecl) = tmpl;
14249
14250   /* If we've just instantiated the main entry point for a function,
14251      instantiate all the alternate entry points as well.  We do this
14252      by cloning the instantiation of the main entry point, not by
14253      instantiating the template clones.  */
14254   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14255     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14256
14257   return fndecl;
14258 }
14259
14260 /* Wrapper for instantiate_template_1.  */
14261
14262 tree
14263 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14264 {
14265   tree ret;
14266   timevar_push (TV_TEMPLATE_INST);
14267   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14268   timevar_pop (TV_TEMPLATE_INST);
14269   return ret;
14270 }
14271
14272 /* We're going to do deduction substitution on the type of TMPL, a function
14273    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14274    disable access checking.  */
14275
14276 static void
14277 push_deduction_access_scope (tree tmpl)
14278 {
14279   if (cxx_dialect >= cxx0x)
14280     {
14281       int ptd = processing_template_decl;
14282       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14283       /* Preserve processing_template_decl across push_to_top_level.  */
14284       if (ptd && !processing_template_decl)
14285         ++processing_template_decl;
14286     }
14287   else
14288     push_deferring_access_checks (dk_no_check);
14289 }
14290
14291 /* And pop back out.  */
14292
14293 static void
14294 pop_deduction_access_scope (tree tmpl)
14295 {
14296   if (cxx_dialect >= cxx0x)
14297     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14298   else
14299     pop_deferring_access_checks ();
14300 }
14301
14302 /* PARM is a template parameter pack for FN.  Returns true iff
14303    PARM is used in a deducible way in the argument list of FN.  */
14304
14305 static bool
14306 pack_deducible_p (tree parm, tree fn)
14307 {
14308   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14309   for (; t; t = TREE_CHAIN (t))
14310     {
14311       tree type = TREE_VALUE (t);
14312       tree packs;
14313       if (!PACK_EXPANSION_P (type))
14314         continue;
14315       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14316            packs; packs = TREE_CHAIN (packs))
14317         if (TREE_VALUE (packs) == parm)
14318           {
14319             /* The template parameter pack is used in a function parameter
14320                pack.  If this is the end of the parameter list, the
14321                template parameter pack is deducible.  */
14322             if (TREE_CHAIN (t) == void_list_node)
14323               return true;
14324             else
14325               /* Otherwise, not.  Well, it could be deduced from
14326                  a non-pack parameter, but doing so would end up with
14327                  a deduction mismatch, so don't bother.  */
14328               return false;
14329           }
14330     }
14331   /* The template parameter pack isn't used in any function parameter
14332      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14333   return true;
14334 }
14335
14336 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14337    NARGS elements of the arguments that are being used when calling
14338    it.  TARGS is a vector into which the deduced template arguments
14339    are placed.
14340
14341    Return zero for success, 2 for an incomplete match that doesn't resolve
14342    all the types, and 1 for complete failure.  An error message will be
14343    printed only for an incomplete match.
14344
14345    If FN is a conversion operator, or we are trying to produce a specific
14346    specialization, RETURN_TYPE is the return type desired.
14347
14348    The EXPLICIT_TARGS are explicit template arguments provided via a
14349    template-id.
14350
14351    The parameter STRICT is one of:
14352
14353    DEDUCE_CALL:
14354      We are deducing arguments for a function call, as in
14355      [temp.deduct.call].
14356
14357    DEDUCE_CONV:
14358      We are deducing arguments for a conversion function, as in
14359      [temp.deduct.conv].
14360
14361    DEDUCE_EXACT:
14362      We are deducing arguments when doing an explicit instantiation
14363      as in [temp.explicit], when determining an explicit specialization
14364      as in [temp.expl.spec], or when taking the address of a function
14365      template, as in [temp.deduct.funcaddr].  */
14366
14367 int
14368 fn_type_unification (tree fn,
14369                      tree explicit_targs,
14370                      tree targs,
14371                      const tree *args,
14372                      unsigned int nargs,
14373                      tree return_type,
14374                      unification_kind_t strict,
14375                      int flags,
14376                      bool explain_p)
14377 {
14378   tree parms;
14379   tree fntype;
14380   int result;
14381
14382   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14383
14384   fntype = TREE_TYPE (fn);
14385   if (explicit_targs)
14386     {
14387       /* [temp.deduct]
14388
14389          The specified template arguments must match the template
14390          parameters in kind (i.e., type, nontype, template), and there
14391          must not be more arguments than there are parameters;
14392          otherwise type deduction fails.
14393
14394          Nontype arguments must match the types of the corresponding
14395          nontype template parameters, or must be convertible to the
14396          types of the corresponding nontype parameters as specified in
14397          _temp.arg.nontype_, otherwise type deduction fails.
14398
14399          All references in the function type of the function template
14400          to the corresponding template parameters are replaced by the
14401          specified template argument values.  If a substitution in a
14402          template parameter or in the function type of the function
14403          template results in an invalid type, type deduction fails.  */
14404       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14405       int i, len = TREE_VEC_LENGTH (tparms);
14406       tree converted_args;
14407       bool incomplete = false;
14408
14409       if (explicit_targs == error_mark_node)
14410         return unify_invalid (explain_p);
14411
14412       converted_args
14413         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14414                                   (explain_p
14415                                    ? tf_warning_or_error
14416                                    : tf_none),
14417                                    /*require_all_args=*/false,
14418                                    /*use_default_args=*/false));
14419       if (converted_args == error_mark_node)
14420         return 1;
14421
14422       /* Substitute the explicit args into the function type.  This is
14423          necessary so that, for instance, explicitly declared function
14424          arguments can match null pointed constants.  If we were given
14425          an incomplete set of explicit args, we must not do semantic
14426          processing during substitution as we could create partial
14427          instantiations.  */
14428       for (i = 0; i < len; i++)
14429         {
14430           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14431           bool parameter_pack = false;
14432           tree targ = TREE_VEC_ELT (converted_args, i);
14433
14434           /* Dig out the actual parm.  */
14435           if (TREE_CODE (parm) == TYPE_DECL
14436               || TREE_CODE (parm) == TEMPLATE_DECL)
14437             {
14438               parm = TREE_TYPE (parm);
14439               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14440             }
14441           else if (TREE_CODE (parm) == PARM_DECL)
14442             {
14443               parm = DECL_INITIAL (parm);
14444               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14445             }
14446
14447           if (!parameter_pack && targ == NULL_TREE)
14448             /* No explicit argument for this template parameter.  */
14449             incomplete = true;
14450
14451           if (parameter_pack && pack_deducible_p (parm, fn))
14452             {
14453               /* Mark the argument pack as "incomplete". We could
14454                  still deduce more arguments during unification.
14455                  We remove this mark in type_unification_real.  */
14456               if (targ)
14457                 {
14458                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14459                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14460                     = ARGUMENT_PACK_ARGS (targ);
14461                 }
14462
14463               /* We have some incomplete argument packs.  */
14464               incomplete = true;
14465             }
14466         }
14467
14468       processing_template_decl += incomplete;
14469       fntype = deduction_tsubst_fntype (fn, converted_args,
14470                                         (explain_p
14471                                          ? tf_warning_or_error
14472                                          : tf_none));
14473       processing_template_decl -= incomplete;
14474
14475       if (fntype == error_mark_node)
14476         return 1;
14477
14478       /* Place the explicitly specified arguments in TARGS.  */
14479       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14480         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14481     }
14482
14483   /* Never do unification on the 'this' parameter.  */
14484   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14485
14486   if (return_type)
14487     {
14488       tree *new_args;
14489
14490       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14491       new_args = XALLOCAVEC (tree, nargs + 1);
14492       new_args[0] = return_type;
14493       memcpy (new_args + 1, args, nargs * sizeof (tree));
14494       args = new_args;
14495       ++nargs;
14496     }
14497
14498   /* We allow incomplete unification without an error message here
14499      because the standard doesn't seem to explicitly prohibit it.  Our
14500      callers must be ready to deal with unification failures in any
14501      event.  */
14502   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14503                                   targs, parms, args, nargs, /*subr=*/0,
14504                                   strict, flags, explain_p);
14505
14506   /* Now that we have bindings for all of the template arguments,
14507      ensure that the arguments deduced for the template template
14508      parameters have compatible template parameter lists.  We cannot
14509      check this property before we have deduced all template
14510      arguments, because the template parameter types of a template
14511      template parameter might depend on prior template parameters
14512      deduced after the template template parameter.  The following
14513      ill-formed example illustrates this issue:
14514
14515        template<typename T, template<T> class C> void f(C<5>, T);
14516
14517        template<int N> struct X {};
14518
14519        void g() {
14520          f(X<5>(), 5l); // error: template argument deduction fails
14521        }
14522
14523      The template parameter list of 'C' depends on the template type
14524      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14525      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14526      time that we deduce 'C'.  */
14527   if (result == 0
14528       && !template_template_parm_bindings_ok_p 
14529            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14530     return unify_inconsistent_template_template_parameters (explain_p);
14531
14532   if (result == 0)
14533     /* All is well so far.  Now, check:
14534
14535        [temp.deduct]
14536
14537        When all template arguments have been deduced, all uses of
14538        template parameters in nondeduced contexts are replaced with
14539        the corresponding deduced argument values.  If the
14540        substitution results in an invalid type, as described above,
14541        type deduction fails.  */
14542     {
14543       tree substed = deduction_tsubst_fntype (fn, targs,
14544                                               (explain_p
14545                                                ? tf_warning_or_error
14546                                                : tf_none));
14547       if (substed == error_mark_node)
14548         return 1;
14549
14550       /* If we're looking for an exact match, check that what we got
14551          is indeed an exact match.  It might not be if some template
14552          parameters are used in non-deduced contexts.  */
14553       if (strict == DEDUCE_EXACT)
14554         {
14555           unsigned int i;
14556
14557           tree sarg
14558             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14559           if (return_type)
14560             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14561           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14562             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14563               return unify_type_mismatch (explain_p, args[i],
14564                                           TREE_VALUE (sarg));
14565         }
14566     }
14567
14568   return result;
14569 }
14570
14571 /* Adjust types before performing type deduction, as described in
14572    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14573    sections are symmetric.  PARM is the type of a function parameter
14574    or the return type of the conversion function.  ARG is the type of
14575    the argument passed to the call, or the type of the value
14576    initialized with the result of the conversion function.
14577    ARG_EXPR is the original argument expression, which may be null.  */
14578
14579 static int
14580 maybe_adjust_types_for_deduction (unification_kind_t strict,
14581                                   tree* parm,
14582                                   tree* arg,
14583                                   tree arg_expr)
14584 {
14585   int result = 0;
14586
14587   switch (strict)
14588     {
14589     case DEDUCE_CALL:
14590       break;
14591
14592     case DEDUCE_CONV:
14593       {
14594         /* Swap PARM and ARG throughout the remainder of this
14595            function; the handling is precisely symmetric since PARM
14596            will initialize ARG rather than vice versa.  */
14597         tree* temp = parm;
14598         parm = arg;
14599         arg = temp;
14600         break;
14601       }
14602
14603     case DEDUCE_EXACT:
14604       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14605          too, but here handle it by stripping the reference from PARM
14606          rather than by adding it to ARG.  */
14607       if (TREE_CODE (*parm) == REFERENCE_TYPE
14608           && TYPE_REF_IS_RVALUE (*parm)
14609           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14610           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14611           && TREE_CODE (*arg) == REFERENCE_TYPE
14612           && !TYPE_REF_IS_RVALUE (*arg))
14613         *parm = TREE_TYPE (*parm);
14614       /* Nothing else to do in this case.  */
14615       return 0;
14616
14617     default:
14618       gcc_unreachable ();
14619     }
14620
14621   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14622     {
14623       /* [temp.deduct.call]
14624
14625          If P is not a reference type:
14626
14627          --If A is an array type, the pointer type produced by the
14628          array-to-pointer standard conversion (_conv.array_) is
14629          used in place of A for type deduction; otherwise,
14630
14631          --If A is a function type, the pointer type produced by
14632          the function-to-pointer standard conversion
14633          (_conv.func_) is used in place of A for type deduction;
14634          otherwise,
14635
14636          --If A is a cv-qualified type, the top level
14637          cv-qualifiers of A's type are ignored for type
14638          deduction.  */
14639       if (TREE_CODE (*arg) == ARRAY_TYPE)
14640         *arg = build_pointer_type (TREE_TYPE (*arg));
14641       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14642         *arg = build_pointer_type (*arg);
14643       else
14644         *arg = TYPE_MAIN_VARIANT (*arg);
14645     }
14646
14647   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14648      of the form T&&, where T is a template parameter, and the argument
14649      is an lvalue, T is deduced as A& */
14650   if (TREE_CODE (*parm) == REFERENCE_TYPE
14651       && TYPE_REF_IS_RVALUE (*parm)
14652       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14653       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14654       && (arg_expr ? real_lvalue_p (arg_expr)
14655           /* try_one_overload doesn't provide an arg_expr, but
14656              functions are always lvalues.  */
14657           : TREE_CODE (*arg) == FUNCTION_TYPE))
14658     *arg = build_reference_type (*arg);
14659
14660   /* [temp.deduct.call]
14661
14662      If P is a cv-qualified type, the top level cv-qualifiers
14663      of P's type are ignored for type deduction.  If P is a
14664      reference type, the type referred to by P is used for
14665      type deduction.  */
14666   *parm = TYPE_MAIN_VARIANT (*parm);
14667   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14668     {
14669       *parm = TREE_TYPE (*parm);
14670       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14671     }
14672
14673   /* DR 322. For conversion deduction, remove a reference type on parm
14674      too (which has been swapped into ARG).  */
14675   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14676     *arg = TREE_TYPE (*arg);
14677
14678   return result;
14679 }
14680
14681 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14682    template which does contain any deducible template parameters; check if
14683    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14684    unify_one_argument.  */
14685
14686 static int
14687 check_non_deducible_conversion (tree parm, tree arg, int strict,
14688                                 int flags, bool explain_p)
14689 {
14690   tree type;
14691
14692   if (!TYPE_P (arg))
14693     type = TREE_TYPE (arg);
14694   else
14695     type = arg;
14696
14697   if (same_type_p (parm, type))
14698     return unify_success (explain_p);
14699
14700   if (strict == DEDUCE_CONV)
14701     {
14702       if (can_convert_arg (type, parm, NULL_TREE, flags))
14703         return unify_success (explain_p);
14704     }
14705   else if (strict != DEDUCE_EXACT)
14706     {
14707       if (can_convert_arg (parm, type,
14708                            TYPE_P (arg) ? NULL_TREE : arg,
14709                            flags))
14710         return unify_success (explain_p);
14711     }
14712
14713   if (strict == DEDUCE_EXACT)
14714     return unify_type_mismatch (explain_p, parm, arg);
14715   else
14716     return unify_arg_conversion (explain_p, parm, type, arg);
14717 }
14718
14719 /* Subroutine of type_unification_real and unify_pack_expansion to
14720    handle unification of a single P/A pair.  Parameters are as
14721    for those functions.  */
14722
14723 static int
14724 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14725                     int subr, unification_kind_t strict, int flags,
14726                     bool explain_p)
14727 {
14728   tree arg_expr = NULL_TREE;
14729   int arg_strict;
14730
14731   if (arg == error_mark_node || parm == error_mark_node)
14732     return unify_invalid (explain_p);
14733   if (arg == unknown_type_node)
14734     /* We can't deduce anything from this, but we might get all the
14735        template args from other function args.  */
14736     return unify_success (explain_p);
14737
14738   /* FIXME uses_deducible_template_parms */
14739   if (TYPE_P (parm) && !uses_template_parms (parm))
14740     return check_non_deducible_conversion (parm, arg, strict, flags,
14741                                            explain_p);
14742
14743   switch (strict)
14744     {
14745     case DEDUCE_CALL:
14746       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14747                     | UNIFY_ALLOW_MORE_CV_QUAL
14748                     | UNIFY_ALLOW_DERIVED);
14749       break;
14750
14751     case DEDUCE_CONV:
14752       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14753       break;
14754
14755     case DEDUCE_EXACT:
14756       arg_strict = UNIFY_ALLOW_NONE;
14757       break;
14758
14759     default:
14760       gcc_unreachable ();
14761     }
14762
14763   /* We only do these transformations if this is the top-level
14764      parameter_type_list in a call or declaration matching; in other
14765      situations (nested function declarators, template argument lists) we
14766      won't be comparing a type to an expression, and we don't do any type
14767      adjustments.  */
14768   if (!subr)
14769     {
14770       if (!TYPE_P (arg))
14771         {
14772           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14773           if (type_unknown_p (arg))
14774             {
14775               /* [temp.deduct.type] A template-argument can be
14776                  deduced from a pointer to function or pointer
14777                  to member function argument if the set of
14778                  overloaded functions does not contain function
14779                  templates and at most one of a set of
14780                  overloaded functions provides a unique
14781                  match.  */
14782
14783               if (resolve_overloaded_unification
14784                   (tparms, targs, parm, arg, strict,
14785                    arg_strict, explain_p))
14786                 return unify_success (explain_p);
14787               return unify_overload_resolution_failure (explain_p, arg);
14788             }
14789
14790           arg_expr = arg;
14791           arg = unlowered_expr_type (arg);
14792           if (arg == error_mark_node)
14793             return unify_invalid (explain_p);
14794         }
14795
14796       arg_strict |=
14797         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
14798     }
14799   else
14800     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
14801                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
14802
14803   /* For deduction from an init-list we need the actual list.  */
14804   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14805     arg = arg_expr;
14806   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
14807 }
14808
14809 /* Most parms like fn_type_unification.
14810
14811    If SUBR is 1, we're being called recursively (to unify the
14812    arguments of a function or method parameter of a function
14813    template). */
14814
14815 static int
14816 type_unification_real (tree tparms,
14817                        tree targs,
14818                        tree xparms,
14819                        const tree *xargs,
14820                        unsigned int xnargs,
14821                        int subr,
14822                        unification_kind_t strict,
14823                        int flags,
14824                        bool explain_p)
14825 {
14826   tree parm, arg;
14827   int i;
14828   int ntparms = TREE_VEC_LENGTH (tparms);
14829   int saw_undeduced = 0;
14830   tree parms;
14831   const tree *args;
14832   unsigned int nargs;
14833   unsigned int ia;
14834
14835   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14836   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14837   gcc_assert (ntparms > 0);
14838
14839   /* Reset the number of non-defaulted template arguments contained
14840      in TARGS.  */
14841   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14842
14843  again:
14844   parms = xparms;
14845   args = xargs;
14846   nargs = xnargs;
14847
14848   ia = 0;
14849   while (parms && parms != void_list_node
14850          && ia < nargs)
14851     {
14852       parm = TREE_VALUE (parms);
14853
14854       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14855           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14856         /* For a function parameter pack that occurs at the end of the
14857            parameter-declaration-list, the type A of each remaining
14858            argument of the call is compared with the type P of the
14859            declarator-id of the function parameter pack.  */
14860         break;
14861
14862       parms = TREE_CHAIN (parms);
14863
14864       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14865         /* For a function parameter pack that does not occur at the
14866            end of the parameter-declaration-list, the type of the
14867            parameter pack is a non-deduced context.  */
14868         continue;
14869
14870       arg = args[ia];
14871       ++ia;
14872
14873       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
14874                               flags, explain_p))
14875         return 1;
14876     }
14877
14878   if (parms 
14879       && parms != void_list_node
14880       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14881     {
14882       /* Unify the remaining arguments with the pack expansion type.  */
14883       tree argvec;
14884       tree parmvec = make_tree_vec (1);
14885
14886       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14887       argvec = make_tree_vec (nargs - ia);
14888       for (i = 0; ia < nargs; ++ia, ++i)
14889         TREE_VEC_ELT (argvec, i) = args[ia];
14890
14891       /* Copy the parameter into parmvec.  */
14892       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14893       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14894                                 /*subr=*/subr, explain_p))
14895         return 1;
14896
14897       /* Advance to the end of the list of parameters.  */
14898       parms = TREE_CHAIN (parms);
14899     }
14900
14901   /* Fail if we've reached the end of the parm list, and more args
14902      are present, and the parm list isn't variadic.  */
14903   if (ia < nargs && parms == void_list_node)
14904     return unify_too_many_arguments (explain_p, nargs, ia);
14905   /* Fail if parms are left and they don't have default values.  */
14906   if (parms && parms != void_list_node
14907       && TREE_PURPOSE (parms) == NULL_TREE)
14908     {
14909       unsigned int count = nargs;
14910       tree p = parms;
14911       while (p && p != void_list_node)
14912         {
14913           count++;
14914           p = TREE_CHAIN (p);
14915         }
14916       return unify_too_few_arguments (explain_p, ia, count);
14917     }
14918
14919   if (!subr)
14920     {
14921       tsubst_flags_t complain = (explain_p
14922                                  ? tf_warning_or_error
14923                                  : tf_none);
14924
14925       /* Check to see if we need another pass before we start clearing
14926          ARGUMENT_PACK_INCOMPLETE_P.  */
14927       for (i = 0; i < ntparms; i++)
14928         {
14929           tree targ = TREE_VEC_ELT (targs, i);
14930           tree tparm = TREE_VEC_ELT (tparms, i);
14931
14932           if (targ || tparm == error_mark_node)
14933             continue;
14934           tparm = TREE_VALUE (tparm);
14935
14936           /* If this is an undeduced nontype parameter that depends on
14937              a type parameter, try another pass; its type may have been
14938              deduced from a later argument than the one from which
14939              this parameter can be deduced.  */
14940           if (TREE_CODE (tparm) == PARM_DECL
14941               && uses_template_parms (TREE_TYPE (tparm))
14942               && !saw_undeduced++)
14943             goto again;
14944         }
14945
14946       for (i = 0; i < ntparms; i++)
14947         {
14948           tree targ = TREE_VEC_ELT (targs, i);
14949           tree tparm = TREE_VEC_ELT (tparms, i);
14950
14951           /* Clear the "incomplete" flags on all argument packs now so that
14952              substituting them into later default arguments works.  */
14953           if (targ && ARGUMENT_PACK_P (targ))
14954             {
14955               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14956               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14957             }
14958
14959           if (targ || tparm == error_mark_node)
14960             continue;
14961           tparm = TREE_VALUE (tparm);
14962
14963           /* Core issue #226 (C++0x) [temp.deduct]:
14964
14965              If a template argument has not been deduced, its
14966              default template argument, if any, is used. 
14967
14968              When we are in C++98 mode, TREE_PURPOSE will either
14969              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14970              to explicitly check cxx_dialect here.  */
14971           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14972             {
14973               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14974               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14975               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
14976               arg = convert_template_argument (parm, arg, targs, complain,
14977                                                i, NULL_TREE);
14978               if (arg == error_mark_node)
14979                 return 1;
14980               else
14981                 {
14982                   TREE_VEC_ELT (targs, i) = arg;
14983                   /* The position of the first default template argument,
14984                      is also the number of non-defaulted arguments in TARGS.
14985                      Record that.  */
14986                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14987                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14988                   continue;
14989                 }
14990             }
14991
14992           /* If the type parameter is a parameter pack, then it will
14993              be deduced to an empty parameter pack.  */
14994           if (template_parameter_pack_p (tparm))
14995             {
14996               tree arg;
14997
14998               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14999                 {
15000                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15001                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15002                   TREE_CONSTANT (arg) = 1;
15003                 }
15004               else
15005                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15006
15007               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15008
15009               TREE_VEC_ELT (targs, i) = arg;
15010               continue;
15011             }
15012
15013           return unify_parameter_deduction_failure (explain_p, tparm);
15014         }
15015     }
15016 #ifdef ENABLE_CHECKING
15017   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15018     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15019 #endif
15020
15021   return unify_success (explain_p);
15022 }
15023
15024 /* Subroutine of type_unification_real.  Args are like the variables
15025    at the call site.  ARG is an overloaded function (or template-id);
15026    we try deducing template args from each of the overloads, and if
15027    only one succeeds, we go with that.  Modifies TARGS and returns
15028    true on success.  */
15029
15030 static bool
15031 resolve_overloaded_unification (tree tparms,
15032                                 tree targs,
15033                                 tree parm,
15034                                 tree arg,
15035                                 unification_kind_t strict,
15036                                 int sub_strict,
15037                                 bool explain_p)
15038 {
15039   tree tempargs = copy_node (targs);
15040   int good = 0;
15041   tree goodfn = NULL_TREE;
15042   bool addr_p;
15043
15044   if (TREE_CODE (arg) == ADDR_EXPR)
15045     {
15046       arg = TREE_OPERAND (arg, 0);
15047       addr_p = true;
15048     }
15049   else
15050     addr_p = false;
15051
15052   if (TREE_CODE (arg) == COMPONENT_REF)
15053     /* Handle `&x' where `x' is some static or non-static member
15054        function name.  */
15055     arg = TREE_OPERAND (arg, 1);
15056
15057   if (TREE_CODE (arg) == OFFSET_REF)
15058     arg = TREE_OPERAND (arg, 1);
15059
15060   /* Strip baselink information.  */
15061   if (BASELINK_P (arg))
15062     arg = BASELINK_FUNCTIONS (arg);
15063
15064   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15065     {
15066       /* If we got some explicit template args, we need to plug them into
15067          the affected templates before we try to unify, in case the
15068          explicit args will completely resolve the templates in question.  */
15069
15070       int ok = 0;
15071       tree expl_subargs = TREE_OPERAND (arg, 1);
15072       arg = TREE_OPERAND (arg, 0);
15073
15074       for (; arg; arg = OVL_NEXT (arg))
15075         {
15076           tree fn = OVL_CURRENT (arg);
15077           tree subargs, elem;
15078
15079           if (TREE_CODE (fn) != TEMPLATE_DECL)
15080             continue;
15081
15082           ++processing_template_decl;
15083           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15084                                   expl_subargs, /*check_ret=*/false);
15085           if (subargs && !any_dependent_template_arguments_p (subargs))
15086             {
15087               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15088               if (try_one_overload (tparms, targs, tempargs, parm,
15089                                     elem, strict, sub_strict, addr_p, explain_p)
15090                   && (!goodfn || !decls_match (goodfn, elem)))
15091                 {
15092                   goodfn = elem;
15093                   ++good;
15094                 }
15095             }
15096           else if (subargs)
15097             ++ok;
15098           --processing_template_decl;
15099         }
15100       /* If no templates (or more than one) are fully resolved by the
15101          explicit arguments, this template-id is a non-deduced context; it
15102          could still be OK if we deduce all template arguments for the
15103          enclosing call through other arguments.  */
15104       if (good != 1)
15105         good = ok;
15106     }
15107   else if (TREE_CODE (arg) != OVERLOAD
15108            && TREE_CODE (arg) != FUNCTION_DECL)
15109     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15110        -- but the deduction does not succeed because the expression is
15111        not just the function on its own.  */
15112     return false;
15113   else
15114     for (; arg; arg = OVL_NEXT (arg))
15115       if (try_one_overload (tparms, targs, tempargs, parm,
15116                             TREE_TYPE (OVL_CURRENT (arg)),
15117                             strict, sub_strict, addr_p, explain_p)
15118           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15119         {
15120           goodfn = OVL_CURRENT (arg);
15121           ++good;
15122         }
15123
15124   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15125      to function or pointer to member function argument if the set of
15126      overloaded functions does not contain function templates and at most
15127      one of a set of overloaded functions provides a unique match.
15128
15129      So if we found multiple possibilities, we return success but don't
15130      deduce anything.  */
15131
15132   if (good == 1)
15133     {
15134       int i = TREE_VEC_LENGTH (targs);
15135       for (; i--; )
15136         if (TREE_VEC_ELT (tempargs, i))
15137           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15138     }
15139   if (good)
15140     return true;
15141
15142   return false;
15143 }
15144
15145 /* Core DR 115: In contexts where deduction is done and fails, or in
15146    contexts where deduction is not done, if a template argument list is
15147    specified and it, along with any default template arguments, identifies
15148    a single function template specialization, then the template-id is an
15149    lvalue for the function template specialization.  */
15150
15151 tree
15152 resolve_nondeduced_context (tree orig_expr)
15153 {
15154   tree expr, offset, baselink;
15155   bool addr;
15156
15157   if (!type_unknown_p (orig_expr))
15158     return orig_expr;
15159
15160   expr = orig_expr;
15161   addr = false;
15162   offset = NULL_TREE;
15163   baselink = NULL_TREE;
15164
15165   if (TREE_CODE (expr) == ADDR_EXPR)
15166     {
15167       expr = TREE_OPERAND (expr, 0);
15168       addr = true;
15169     }
15170   if (TREE_CODE (expr) == OFFSET_REF)
15171     {
15172       offset = expr;
15173       expr = TREE_OPERAND (expr, 1);
15174     }
15175   if (TREE_CODE (expr) == BASELINK)
15176     {
15177       baselink = expr;
15178       expr = BASELINK_FUNCTIONS (expr);
15179     }
15180
15181   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15182     {
15183       int good = 0;
15184       tree goodfn = NULL_TREE;
15185
15186       /* If we got some explicit template args, we need to plug them into
15187          the affected templates before we try to unify, in case the
15188          explicit args will completely resolve the templates in question.  */
15189
15190       tree expl_subargs = TREE_OPERAND (expr, 1);
15191       tree arg = TREE_OPERAND (expr, 0);
15192       tree badfn = NULL_TREE;
15193       tree badargs = NULL_TREE;
15194
15195       for (; arg; arg = OVL_NEXT (arg))
15196         {
15197           tree fn = OVL_CURRENT (arg);
15198           tree subargs, elem;
15199
15200           if (TREE_CODE (fn) != TEMPLATE_DECL)
15201             continue;
15202
15203           ++processing_template_decl;
15204           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15205                                   expl_subargs, /*check_ret=*/false);
15206           if (subargs && !any_dependent_template_arguments_p (subargs))
15207             {
15208               elem = instantiate_template (fn, subargs, tf_none);
15209               if (elem == error_mark_node)
15210                 {
15211                   badfn = fn;
15212                   badargs = subargs;
15213                 }
15214               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15215                 {
15216                   goodfn = elem;
15217                   ++good;
15218                 }
15219             }
15220           --processing_template_decl;
15221         }
15222       if (good == 1)
15223         {
15224           mark_used (goodfn);
15225           expr = goodfn;
15226           if (baselink)
15227             expr = build_baselink (BASELINK_BINFO (baselink),
15228                                    BASELINK_ACCESS_BINFO (baselink),
15229                                    expr, BASELINK_OPTYPE (baselink));
15230           if (offset)
15231             {
15232               tree base
15233                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15234               expr = build_offset_ref (base, expr, addr);
15235             }
15236           if (addr)
15237             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15238           return expr;
15239         }
15240       else if (good == 0 && badargs)
15241         /* There were no good options and at least one bad one, so let the
15242            user know what the problem is.  */
15243         instantiate_template (badfn, badargs, tf_warning_or_error);
15244     }
15245   return orig_expr;
15246 }
15247
15248 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15249    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15250    different overloads deduce different arguments for a given parm.
15251    ADDR_P is true if the expression for which deduction is being
15252    performed was of the form "& fn" rather than simply "fn".
15253
15254    Returns 1 on success.  */
15255
15256 static int
15257 try_one_overload (tree tparms,
15258                   tree orig_targs,
15259                   tree targs,
15260                   tree parm,
15261                   tree arg,
15262                   unification_kind_t strict,
15263                   int sub_strict,
15264                   bool addr_p,
15265                   bool explain_p)
15266 {
15267   int nargs;
15268   tree tempargs;
15269   int i;
15270
15271   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15272      to function or pointer to member function argument if the set of
15273      overloaded functions does not contain function templates and at most
15274      one of a set of overloaded functions provides a unique match.
15275
15276      So if this is a template, just return success.  */
15277
15278   if (uses_template_parms (arg))
15279     return 1;
15280
15281   if (TREE_CODE (arg) == METHOD_TYPE)
15282     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15283   else if (addr_p)
15284     arg = build_pointer_type (arg);
15285
15286   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15287
15288   /* We don't copy orig_targs for this because if we have already deduced
15289      some template args from previous args, unify would complain when we
15290      try to deduce a template parameter for the same argument, even though
15291      there isn't really a conflict.  */
15292   nargs = TREE_VEC_LENGTH (targs);
15293   tempargs = make_tree_vec (nargs);
15294
15295   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15296     return 0;
15297
15298   /* First make sure we didn't deduce anything that conflicts with
15299      explicitly specified args.  */
15300   for (i = nargs; i--; )
15301     {
15302       tree elt = TREE_VEC_ELT (tempargs, i);
15303       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15304
15305       if (!elt)
15306         /*NOP*/;
15307       else if (uses_template_parms (elt))
15308         /* Since we're unifying against ourselves, we will fill in
15309            template args used in the function parm list with our own
15310            template parms.  Discard them.  */
15311         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15312       else if (oldelt && !template_args_equal (oldelt, elt))
15313         return 0;
15314     }
15315
15316   for (i = nargs; i--; )
15317     {
15318       tree elt = TREE_VEC_ELT (tempargs, i);
15319
15320       if (elt)
15321         TREE_VEC_ELT (targs, i) = elt;
15322     }
15323
15324   return 1;
15325 }
15326
15327 /* PARM is a template class (perhaps with unbound template
15328    parameters).  ARG is a fully instantiated type.  If ARG can be
15329    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15330    TARGS are as for unify.  */
15331
15332 static tree
15333 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15334                        bool explain_p)
15335 {
15336   tree copy_of_targs;
15337
15338   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15339       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15340           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15341     return NULL_TREE;
15342
15343   /* We need to make a new template argument vector for the call to
15344      unify.  If we used TARGS, we'd clutter it up with the result of
15345      the attempted unification, even if this class didn't work out.
15346      We also don't want to commit ourselves to all the unifications
15347      we've already done, since unification is supposed to be done on
15348      an argument-by-argument basis.  In other words, consider the
15349      following pathological case:
15350
15351        template <int I, int J, int K>
15352        struct S {};
15353
15354        template <int I, int J>
15355        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15356
15357        template <int I, int J, int K>
15358        void f(S<I, J, K>, S<I, I, I>);
15359
15360        void g() {
15361          S<0, 0, 0> s0;
15362          S<0, 1, 2> s2;
15363
15364          f(s0, s2);
15365        }
15366
15367      Now, by the time we consider the unification involving `s2', we
15368      already know that we must have `f<0, 0, 0>'.  But, even though
15369      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15370      because there are two ways to unify base classes of S<0, 1, 2>
15371      with S<I, I, I>.  If we kept the already deduced knowledge, we
15372      would reject the possibility I=1.  */
15373   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15374
15375   /* If unification failed, we're done.  */
15376   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15377              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15378     return NULL_TREE;
15379
15380   return arg;
15381 }
15382
15383 /* Given a template type PARM and a class type ARG, find the unique
15384    base type in ARG that is an instance of PARM.  We do not examine
15385    ARG itself; only its base-classes.  If there is not exactly one
15386    appropriate base class, return NULL_TREE.  PARM may be the type of
15387    a partial specialization, as well as a plain template type.  Used
15388    by unify.  */
15389
15390 static enum template_base_result
15391 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15392                    bool explain_p, tree *result)
15393 {
15394   tree rval = NULL_TREE;
15395   tree binfo;
15396
15397   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15398
15399   binfo = TYPE_BINFO (complete_type (arg));
15400   if (!binfo)
15401     {
15402       /* The type could not be completed.  */
15403       *result = NULL_TREE;
15404       return tbr_incomplete_type;
15405     }
15406
15407   /* Walk in inheritance graph order.  The search order is not
15408      important, and this avoids multiple walks of virtual bases.  */
15409   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15410     {
15411       tree r = try_class_unification (tparms, targs, parm,
15412                                       BINFO_TYPE (binfo), explain_p);
15413
15414       if (r)
15415         {
15416           /* If there is more than one satisfactory baseclass, then:
15417
15418                [temp.deduct.call]
15419
15420               If they yield more than one possible deduced A, the type
15421               deduction fails.
15422
15423              applies.  */
15424           if (rval && !same_type_p (r, rval))
15425             {
15426               *result = NULL_TREE;
15427               return tbr_ambiguous_baseclass;
15428             }
15429
15430           rval = r;
15431         }
15432     }
15433
15434   *result = rval;
15435   return tbr_success;
15436 }
15437
15438 /* Returns the level of DECL, which declares a template parameter.  */
15439
15440 static int
15441 template_decl_level (tree decl)
15442 {
15443   switch (TREE_CODE (decl))
15444     {
15445     case TYPE_DECL:
15446     case TEMPLATE_DECL:
15447       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15448
15449     case PARM_DECL:
15450       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15451
15452     default:
15453       gcc_unreachable ();
15454     }
15455   return 0;
15456 }
15457
15458 /* Decide whether ARG can be unified with PARM, considering only the
15459    cv-qualifiers of each type, given STRICT as documented for unify.
15460    Returns nonzero iff the unification is OK on that basis.  */
15461
15462 static int
15463 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15464 {
15465   int arg_quals = cp_type_quals (arg);
15466   int parm_quals = cp_type_quals (parm);
15467
15468   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15469       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15470     {
15471       /*  Although a CVR qualifier is ignored when being applied to a
15472           substituted template parameter ([8.3.2]/1 for example), that
15473           does not allow us to unify "const T" with "int&" because both
15474           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15475           It is ok when we're allowing additional CV qualifiers
15476           at the outer level [14.8.2.1]/3,1st bullet.  */
15477       if ((TREE_CODE (arg) == REFERENCE_TYPE
15478            || TREE_CODE (arg) == FUNCTION_TYPE
15479            || TREE_CODE (arg) == METHOD_TYPE)
15480           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15481         return 0;
15482
15483       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15484           && (parm_quals & TYPE_QUAL_RESTRICT))
15485         return 0;
15486     }
15487
15488   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15489       && (arg_quals & parm_quals) != parm_quals)
15490     return 0;
15491
15492   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15493       && (parm_quals & arg_quals) != arg_quals)
15494     return 0;
15495
15496   return 1;
15497 }
15498
15499 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15500 void 
15501 template_parm_level_and_index (tree parm, int* level, int* index)
15502 {
15503   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15504       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15505       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15506     {
15507       *index = TEMPLATE_TYPE_IDX (parm);
15508       *level = TEMPLATE_TYPE_LEVEL (parm);
15509     }
15510   else
15511     {
15512       *index = TEMPLATE_PARM_IDX (parm);
15513       *level = TEMPLATE_PARM_LEVEL (parm);
15514     }
15515 }
15516
15517 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15518   do {                                                                  \
15519     if (unify (TP, TA, P, A, S, EP))                                    \
15520       return 1;                                                         \
15521   } while (0);
15522
15523 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15524    expansion at the end of PACKED_PARMS. Returns 0 if the type
15525    deduction succeeds, 1 otherwise. STRICT is the same as in
15526    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15527    call argument list. We'll need to adjust the arguments to make them
15528    types. SUBR tells us if this is from a recursive call to
15529    type_unification_real, or for comparing two template argument
15530    lists. */
15531
15532 static int
15533 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15534                       tree packed_args, unification_kind_t strict,
15535                       bool subr, bool explain_p)
15536 {
15537   tree parm 
15538     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15539   tree pattern = PACK_EXPANSION_PATTERN (parm);
15540   tree pack, packs = NULL_TREE;
15541   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15542   int len = TREE_VEC_LENGTH (packed_args);
15543
15544   /* Determine the parameter packs we will be deducing from the
15545      pattern, and record their current deductions.  */
15546   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15547        pack; pack = TREE_CHAIN (pack))
15548     {
15549       tree parm_pack = TREE_VALUE (pack);
15550       int idx, level;
15551
15552       /* Determine the index and level of this parameter pack.  */
15553       template_parm_level_and_index (parm_pack, &level, &idx);
15554
15555       /* Keep track of the parameter packs and their corresponding
15556          argument packs.  */
15557       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15558       TREE_TYPE (packs) = make_tree_vec (len - start);
15559     }
15560   
15561   /* Loop through all of the arguments that have not yet been
15562      unified and unify each with the pattern.  */
15563   for (i = start; i < len; i++)
15564     {
15565       tree parm;
15566       bool any_explicit = false;
15567       tree arg = TREE_VEC_ELT (packed_args, i);
15568
15569       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15570          or the element of its argument pack at the current index if
15571          this argument was explicitly specified.  */
15572       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15573         {
15574           int idx, level;
15575           tree arg, pargs;
15576           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15577
15578           arg = NULL_TREE;
15579           if (TREE_VALUE (pack)
15580               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15581               && (i < TREE_VEC_LENGTH (pargs)))
15582             {
15583               any_explicit = true;
15584               arg = TREE_VEC_ELT (pargs, i);
15585             }
15586           TMPL_ARG (targs, level, idx) = arg;
15587         }
15588
15589       /* If we had explicit template arguments, substitute them into the
15590          pattern before deduction.  */
15591       if (any_explicit)
15592         {
15593           /* Some arguments might still be unspecified or dependent.  */
15594           bool dependent;
15595           ++processing_template_decl;
15596           dependent = any_dependent_template_arguments_p (targs);
15597           if (!dependent)
15598             --processing_template_decl;
15599           parm = tsubst (pattern, targs,
15600                          explain_p ? tf_warning_or_error : tf_none,
15601                          NULL_TREE);
15602           if (dependent)
15603             --processing_template_decl;
15604           if (parm == error_mark_node)
15605             return 1;
15606         }
15607       else
15608         parm = pattern;
15609
15610       /* Unify the pattern with the current argument.  */
15611       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15612                               LOOKUP_IMPLICIT, explain_p))
15613         return 1;
15614
15615       /* For each parameter pack, collect the deduced value.  */
15616       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15617         {
15618           int idx, level;
15619           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15620
15621           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15622             TMPL_ARG (targs, level, idx);
15623         }
15624     }
15625
15626   /* Verify that the results of unification with the parameter packs
15627      produce results consistent with what we've seen before, and make
15628      the deduced argument packs available.  */
15629   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15630     {
15631       tree old_pack = TREE_VALUE (pack);
15632       tree new_args = TREE_TYPE (pack);
15633       int i, len = TREE_VEC_LENGTH (new_args);
15634       int idx, level;
15635       bool nondeduced_p = false;
15636
15637       /* By default keep the original deduced argument pack.
15638          If necessary, more specific code is going to update the
15639          resulting deduced argument later down in this function.  */
15640       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15641       TMPL_ARG (targs, level, idx) = old_pack;
15642
15643       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15644          actually deduce anything.  */
15645       for (i = 0; i < len && !nondeduced_p; ++i)
15646         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15647           nondeduced_p = true;
15648       if (nondeduced_p)
15649         continue;
15650
15651       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15652         {
15653           /* If we had fewer function args than explicit template args,
15654              just use the explicits.  */
15655           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15656           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15657           if (len < explicit_len)
15658             new_args = explicit_args;
15659         }
15660
15661       if (!old_pack)
15662         {
15663           tree result;
15664           /* Build the deduced *_ARGUMENT_PACK.  */
15665           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15666             {
15667               result = make_node (NONTYPE_ARGUMENT_PACK);
15668               TREE_TYPE (result) = 
15669                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15670               TREE_CONSTANT (result) = 1;
15671             }
15672           else
15673             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15674
15675           SET_ARGUMENT_PACK_ARGS (result, new_args);
15676
15677           /* Note the deduced argument packs for this parameter
15678              pack.  */
15679           TMPL_ARG (targs, level, idx) = result;
15680         }
15681       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15682                && (ARGUMENT_PACK_ARGS (old_pack) 
15683                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15684         {
15685           /* We only had the explicitly-provided arguments before, but
15686              now we have a complete set of arguments.  */
15687           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15688
15689           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15690           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15691           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15692         }
15693       else
15694         {
15695           tree bad_old_arg, bad_new_arg;
15696           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15697
15698           if (!comp_template_args_with_info (old_args, new_args,
15699                                              &bad_old_arg, &bad_new_arg))
15700             /* Inconsistent unification of this parameter pack.  */
15701             return unify_parameter_pack_inconsistent (explain_p,
15702                                                       bad_old_arg,
15703                                                       bad_new_arg);
15704         }
15705     }
15706
15707   return unify_success (explain_p);
15708 }
15709
15710 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15711    set of template parameters to a template.  TARGS is the bindings
15712    for those template parameters, as determined thus far; TARGS may
15713    include template arguments for outer levels of template parameters
15714    as well.  PARM is a parameter to a template function, or a
15715    subcomponent of that parameter; ARG is the corresponding argument.
15716    This function attempts to match PARM with ARG in a manner
15717    consistent with the existing assignments in TARGS.  If more values
15718    are deduced, then TARGS is updated.
15719
15720    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15721    parameter STRICT is a bitwise or of the following flags:
15722
15723      UNIFY_ALLOW_NONE:
15724        Require an exact match between PARM and ARG.
15725      UNIFY_ALLOW_MORE_CV_QUAL:
15726        Allow the deduced ARG to be more cv-qualified (by qualification
15727        conversion) than ARG.
15728      UNIFY_ALLOW_LESS_CV_QUAL:
15729        Allow the deduced ARG to be less cv-qualified than ARG.
15730      UNIFY_ALLOW_DERIVED:
15731        Allow the deduced ARG to be a template base class of ARG,
15732        or a pointer to a template base class of the type pointed to by
15733        ARG.
15734      UNIFY_ALLOW_INTEGER:
15735        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15736        case for more information.
15737      UNIFY_ALLOW_OUTER_LEVEL:
15738        This is the outermost level of a deduction. Used to determine validity
15739        of qualification conversions. A valid qualification conversion must
15740        have const qualified pointers leading up to the inner type which
15741        requires additional CV quals, except at the outer level, where const
15742        is not required [conv.qual]. It would be normal to set this flag in
15743        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15744      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15745        This is the outermost level of a deduction, and PARM can be more CV
15746        qualified at this point.
15747      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15748        This is the outermost level of a deduction, and PARM can be less CV
15749        qualified at this point.  */
15750
15751 static int
15752 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15753        bool explain_p)
15754 {
15755   int idx;
15756   tree targ;
15757   tree tparm;
15758   int strict_in = strict;
15759
15760   /* I don't think this will do the right thing with respect to types.
15761      But the only case I've seen it in so far has been array bounds, where
15762      signedness is the only information lost, and I think that will be
15763      okay.  */
15764   while (TREE_CODE (parm) == NOP_EXPR)
15765     parm = TREE_OPERAND (parm, 0);
15766
15767   if (arg == error_mark_node)
15768     return unify_invalid (explain_p);
15769   if (arg == unknown_type_node
15770       || arg == init_list_type_node)
15771     /* We can't deduce anything from this, but we might get all the
15772        template args from other function args.  */
15773     return unify_success (explain_p);
15774
15775   /* If PARM uses template parameters, then we can't bail out here,
15776      even if ARG == PARM, since we won't record unifications for the
15777      template parameters.  We might need them if we're trying to
15778      figure out which of two things is more specialized.  */
15779   if (arg == parm && !uses_template_parms (parm))
15780     return unify_success (explain_p);
15781
15782   /* Handle init lists early, so the rest of the function can assume
15783      we're dealing with a type. */
15784   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15785     {
15786       tree elt, elttype;
15787       unsigned i;
15788       tree orig_parm = parm;
15789
15790       /* Replace T with std::initializer_list<T> for deduction.  */
15791       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15792           && flag_deduce_init_list)
15793         parm = listify (parm);
15794
15795       if (!is_std_init_list (parm))
15796         /* We can only deduce from an initializer list argument if the
15797            parameter is std::initializer_list; otherwise this is a
15798            non-deduced context. */
15799         return unify_success (explain_p);
15800
15801       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15802
15803       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15804         {
15805           int elt_strict = strict;
15806
15807           if (elt == error_mark_node)
15808             return unify_invalid (explain_p);
15809
15810           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15811             {
15812               tree type = TREE_TYPE (elt);
15813               /* It should only be possible to get here for a call.  */
15814               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15815               elt_strict |= maybe_adjust_types_for_deduction
15816                 (DEDUCE_CALL, &elttype, &type, elt);
15817               elt = type;
15818             }
15819
15820           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15821                                    explain_p);
15822         }
15823
15824       /* If the std::initializer_list<T> deduction worked, replace the
15825          deduced A with std::initializer_list<A>.  */
15826       if (orig_parm != parm)
15827         {
15828           idx = TEMPLATE_TYPE_IDX (orig_parm);
15829           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15830           targ = listify (targ);
15831           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15832         }
15833       return unify_success (explain_p);
15834     }
15835
15836   /* Immediately reject some pairs that won't unify because of
15837      cv-qualification mismatches.  */
15838   if (TREE_CODE (arg) == TREE_CODE (parm)
15839       && TYPE_P (arg)
15840       /* It is the elements of the array which hold the cv quals of an array
15841          type, and the elements might be template type parms. We'll check
15842          when we recurse.  */
15843       && TREE_CODE (arg) != ARRAY_TYPE
15844       /* We check the cv-qualifiers when unifying with template type
15845          parameters below.  We want to allow ARG `const T' to unify with
15846          PARM `T' for example, when computing which of two templates
15847          is more specialized, for example.  */
15848       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15849       && !check_cv_quals_for_unify (strict_in, arg, parm))
15850     return unify_cv_qual_mismatch (explain_p, parm, arg);
15851
15852   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15853       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15854     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15855   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15856   strict &= ~UNIFY_ALLOW_DERIVED;
15857   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15858   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15859
15860   switch (TREE_CODE (parm))
15861     {
15862     case TYPENAME_TYPE:
15863     case SCOPE_REF:
15864     case UNBOUND_CLASS_TEMPLATE:
15865       /* In a type which contains a nested-name-specifier, template
15866          argument values cannot be deduced for template parameters used
15867          within the nested-name-specifier.  */
15868       return unify_success (explain_p);
15869
15870     case TEMPLATE_TYPE_PARM:
15871     case TEMPLATE_TEMPLATE_PARM:
15872     case BOUND_TEMPLATE_TEMPLATE_PARM:
15873       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15874       if (tparm == error_mark_node)
15875         return unify_invalid (explain_p);
15876
15877       if (TEMPLATE_TYPE_LEVEL (parm)
15878           != template_decl_level (tparm))
15879         /* The PARM is not one we're trying to unify.  Just check
15880            to see if it matches ARG.  */
15881         {
15882           if (TREE_CODE (arg) == TREE_CODE (parm)
15883               && same_type_p (parm, arg))
15884             return unify_success (explain_p);
15885           else
15886             return unify_type_mismatch (explain_p, parm, arg);
15887         }
15888       idx = TEMPLATE_TYPE_IDX (parm);
15889       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15890       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15891
15892       /* Check for mixed types and values.  */
15893       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15894            && TREE_CODE (tparm) != TYPE_DECL)
15895           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15896               && TREE_CODE (tparm) != TEMPLATE_DECL))
15897         gcc_unreachable ();
15898
15899       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15900         {
15901           /* ARG must be constructed from a template class or a template
15902              template parameter.  */
15903           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15904               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15905             return unify_template_deduction_failure (explain_p, parm, arg);
15906
15907           {
15908             tree parmvec = TYPE_TI_ARGS (parm);
15909             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15910             tree full_argvec = add_to_template_args (targs, argvec);
15911             tree parm_parms 
15912               = DECL_INNERMOST_TEMPLATE_PARMS
15913                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15914             int i, len;
15915             int parm_variadic_p = 0;
15916
15917             /* The resolution to DR150 makes clear that default
15918                arguments for an N-argument may not be used to bind T
15919                to a template template parameter with fewer than N
15920                parameters.  It is not safe to permit the binding of
15921                default arguments as an extension, as that may change
15922                the meaning of a conforming program.  Consider:
15923
15924                   struct Dense { static const unsigned int dim = 1; };
15925
15926                   template <template <typename> class View,
15927                             typename Block>
15928                   void operator+(float, View<Block> const&);
15929
15930                   template <typename Block,
15931                             unsigned int Dim = Block::dim>
15932                   struct Lvalue_proxy { operator float() const; };
15933
15934                   void
15935                   test_1d (void) {
15936                     Lvalue_proxy<Dense> p;
15937                     float b;
15938                     b + p;
15939                   }
15940
15941               Here, if Lvalue_proxy is permitted to bind to View, then
15942               the global operator+ will be used; if they are not, the
15943               Lvalue_proxy will be converted to float.  */
15944             if (coerce_template_parms (parm_parms,
15945                                        full_argvec,
15946                                        TYPE_TI_TEMPLATE (parm),
15947                                        (explain_p
15948                                         ? tf_warning_or_error
15949                                         : tf_none),
15950                                        /*require_all_args=*/true,
15951                                        /*use_default_args=*/false)
15952                 == error_mark_node)
15953               return 1;
15954
15955             /* Deduce arguments T, i from TT<T> or TT<i>.
15956                We check each element of PARMVEC and ARGVEC individually
15957                rather than the whole TREE_VEC since they can have
15958                different number of elements.  */
15959
15960             parmvec = expand_template_argument_pack (parmvec);
15961             argvec = expand_template_argument_pack (argvec);
15962
15963             len = TREE_VEC_LENGTH (parmvec);
15964
15965             /* Check if the parameters end in a pack, making them
15966                variadic.  */
15967             if (len > 0
15968                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15969               parm_variadic_p = 1;
15970             
15971             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15972               return unify_too_few_arguments (explain_p,
15973                                               TREE_VEC_LENGTH (argvec), len);
15974
15975              for (i = 0; i < len - parm_variadic_p; ++i)
15976               {
15977                 RECUR_AND_CHECK_FAILURE (tparms, targs,
15978                                          TREE_VEC_ELT (parmvec, i),
15979                                          TREE_VEC_ELT (argvec, i),
15980                                          UNIFY_ALLOW_NONE, explain_p);
15981               }
15982
15983             if (parm_variadic_p
15984                 && unify_pack_expansion (tparms, targs,
15985                                          parmvec, argvec,
15986                                          DEDUCE_EXACT,
15987                                          /*subr=*/true, explain_p))
15988               return 1;
15989           }
15990           arg = TYPE_TI_TEMPLATE (arg);
15991
15992           /* Fall through to deduce template name.  */
15993         }
15994
15995       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15996           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15997         {
15998           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15999
16000           /* Simple cases: Value already set, does match or doesn't.  */
16001           if (targ != NULL_TREE && template_args_equal (targ, arg))
16002             return unify_success (explain_p);
16003           else if (targ)
16004             return unify_inconsistency (explain_p, parm, targ, arg);
16005         }
16006       else
16007         {
16008           /* If PARM is `const T' and ARG is only `int', we don't have
16009              a match unless we are allowing additional qualification.
16010              If ARG is `const int' and PARM is just `T' that's OK;
16011              that binds `const int' to `T'.  */
16012           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16013                                          arg, parm))
16014             return unify_cv_qual_mismatch (explain_p, parm, arg);
16015
16016           /* Consider the case where ARG is `const volatile int' and
16017              PARM is `const T'.  Then, T should be `volatile int'.  */
16018           arg = cp_build_qualified_type_real
16019             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16020           if (arg == error_mark_node)
16021             return unify_invalid (explain_p);
16022
16023           /* Simple cases: Value already set, does match or doesn't.  */
16024           if (targ != NULL_TREE && same_type_p (targ, arg))
16025             return unify_success (explain_p);
16026           else if (targ)
16027             return unify_inconsistency (explain_p, parm, targ, arg);
16028
16029           /* Make sure that ARG is not a variable-sized array.  (Note
16030              that were talking about variable-sized arrays (like
16031              `int[n]'), rather than arrays of unknown size (like
16032              `int[]').)  We'll get very confused by such a type since
16033              the bound of the array is not constant, and therefore
16034              not mangleable.  Besides, such types are not allowed in
16035              ISO C++, so we can do as we please here.  We do allow
16036              them for 'auto' deduction, since that isn't ABI-exposed.  */
16037           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16038             return unify_vla_arg (explain_p, arg);
16039
16040           /* Strip typedefs as in convert_template_argument.  */
16041           arg = canonicalize_type_argument (arg, tf_none);
16042         }
16043
16044       /* If ARG is a parameter pack or an expansion, we cannot unify
16045          against it unless PARM is also a parameter pack.  */
16046       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16047           && !template_parameter_pack_p (parm))
16048         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16049
16050       /* If the argument deduction results is a METHOD_TYPE,
16051          then there is a problem.
16052          METHOD_TYPE doesn't map to any real C++ type the result of
16053          the deduction can not be of that type.  */
16054       if (TREE_CODE (arg) == METHOD_TYPE)
16055         return unify_method_type_error (explain_p, arg);
16056
16057       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16058       return unify_success (explain_p);
16059
16060     case TEMPLATE_PARM_INDEX:
16061       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16062       if (tparm == error_mark_node)
16063         return unify_invalid (explain_p);
16064
16065       if (TEMPLATE_PARM_LEVEL (parm)
16066           != template_decl_level (tparm))
16067         {
16068           /* The PARM is not one we're trying to unify.  Just check
16069              to see if it matches ARG.  */
16070           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16071                          && cp_tree_equal (parm, arg));
16072           if (result)
16073             unify_expression_unequal (explain_p, parm, arg);
16074           return result;
16075         }
16076
16077       idx = TEMPLATE_PARM_IDX (parm);
16078       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16079
16080       if (targ)
16081         {
16082           int x = !cp_tree_equal (targ, arg);
16083           if (x)
16084             unify_inconsistency (explain_p, parm, targ, arg);
16085           return x;
16086         }
16087
16088       /* [temp.deduct.type] If, in the declaration of a function template
16089          with a non-type template-parameter, the non-type
16090          template-parameter is used in an expression in the function
16091          parameter-list and, if the corresponding template-argument is
16092          deduced, the template-argument type shall match the type of the
16093          template-parameter exactly, except that a template-argument
16094          deduced from an array bound may be of any integral type.
16095          The non-type parameter might use already deduced type parameters.  */
16096       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16097       if (!TREE_TYPE (arg))
16098         /* Template-parameter dependent expression.  Just accept it for now.
16099            It will later be processed in convert_template_argument.  */
16100         ;
16101       else if (same_type_p (TREE_TYPE (arg), tparm))
16102         /* OK */;
16103       else if ((strict & UNIFY_ALLOW_INTEGER)
16104                && (TREE_CODE (tparm) == INTEGER_TYPE
16105                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16106         /* Convert the ARG to the type of PARM; the deduced non-type
16107            template argument must exactly match the types of the
16108            corresponding parameter.  */
16109         arg = fold (build_nop (tparm, arg));
16110       else if (uses_template_parms (tparm))
16111         /* We haven't deduced the type of this parameter yet.  Try again
16112            later.  */
16113         return unify_success (explain_p);
16114       else
16115         return unify_type_mismatch (explain_p, tparm, arg);
16116
16117       /* If ARG is a parameter pack or an expansion, we cannot unify
16118          against it unless PARM is also a parameter pack.  */
16119       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16120           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16121         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16122
16123       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16124       return unify_success (explain_p);
16125
16126     case PTRMEM_CST:
16127      {
16128         /* A pointer-to-member constant can be unified only with
16129          another constant.  */
16130       if (TREE_CODE (arg) != PTRMEM_CST)
16131         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16132
16133       /* Just unify the class member. It would be useless (and possibly
16134          wrong, depending on the strict flags) to unify also
16135          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16136          arg refer to the same variable, even if through different
16137          classes. For instance:
16138
16139          struct A { int x; };
16140          struct B : A { };
16141
16142          Unification of &A::x and &B::x must succeed.  */
16143       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16144                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16145      }
16146
16147     case POINTER_TYPE:
16148       {
16149         if (TREE_CODE (arg) != POINTER_TYPE)
16150           return unify_type_mismatch (explain_p, parm, arg);
16151
16152         /* [temp.deduct.call]
16153
16154            A can be another pointer or pointer to member type that can
16155            be converted to the deduced A via a qualification
16156            conversion (_conv.qual_).
16157
16158            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16159            This will allow for additional cv-qualification of the
16160            pointed-to types if appropriate.  */
16161
16162         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16163           /* The derived-to-base conversion only persists through one
16164              level of pointers.  */
16165           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16166
16167         return unify (tparms, targs, TREE_TYPE (parm),
16168                       TREE_TYPE (arg), strict, explain_p);
16169       }
16170
16171     case REFERENCE_TYPE:
16172       if (TREE_CODE (arg) != REFERENCE_TYPE)
16173         return unify_type_mismatch (explain_p, parm, arg);
16174       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16175                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16176
16177     case ARRAY_TYPE:
16178       if (TREE_CODE (arg) != ARRAY_TYPE)
16179         return unify_type_mismatch (explain_p, parm, arg);
16180       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16181           != (TYPE_DOMAIN (arg) == NULL_TREE))
16182         return unify_type_mismatch (explain_p, parm, arg);
16183       if (TYPE_DOMAIN (parm) != NULL_TREE)
16184         {
16185           tree parm_max;
16186           tree arg_max;
16187           bool parm_cst;
16188           bool arg_cst;
16189
16190           /* Our representation of array types uses "N - 1" as the
16191              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16192              not an integer constant.  We cannot unify arbitrarily
16193              complex expressions, so we eliminate the MINUS_EXPRs
16194              here.  */
16195           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16196           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16197           if (!parm_cst)
16198             {
16199               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16200               parm_max = TREE_OPERAND (parm_max, 0);
16201             }
16202           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16203           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16204           if (!arg_cst)
16205             {
16206               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16207                  trying to unify the type of a variable with the type
16208                  of a template parameter.  For example:
16209
16210                    template <unsigned int N>
16211                    void f (char (&) [N]);
16212                    int g(); 
16213                    void h(int i) {
16214                      char a[g(i)];
16215                      f(a); 
16216                    }
16217
16218                 Here, the type of the ARG will be "int [g(i)]", and
16219                 may be a SAVE_EXPR, etc.  */
16220               if (TREE_CODE (arg_max) != MINUS_EXPR)
16221                 return unify_vla_arg (explain_p, arg);
16222               arg_max = TREE_OPERAND (arg_max, 0);
16223             }
16224
16225           /* If only one of the bounds used a MINUS_EXPR, compensate
16226              by adding one to the other bound.  */
16227           if (parm_cst && !arg_cst)
16228             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16229                                     integer_type_node,
16230                                     parm_max,
16231                                     integer_one_node);
16232           else if (arg_cst && !parm_cst)
16233             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16234                                    integer_type_node,
16235                                    arg_max,
16236                                    integer_one_node);
16237
16238           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16239                                    UNIFY_ALLOW_INTEGER, explain_p);
16240         }
16241       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16242                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16243
16244     case REAL_TYPE:
16245     case COMPLEX_TYPE:
16246     case VECTOR_TYPE:
16247     case INTEGER_TYPE:
16248     case BOOLEAN_TYPE:
16249     case ENUMERAL_TYPE:
16250     case VOID_TYPE:
16251       if (TREE_CODE (arg) != TREE_CODE (parm))
16252         return unify_type_mismatch (explain_p, parm, arg);
16253
16254       /* We have already checked cv-qualification at the top of the
16255          function.  */
16256       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16257         return unify_type_mismatch (explain_p, parm, arg);
16258
16259       /* As far as unification is concerned, this wins.  Later checks
16260          will invalidate it if necessary.  */
16261       return unify_success (explain_p);
16262
16263       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16264       /* Type INTEGER_CST can come from ordinary constant template args.  */
16265     case INTEGER_CST:
16266       while (TREE_CODE (arg) == NOP_EXPR)
16267         arg = TREE_OPERAND (arg, 0);
16268
16269       if (TREE_CODE (arg) != INTEGER_CST)
16270         return unify_template_argument_mismatch (explain_p, parm, arg);
16271       return (tree_int_cst_equal (parm, arg)
16272               ? unify_success (explain_p)
16273               : unify_template_argument_mismatch (explain_p, parm, arg));
16274
16275     case TREE_VEC:
16276       {
16277         int i, len, argslen;
16278         int parm_variadic_p = 0;
16279
16280         if (TREE_CODE (arg) != TREE_VEC)
16281           return unify_template_argument_mismatch (explain_p, parm, arg);
16282
16283         len = TREE_VEC_LENGTH (parm);
16284         argslen = TREE_VEC_LENGTH (arg);
16285
16286         /* Check for pack expansions in the parameters.  */
16287         for (i = 0; i < len; ++i)
16288           {
16289             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16290               {
16291                 if (i == len - 1)
16292                   /* We can unify against something with a trailing
16293                      parameter pack.  */
16294                   parm_variadic_p = 1;
16295                 else
16296                   /* [temp.deduct.type]/9: If the template argument list of
16297                      P contains a pack expansion that is not the last
16298                      template argument, the entire template argument list
16299                      is a non-deduced context.  */
16300                   return unify_success (explain_p);
16301               }
16302           }
16303
16304         /* If we don't have enough arguments to satisfy the parameters
16305            (not counting the pack expression at the end), or we have
16306            too many arguments for a parameter list that doesn't end in
16307            a pack expression, we can't unify.  */
16308         if (parm_variadic_p
16309             ? argslen < len - parm_variadic_p
16310             : argslen != len)
16311           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16312
16313         /* Unify all of the parameters that precede the (optional)
16314            pack expression.  */
16315         for (i = 0; i < len - parm_variadic_p; ++i)
16316           {
16317             RECUR_AND_CHECK_FAILURE (tparms, targs,
16318                                      TREE_VEC_ELT (parm, i),
16319                                      TREE_VEC_ELT (arg, i),
16320                                      UNIFY_ALLOW_NONE, explain_p);
16321           }
16322         if (parm_variadic_p)
16323           return unify_pack_expansion (tparms, targs, parm, arg,
16324                                        DEDUCE_EXACT,
16325                                        /*subr=*/true, explain_p);
16326         return unify_success (explain_p);
16327       }
16328
16329     case RECORD_TYPE:
16330     case UNION_TYPE:
16331       if (TREE_CODE (arg) != TREE_CODE (parm))
16332         return unify_type_mismatch (explain_p, parm, arg);
16333
16334       if (TYPE_PTRMEMFUNC_P (parm))
16335         {
16336           if (!TYPE_PTRMEMFUNC_P (arg))
16337             return unify_type_mismatch (explain_p, parm, arg);
16338
16339           return unify (tparms, targs,
16340                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16341                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16342                         strict, explain_p);
16343         }
16344
16345       if (CLASSTYPE_TEMPLATE_INFO (parm))
16346         {
16347           tree t = NULL_TREE;
16348
16349           if (strict_in & UNIFY_ALLOW_DERIVED)
16350             {
16351               /* First, we try to unify the PARM and ARG directly.  */
16352               t = try_class_unification (tparms, targs,
16353                                          parm, arg, explain_p);
16354
16355               if (!t)
16356                 {
16357                   /* Fallback to the special case allowed in
16358                      [temp.deduct.call]:
16359
16360                        If P is a class, and P has the form
16361                        template-id, then A can be a derived class of
16362                        the deduced A.  Likewise, if P is a pointer to
16363                        a class of the form template-id, A can be a
16364                        pointer to a derived class pointed to by the
16365                        deduced A.  */
16366                   enum template_base_result r;
16367                   r = get_template_base (tparms, targs, parm, arg,
16368                                          explain_p, &t);
16369
16370                   if (!t)
16371                     return unify_no_common_base (explain_p, r, parm, arg);
16372                 }
16373             }
16374           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16375                    && (CLASSTYPE_TI_TEMPLATE (parm)
16376                        == CLASSTYPE_TI_TEMPLATE (arg)))
16377             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16378                Then, we should unify `int' and `U'.  */
16379             t = arg;
16380           else
16381             /* There's no chance of unification succeeding.  */
16382             return unify_type_mismatch (explain_p, parm, arg);
16383
16384           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16385                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16386         }
16387       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16388         return unify_type_mismatch (explain_p, parm, arg);
16389       return unify_success (explain_p);
16390
16391     case METHOD_TYPE:
16392     case FUNCTION_TYPE:
16393       {
16394         unsigned int nargs;
16395         tree *args;
16396         tree a;
16397         unsigned int i;
16398
16399         if (TREE_CODE (arg) != TREE_CODE (parm))
16400           return unify_type_mismatch (explain_p, parm, arg);
16401
16402         /* CV qualifications for methods can never be deduced, they must
16403            match exactly.  We need to check them explicitly here,
16404            because type_unification_real treats them as any other
16405            cv-qualified parameter.  */
16406         if (TREE_CODE (parm) == METHOD_TYPE
16407             && (!check_cv_quals_for_unify
16408                 (UNIFY_ALLOW_NONE,
16409                  class_of_this_parm (arg),
16410                  class_of_this_parm (parm))))
16411           return unify_cv_qual_mismatch (explain_p, parm, arg);
16412
16413         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16414                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16415
16416         nargs = list_length (TYPE_ARG_TYPES (arg));
16417         args = XALLOCAVEC (tree, nargs);
16418         for (a = TYPE_ARG_TYPES (arg), i = 0;
16419              a != NULL_TREE && a != void_list_node;
16420              a = TREE_CHAIN (a), ++i)
16421           args[i] = TREE_VALUE (a);
16422         nargs = i;
16423
16424         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16425                                       args, nargs, 1, DEDUCE_EXACT,
16426                                       LOOKUP_NORMAL, explain_p);
16427       }
16428
16429     case OFFSET_TYPE:
16430       /* Unify a pointer to member with a pointer to member function, which
16431          deduces the type of the member as a function type. */
16432       if (TYPE_PTRMEMFUNC_P (arg))
16433         {
16434           tree method_type;
16435           tree fntype;
16436
16437           /* Check top-level cv qualifiers */
16438           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16439             return unify_cv_qual_mismatch (explain_p, parm, arg);
16440
16441           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16442                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16443                                    UNIFY_ALLOW_NONE, explain_p);
16444
16445           /* Determine the type of the function we are unifying against. */
16446           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16447           fntype =
16448             build_function_type (TREE_TYPE (method_type),
16449                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16450
16451           /* Extract the cv-qualifiers of the member function from the
16452              implicit object parameter and place them on the function
16453              type to be restored later. */
16454           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16455           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16456         }
16457
16458       if (TREE_CODE (arg) != OFFSET_TYPE)
16459         return unify_type_mismatch (explain_p, parm, arg);
16460       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16461                                TYPE_OFFSET_BASETYPE (arg),
16462                                UNIFY_ALLOW_NONE, explain_p);
16463       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16464                     strict, explain_p);
16465
16466     case CONST_DECL:
16467       if (DECL_TEMPLATE_PARM_P (parm))
16468         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16469       if (arg != integral_constant_value (parm))
16470         return unify_template_argument_mismatch (explain_p, parm, arg);
16471       return unify_success (explain_p);
16472
16473     case FIELD_DECL:
16474     case TEMPLATE_DECL:
16475       /* Matched cases are handled by the ARG == PARM test above.  */
16476       return unify_template_argument_mismatch (explain_p, parm, arg);
16477
16478     case VAR_DECL:
16479       /* A non-type template parameter that is a variable should be a
16480          an integral constant, in which case, it whould have been
16481          folded into its (constant) value. So we should not be getting
16482          a variable here.  */
16483       gcc_unreachable ();
16484
16485     case TYPE_ARGUMENT_PACK:
16486     case NONTYPE_ARGUMENT_PACK:
16487       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16488                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16489
16490     case TYPEOF_TYPE:
16491     case DECLTYPE_TYPE:
16492     case UNDERLYING_TYPE:
16493       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16494          or UNDERLYING_TYPE nodes.  */
16495       return unify_success (explain_p);
16496
16497     case ERROR_MARK:
16498       /* Unification fails if we hit an error node.  */
16499       return unify_invalid (explain_p);
16500
16501     default:
16502       /* An unresolved overload is a nondeduced context.  */
16503       if (type_unknown_p (parm))
16504         return unify_success (explain_p);
16505       gcc_assert (EXPR_P (parm));
16506
16507       /* We must be looking at an expression.  This can happen with
16508          something like:
16509
16510            template <int I>
16511            void foo(S<I>, S<I + 2>);
16512
16513          This is a "nondeduced context":
16514
16515            [deduct.type]
16516
16517            The nondeduced contexts are:
16518
16519            --A type that is a template-id in which one or more of
16520              the template-arguments is an expression that references
16521              a template-parameter.
16522
16523          In these cases, we assume deduction succeeded, but don't
16524          actually infer any unifications.  */
16525
16526       if (!uses_template_parms (parm)
16527           && !template_args_equal (parm, arg))
16528         return unify_expression_unequal (explain_p, parm, arg);
16529       else
16530         return unify_success (explain_p);
16531     }
16532 }
16533 #undef RECUR_AND_CHECK_FAILURE
16534 \f
16535 /* Note that DECL can be defined in this translation unit, if
16536    required.  */
16537
16538 static void
16539 mark_definable (tree decl)
16540 {
16541   tree clone;
16542   DECL_NOT_REALLY_EXTERN (decl) = 1;
16543   FOR_EACH_CLONE (clone, decl)
16544     DECL_NOT_REALLY_EXTERN (clone) = 1;
16545 }
16546
16547 /* Called if RESULT is explicitly instantiated, or is a member of an
16548    explicitly instantiated class.  */
16549
16550 void
16551 mark_decl_instantiated (tree result, int extern_p)
16552 {
16553   SET_DECL_EXPLICIT_INSTANTIATION (result);
16554
16555   /* If this entity has already been written out, it's too late to
16556      make any modifications.  */
16557   if (TREE_ASM_WRITTEN (result))
16558     return;
16559
16560   if (TREE_CODE (result) != FUNCTION_DECL)
16561     /* The TREE_PUBLIC flag for function declarations will have been
16562        set correctly by tsubst.  */
16563     TREE_PUBLIC (result) = 1;
16564
16565   /* This might have been set by an earlier implicit instantiation.  */
16566   DECL_COMDAT (result) = 0;
16567
16568   if (extern_p)
16569     DECL_NOT_REALLY_EXTERN (result) = 0;
16570   else
16571     {
16572       mark_definable (result);
16573       /* Always make artificials weak.  */
16574       if (DECL_ARTIFICIAL (result) && flag_weak)
16575         comdat_linkage (result);
16576       /* For WIN32 we also want to put explicit instantiations in
16577          linkonce sections.  */
16578       else if (TREE_PUBLIC (result))
16579         maybe_make_one_only (result);
16580     }
16581
16582   /* If EXTERN_P, then this function will not be emitted -- unless
16583      followed by an explicit instantiation, at which point its linkage
16584      will be adjusted.  If !EXTERN_P, then this function will be
16585      emitted here.  In neither circumstance do we want
16586      import_export_decl to adjust the linkage.  */
16587   DECL_INTERFACE_KNOWN (result) = 1;
16588 }
16589
16590 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16591    important template arguments.  If any are missing, we check whether
16592    they're important by using error_mark_node for substituting into any
16593    args that were used for partial ordering (the ones between ARGS and END)
16594    and seeing if it bubbles up.  */
16595
16596 static bool
16597 check_undeduced_parms (tree targs, tree args, tree end)
16598 {
16599   bool found = false;
16600   int i;
16601   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16602     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16603       {
16604         found = true;
16605         TREE_VEC_ELT (targs, i) = error_mark_node;
16606       }
16607   if (found)
16608     {
16609       for (; args != end; args = TREE_CHAIN (args))
16610         {
16611           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16612           if (substed == error_mark_node)
16613             return true;
16614         }
16615     }
16616   return false;
16617 }
16618
16619 /* Given two function templates PAT1 and PAT2, return:
16620
16621    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16622    -1 if PAT2 is more specialized than PAT1.
16623    0 if neither is more specialized.
16624
16625    LEN indicates the number of parameters we should consider
16626    (defaulted parameters should not be considered).
16627
16628    The 1998 std underspecified function template partial ordering, and
16629    DR214 addresses the issue.  We take pairs of arguments, one from
16630    each of the templates, and deduce them against each other.  One of
16631    the templates will be more specialized if all the *other*
16632    template's arguments deduce against its arguments and at least one
16633    of its arguments *does* *not* deduce against the other template's
16634    corresponding argument.  Deduction is done as for class templates.
16635    The arguments used in deduction have reference and top level cv
16636    qualifiers removed.  Iff both arguments were originally reference
16637    types *and* deduction succeeds in both directions, the template
16638    with the more cv-qualified argument wins for that pairing (if
16639    neither is more cv-qualified, they both are equal).  Unlike regular
16640    deduction, after all the arguments have been deduced in this way,
16641    we do *not* verify the deduced template argument values can be
16642    substituted into non-deduced contexts.
16643
16644    The logic can be a bit confusing here, because we look at deduce1 and
16645    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16646    can find template arguments for pat1 to make arg1 look like arg2, that
16647    means that arg2 is at least as specialized as arg1.  */
16648
16649 int
16650 more_specialized_fn (tree pat1, tree pat2, int len)
16651 {
16652   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16653   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16654   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16655   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16656   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16657   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16658   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16659   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16660   tree origs1, origs2;
16661   bool lose1 = false;
16662   bool lose2 = false;
16663
16664   /* Remove the this parameter from non-static member functions.  If
16665      one is a non-static member function and the other is not a static
16666      member function, remove the first parameter from that function
16667      also.  This situation occurs for operator functions where we
16668      locate both a member function (with this pointer) and non-member
16669      operator (with explicit first operand).  */
16670   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16671     {
16672       len--; /* LEN is the number of significant arguments for DECL1 */
16673       args1 = TREE_CHAIN (args1);
16674       if (!DECL_STATIC_FUNCTION_P (decl2))
16675         args2 = TREE_CHAIN (args2);
16676     }
16677   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16678     {
16679       args2 = TREE_CHAIN (args2);
16680       if (!DECL_STATIC_FUNCTION_P (decl1))
16681         {
16682           len--;
16683           args1 = TREE_CHAIN (args1);
16684         }
16685     }
16686
16687   /* If only one is a conversion operator, they are unordered.  */
16688   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16689     return 0;
16690
16691   /* Consider the return type for a conversion function */
16692   if (DECL_CONV_FN_P (decl1))
16693     {
16694       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16695       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16696       len++;
16697     }
16698
16699   processing_template_decl++;
16700
16701   origs1 = args1;
16702   origs2 = args2;
16703
16704   while (len--
16705          /* Stop when an ellipsis is seen.  */
16706          && args1 != NULL_TREE && args2 != NULL_TREE)
16707     {
16708       tree arg1 = TREE_VALUE (args1);
16709       tree arg2 = TREE_VALUE (args2);
16710       int deduce1, deduce2;
16711       int quals1 = -1;
16712       int quals2 = -1;
16713
16714       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16715           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16716         {
16717           /* When both arguments are pack expansions, we need only
16718              unify the patterns themselves.  */
16719           arg1 = PACK_EXPANSION_PATTERN (arg1);
16720           arg2 = PACK_EXPANSION_PATTERN (arg2);
16721
16722           /* This is the last comparison we need to do.  */
16723           len = 0;
16724         }
16725
16726       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16727         {
16728           arg1 = TREE_TYPE (arg1);
16729           quals1 = cp_type_quals (arg1);
16730         }
16731
16732       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16733         {
16734           arg2 = TREE_TYPE (arg2);
16735           quals2 = cp_type_quals (arg2);
16736         }
16737
16738       if ((quals1 < 0) != (quals2 < 0))
16739         {
16740           /* Only of the args is a reference, see if we should apply
16741              array/function pointer decay to it.  This is not part of
16742              DR214, but is, IMHO, consistent with the deduction rules
16743              for the function call itself, and with our earlier
16744              implementation of the underspecified partial ordering
16745              rules.  (nathan).  */
16746           if (quals1 >= 0)
16747             {
16748               switch (TREE_CODE (arg1))
16749                 {
16750                 case ARRAY_TYPE:
16751                   arg1 = TREE_TYPE (arg1);
16752                   /* FALLTHROUGH. */
16753                 case FUNCTION_TYPE:
16754                   arg1 = build_pointer_type (arg1);
16755                   break;
16756
16757                 default:
16758                   break;
16759                 }
16760             }
16761           else
16762             {
16763               switch (TREE_CODE (arg2))
16764                 {
16765                 case ARRAY_TYPE:
16766                   arg2 = TREE_TYPE (arg2);
16767                   /* FALLTHROUGH. */
16768                 case FUNCTION_TYPE:
16769                   arg2 = build_pointer_type (arg2);
16770                   break;
16771
16772                 default:
16773                   break;
16774                 }
16775             }
16776         }
16777
16778       arg1 = TYPE_MAIN_VARIANT (arg1);
16779       arg2 = TYPE_MAIN_VARIANT (arg2);
16780
16781       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16782         {
16783           int i, len2 = list_length (args2);
16784           tree parmvec = make_tree_vec (1);
16785           tree argvec = make_tree_vec (len2);
16786           tree ta = args2;
16787
16788           /* Setup the parameter vector, which contains only ARG1.  */
16789           TREE_VEC_ELT (parmvec, 0) = arg1;
16790
16791           /* Setup the argument vector, which contains the remaining
16792              arguments.  */
16793           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16794             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16795
16796           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16797                                            argvec, DEDUCE_EXACT,
16798                                            /*subr=*/true, /*explain_p=*/false)
16799                      == 0);
16800
16801           /* We cannot deduce in the other direction, because ARG1 is
16802              a pack expansion but ARG2 is not.  */
16803           deduce2 = 0;
16804         }
16805       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16806         {
16807           int i, len1 = list_length (args1);
16808           tree parmvec = make_tree_vec (1);
16809           tree argvec = make_tree_vec (len1);
16810           tree ta = args1;
16811
16812           /* Setup the parameter vector, which contains only ARG1.  */
16813           TREE_VEC_ELT (parmvec, 0) = arg2;
16814
16815           /* Setup the argument vector, which contains the remaining
16816              arguments.  */
16817           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16818             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16819
16820           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16821                                            argvec, DEDUCE_EXACT,
16822                                            /*subr=*/true, /*explain_p=*/false)
16823                      == 0);
16824
16825           /* We cannot deduce in the other direction, because ARG2 is
16826              a pack expansion but ARG1 is not.*/
16827           deduce1 = 0;
16828         }
16829
16830       else
16831         {
16832           /* The normal case, where neither argument is a pack
16833              expansion.  */
16834           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16835                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16836                      == 0);
16837           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16838                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16839                      == 0);
16840         }
16841
16842       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16843          arg2, then arg2 is not as specialized as arg1.  */
16844       if (!deduce1)
16845         lose2 = true;
16846       if (!deduce2)
16847         lose1 = true;
16848
16849       /* "If, for a given type, deduction succeeds in both directions
16850          (i.e., the types are identical after the transformations above)
16851          and if the type from the argument template is more cv-qualified
16852          than the type from the parameter template (as described above)
16853          that type is considered to be more specialized than the other. If
16854          neither type is more cv-qualified than the other then neither type
16855          is more specialized than the other."  */
16856
16857       if (deduce1 && deduce2
16858           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16859         {
16860           if ((quals1 & quals2) == quals2)
16861             lose2 = true;
16862           if ((quals1 & quals2) == quals1)
16863             lose1 = true;
16864         }
16865
16866       if (lose1 && lose2)
16867         /* We've failed to deduce something in either direction.
16868            These must be unordered.  */
16869         break;
16870
16871       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16872           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16873         /* We have already processed all of the arguments in our
16874            handing of the pack expansion type.  */
16875         len = 0;
16876
16877       args1 = TREE_CHAIN (args1);
16878       args2 = TREE_CHAIN (args2);
16879     }
16880
16881   /* "In most cases, all template parameters must have values in order for
16882      deduction to succeed, but for partial ordering purposes a template
16883      parameter may remain without a value provided it is not used in the
16884      types being used for partial ordering."
16885
16886      Thus, if we are missing any of the targs1 we need to substitute into
16887      origs1, then pat2 is not as specialized as pat1.  This can happen when
16888      there is a nondeduced context.  */
16889   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16890     lose2 = true;
16891   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16892     lose1 = true;
16893
16894   processing_template_decl--;
16895
16896   /* All things being equal, if the next argument is a pack expansion
16897      for one function but not for the other, prefer the
16898      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16899   if (lose1 == lose2
16900       && args1 && TREE_VALUE (args1)
16901       && args2 && TREE_VALUE (args2))
16902     {
16903       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16904       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16905     }
16906
16907   if (lose1 == lose2)
16908     return 0;
16909   else if (!lose1)
16910     return 1;
16911   else
16912     return -1;
16913 }
16914
16915 /* Determine which of two partial specializations is more specialized.
16916
16917    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16918    to the first partial specialization.  The TREE_VALUE is the
16919    innermost set of template parameters for the partial
16920    specialization.  PAT2 is similar, but for the second template.
16921
16922    Return 1 if the first partial specialization is more specialized;
16923    -1 if the second is more specialized; 0 if neither is more
16924    specialized.
16925
16926    See [temp.class.order] for information about determining which of
16927    two templates is more specialized.  */
16928
16929 static int
16930 more_specialized_class (tree pat1, tree pat2)
16931 {
16932   tree targs;
16933   tree tmpl1, tmpl2;
16934   int winner = 0;
16935   bool any_deductions = false;
16936
16937   tmpl1 = TREE_TYPE (pat1);
16938   tmpl2 = TREE_TYPE (pat2);
16939
16940   /* Just like what happens for functions, if we are ordering between
16941      different class template specializations, we may encounter dependent
16942      types in the arguments, and we need our dependency check functions
16943      to behave correctly.  */
16944   ++processing_template_decl;
16945   targs = get_class_bindings (TREE_VALUE (pat1),
16946                               CLASSTYPE_TI_ARGS (tmpl1),
16947                               CLASSTYPE_TI_ARGS (tmpl2));
16948   if (targs)
16949     {
16950       --winner;
16951       any_deductions = true;
16952     }
16953
16954   targs = get_class_bindings (TREE_VALUE (pat2),
16955                               CLASSTYPE_TI_ARGS (tmpl2),
16956                               CLASSTYPE_TI_ARGS (tmpl1));
16957   if (targs)
16958     {
16959       ++winner;
16960       any_deductions = true;
16961     }
16962   --processing_template_decl;
16963
16964   /* In the case of a tie where at least one of the class templates
16965      has a parameter pack at the end, the template with the most
16966      non-packed parameters wins.  */
16967   if (winner == 0
16968       && any_deductions
16969       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16970           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16971     {
16972       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16973       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16974       int len1 = TREE_VEC_LENGTH (args1);
16975       int len2 = TREE_VEC_LENGTH (args2);
16976
16977       /* We don't count the pack expansion at the end.  */
16978       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16979         --len1;
16980       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16981         --len2;
16982
16983       if (len1 > len2)
16984         return 1;
16985       else if (len1 < len2)
16986         return -1;
16987     }
16988
16989   return winner;
16990 }
16991
16992 /* Return the template arguments that will produce the function signature
16993    DECL from the function template FN, with the explicit template
16994    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16995    also match.  Return NULL_TREE if no satisfactory arguments could be
16996    found.  */
16997
16998 static tree
16999 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17000 {
17001   int ntparms = DECL_NTPARMS (fn);
17002   tree targs = make_tree_vec (ntparms);
17003   tree decl_type;
17004   tree decl_arg_types;
17005   tree *args;
17006   unsigned int nargs, ix;
17007   tree arg;
17008
17009   /* Substitute the explicit template arguments into the type of DECL.
17010      The call to fn_type_unification will handle substitution into the
17011      FN.  */
17012   decl_type = TREE_TYPE (decl);
17013   if (explicit_args && uses_template_parms (decl_type))
17014     {
17015       tree tmpl;
17016       tree converted_args;
17017
17018       if (DECL_TEMPLATE_INFO (decl))
17019         tmpl = DECL_TI_TEMPLATE (decl);
17020       else
17021         /* We can get here for some invalid specializations.  */
17022         return NULL_TREE;
17023
17024       converted_args
17025         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17026                                  explicit_args, NULL_TREE,
17027                                  tf_none,
17028                                  /*require_all_args=*/false,
17029                                  /*use_default_args=*/false);
17030       if (converted_args == error_mark_node)
17031         return NULL_TREE;
17032
17033       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17034       if (decl_type == error_mark_node)
17035         return NULL_TREE;
17036     }
17037
17038   /* Never do unification on the 'this' parameter.  */
17039   decl_arg_types = skip_artificial_parms_for (decl, 
17040                                               TYPE_ARG_TYPES (decl_type));
17041
17042   nargs = list_length (decl_arg_types);
17043   args = XALLOCAVEC (tree, nargs);
17044   for (arg = decl_arg_types, ix = 0;
17045        arg != NULL_TREE && arg != void_list_node;
17046        arg = TREE_CHAIN (arg), ++ix)
17047     args[ix] = TREE_VALUE (arg);
17048
17049   if (fn_type_unification (fn, explicit_args, targs,
17050                            args, ix,
17051                            (check_rettype || DECL_CONV_FN_P (fn)
17052                             ? TREE_TYPE (decl_type) : NULL_TREE),
17053                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17054     return NULL_TREE;
17055
17056   return targs;
17057 }
17058
17059 /* Return the innermost template arguments that, when applied to a
17060    template specialization whose innermost template parameters are
17061    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17062    ARGS.
17063
17064    For example, suppose we have:
17065
17066      template <class T, class U> struct S {};
17067      template <class T> struct S<T*, int> {};
17068
17069    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17070    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17071    int}.  The resulting vector will be {double}, indicating that `T'
17072    is bound to `double'.  */
17073
17074 static tree
17075 get_class_bindings (tree tparms, tree spec_args, tree args)
17076 {
17077   int i, ntparms = TREE_VEC_LENGTH (tparms);
17078   tree deduced_args;
17079   tree innermost_deduced_args;
17080
17081   innermost_deduced_args = make_tree_vec (ntparms);
17082   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17083     {
17084       deduced_args = copy_node (args);
17085       SET_TMPL_ARGS_LEVEL (deduced_args,
17086                            TMPL_ARGS_DEPTH (deduced_args),
17087                            innermost_deduced_args);
17088     }
17089   else
17090     deduced_args = innermost_deduced_args;
17091
17092   if (unify (tparms, deduced_args,
17093              INNERMOST_TEMPLATE_ARGS (spec_args),
17094              INNERMOST_TEMPLATE_ARGS (args),
17095              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17096     return NULL_TREE;
17097
17098   for (i =  0; i < ntparms; ++i)
17099     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17100       return NULL_TREE;
17101
17102   /* Verify that nondeduced template arguments agree with the type
17103      obtained from argument deduction.
17104
17105      For example:
17106
17107        struct A { typedef int X; };
17108        template <class T, class U> struct C {};
17109        template <class T> struct C<T, typename T::X> {};
17110
17111      Then with the instantiation `C<A, int>', we can deduce that
17112      `T' is `A' but unify () does not check whether `typename T::X'
17113      is `int'.  */
17114   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17115   if (spec_args == error_mark_node
17116       /* We only need to check the innermost arguments; the other
17117          arguments will always agree.  */
17118       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17119                               INNERMOST_TEMPLATE_ARGS (args)))
17120     return NULL_TREE;
17121
17122   /* Now that we have bindings for all of the template arguments,
17123      ensure that the arguments deduced for the template template
17124      parameters have compatible template parameter lists.  See the use
17125      of template_template_parm_bindings_ok_p in fn_type_unification
17126      for more information.  */
17127   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17128     return NULL_TREE;
17129
17130   return deduced_args;
17131 }
17132
17133 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17134    Return the TREE_LIST node with the most specialized template, if
17135    any.  If there is no most specialized template, the error_mark_node
17136    is returned.
17137
17138    Note that this function does not look at, or modify, the
17139    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17140    returned is one of the elements of INSTANTIATIONS, callers may
17141    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17142    and retrieve it from the value returned.  */
17143
17144 tree
17145 most_specialized_instantiation (tree templates)
17146 {
17147   tree fn, champ;
17148
17149   ++processing_template_decl;
17150
17151   champ = templates;
17152   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17153     {
17154       int fate = 0;
17155
17156       if (get_bindings (TREE_VALUE (champ),
17157                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17158                         NULL_TREE, /*check_ret=*/true))
17159         fate--;
17160
17161       if (get_bindings (TREE_VALUE (fn),
17162                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17163                         NULL_TREE, /*check_ret=*/true))
17164         fate++;
17165
17166       if (fate == -1)
17167         champ = fn;
17168       else if (!fate)
17169         {
17170           /* Equally specialized, move to next function.  If there
17171              is no next function, nothing's most specialized.  */
17172           fn = TREE_CHAIN (fn);
17173           champ = fn;
17174           if (!fn)
17175             break;
17176         }
17177     }
17178
17179   if (champ)
17180     /* Now verify that champ is better than everything earlier in the
17181        instantiation list.  */
17182     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17183       if (get_bindings (TREE_VALUE (champ),
17184                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17185                         NULL_TREE, /*check_ret=*/true)
17186           || !get_bindings (TREE_VALUE (fn),
17187                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17188                             NULL_TREE, /*check_ret=*/true))
17189         {
17190           champ = NULL_TREE;
17191           break;
17192         }
17193
17194   processing_template_decl--;
17195
17196   if (!champ)
17197     return error_mark_node;
17198
17199   return champ;
17200 }
17201
17202 /* If DECL is a specialization of some template, return the most
17203    general such template.  Otherwise, returns NULL_TREE.
17204
17205    For example, given:
17206
17207      template <class T> struct S { template <class U> void f(U); };
17208
17209    if TMPL is `template <class U> void S<int>::f(U)' this will return
17210    the full template.  This function will not trace past partial
17211    specializations, however.  For example, given in addition:
17212
17213      template <class T> struct S<T*> { template <class U> void f(U); };
17214
17215    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17216    `template <class T> template <class U> S<T*>::f(U)'.  */
17217
17218 tree
17219 most_general_template (tree decl)
17220 {
17221   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17222      an immediate specialization.  */
17223   if (TREE_CODE (decl) == FUNCTION_DECL)
17224     {
17225       if (DECL_TEMPLATE_INFO (decl)) {
17226         decl = DECL_TI_TEMPLATE (decl);
17227
17228         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17229            template friend.  */
17230         if (TREE_CODE (decl) != TEMPLATE_DECL)
17231           return NULL_TREE;
17232       } else
17233         return NULL_TREE;
17234     }
17235
17236   /* Look for more and more general templates.  */
17237   while (DECL_TEMPLATE_INFO (decl))
17238     {
17239       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17240          (See cp-tree.h for details.)  */
17241       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17242         break;
17243
17244       if (CLASS_TYPE_P (TREE_TYPE (decl))
17245           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17246         break;
17247
17248       /* Stop if we run into an explicitly specialized class template.  */
17249       if (!DECL_NAMESPACE_SCOPE_P (decl)
17250           && DECL_CONTEXT (decl)
17251           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17252         break;
17253
17254       decl = DECL_TI_TEMPLATE (decl);
17255     }
17256
17257   return decl;
17258 }
17259
17260 /* Return the most specialized of the class template partial
17261    specializations of TMPL which can produce TYPE, a specialization of
17262    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17263    a _TYPE node corresponding to the partial specialization, while the
17264    TREE_PURPOSE is the set of template arguments that must be
17265    substituted into the TREE_TYPE in order to generate TYPE.
17266
17267    If the choice of partial specialization is ambiguous, a diagnostic
17268    is issued, and the error_mark_node is returned.  If there are no
17269    partial specializations of TMPL matching TYPE, then NULL_TREE is
17270    returned.  */
17271
17272 static tree
17273 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17274 {
17275   tree list = NULL_TREE;
17276   tree t;
17277   tree champ;
17278   int fate;
17279   bool ambiguous_p;
17280   tree args;
17281   tree outer_args = NULL_TREE;
17282
17283   tmpl = most_general_template (tmpl);
17284   args = CLASSTYPE_TI_ARGS (type);
17285
17286   /* For determining which partial specialization to use, only the
17287      innermost args are interesting.  */
17288   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17289     {
17290       outer_args = strip_innermost_template_args (args, 1);
17291       args = INNERMOST_TEMPLATE_ARGS (args);
17292     }
17293
17294   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17295     {
17296       tree partial_spec_args;
17297       tree spec_args;
17298       tree parms = TREE_VALUE (t);
17299
17300       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17301
17302       ++processing_template_decl;
17303
17304       if (outer_args)
17305         {
17306           int i;
17307
17308           /* Discard the outer levels of args, and then substitute in the
17309              template args from the enclosing class.  */
17310           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17311           partial_spec_args = tsubst_template_args
17312             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17313
17314           /* PARMS already refers to just the innermost parms, but the
17315              template parms in partial_spec_args had their levels lowered
17316              by tsubst, so we need to do the same for the parm list.  We
17317              can't just tsubst the TREE_VEC itself, as tsubst wants to
17318              treat a TREE_VEC as an argument vector.  */
17319           parms = copy_node (parms);
17320           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17321             TREE_VEC_ELT (parms, i) =
17322               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17323
17324         }
17325
17326       partial_spec_args =
17327           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17328                                  add_to_template_args (outer_args,
17329                                                        partial_spec_args),
17330                                  tmpl, tf_none,
17331                                  /*require_all_args=*/true,
17332                                  /*use_default_args=*/true);
17333
17334       --processing_template_decl;
17335
17336       if (partial_spec_args == error_mark_node)
17337         return error_mark_node;
17338
17339       spec_args = get_class_bindings (parms,
17340                                       partial_spec_args,
17341                                       args);
17342       if (spec_args)
17343         {
17344           if (outer_args)
17345             spec_args = add_to_template_args (outer_args, spec_args);
17346           list = tree_cons (spec_args, TREE_VALUE (t), list);
17347           TREE_TYPE (list) = TREE_TYPE (t);
17348         }
17349     }
17350
17351   if (! list)
17352     return NULL_TREE;
17353
17354   ambiguous_p = false;
17355   t = list;
17356   champ = t;
17357   t = TREE_CHAIN (t);
17358   for (; t; t = TREE_CHAIN (t))
17359     {
17360       fate = more_specialized_class (champ, t);
17361       if (fate == 1)
17362         ;
17363       else
17364         {
17365           if (fate == 0)
17366             {
17367               t = TREE_CHAIN (t);
17368               if (! t)
17369                 {
17370                   ambiguous_p = true;
17371                   break;
17372                 }
17373             }
17374           champ = t;
17375         }
17376     }
17377
17378   if (!ambiguous_p)
17379     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17380       {
17381         fate = more_specialized_class (champ, t);
17382         if (fate != 1)
17383           {
17384             ambiguous_p = true;
17385             break;
17386           }
17387       }
17388
17389   if (ambiguous_p)
17390     {
17391       const char *str;
17392       char *spaces = NULL;
17393       if (!(complain & tf_error))
17394         return error_mark_node;
17395       error ("ambiguous class template instantiation for %q#T", type);
17396       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17397       for (t = list; t; t = TREE_CHAIN (t))
17398         {
17399           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17400           spaces = spaces ? spaces : get_spaces (str);
17401         }
17402       free (spaces);
17403       return error_mark_node;
17404     }
17405
17406   return champ;
17407 }
17408
17409 /* Explicitly instantiate DECL.  */
17410
17411 void
17412 do_decl_instantiation (tree decl, tree storage)
17413 {
17414   tree result = NULL_TREE;
17415   int extern_p = 0;
17416
17417   if (!decl || decl == error_mark_node)
17418     /* An error occurred, for which grokdeclarator has already issued
17419        an appropriate message.  */
17420     return;
17421   else if (! DECL_LANG_SPECIFIC (decl))
17422     {
17423       error ("explicit instantiation of non-template %q#D", decl);
17424       return;
17425     }
17426   else if (TREE_CODE (decl) == VAR_DECL)
17427     {
17428       /* There is an asymmetry here in the way VAR_DECLs and
17429          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17430          the latter, the DECL we get back will be marked as a
17431          template instantiation, and the appropriate
17432          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17433          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17434          should handle VAR_DECLs as it currently handles
17435          FUNCTION_DECLs.  */
17436       if (!DECL_CLASS_SCOPE_P (decl))
17437         {
17438           error ("%qD is not a static data member of a class template", decl);
17439           return;
17440         }
17441       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17442       if (!result || TREE_CODE (result) != VAR_DECL)
17443         {
17444           error ("no matching template for %qD found", decl);
17445           return;
17446         }
17447       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17448         {
17449           error ("type %qT for explicit instantiation %qD does not match "
17450                  "declared type %qT", TREE_TYPE (result), decl,
17451                  TREE_TYPE (decl));
17452           return;
17453         }
17454     }
17455   else if (TREE_CODE (decl) != FUNCTION_DECL)
17456     {
17457       error ("explicit instantiation of %q#D", decl);
17458       return;
17459     }
17460   else
17461     result = decl;
17462
17463   /* Check for various error cases.  Note that if the explicit
17464      instantiation is valid the RESULT will currently be marked as an
17465      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17466      until we get here.  */
17467
17468   if (DECL_TEMPLATE_SPECIALIZATION (result))
17469     {
17470       /* DR 259 [temp.spec].
17471
17472          Both an explicit instantiation and a declaration of an explicit
17473          specialization shall not appear in a program unless the explicit
17474          instantiation follows a declaration of the explicit specialization.
17475
17476          For a given set of template parameters, if an explicit
17477          instantiation of a template appears after a declaration of an
17478          explicit specialization for that template, the explicit
17479          instantiation has no effect.  */
17480       return;
17481     }
17482   else if (DECL_EXPLICIT_INSTANTIATION (result))
17483     {
17484       /* [temp.spec]
17485
17486          No program shall explicitly instantiate any template more
17487          than once.
17488
17489          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17490          the first instantiation was `extern' and the second is not,
17491          and EXTERN_P for the opposite case.  */
17492       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17493         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17494       /* If an "extern" explicit instantiation follows an ordinary
17495          explicit instantiation, the template is instantiated.  */
17496       if (extern_p)
17497         return;
17498     }
17499   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17500     {
17501       error ("no matching template for %qD found", result);
17502       return;
17503     }
17504   else if (!DECL_TEMPLATE_INFO (result))
17505     {
17506       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17507       return;
17508     }
17509
17510   if (storage == NULL_TREE)
17511     ;
17512   else if (storage == ridpointers[(int) RID_EXTERN])
17513     {
17514       if (!in_system_header && (cxx_dialect == cxx98))
17515         pedwarn (input_location, OPT_pedantic, 
17516                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17517                  "instantiations");
17518       extern_p = 1;
17519     }
17520   else
17521     error ("storage class %qD applied to template instantiation", storage);
17522
17523   check_explicit_instantiation_namespace (result);
17524   mark_decl_instantiated (result, extern_p);
17525   if (! extern_p)
17526     instantiate_decl (result, /*defer_ok=*/1,
17527                       /*expl_inst_class_mem_p=*/false);
17528 }
17529
17530 static void
17531 mark_class_instantiated (tree t, int extern_p)
17532 {
17533   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17534   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17535   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17536   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17537   if (! extern_p)
17538     {
17539       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17540       rest_of_type_compilation (t, 1);
17541     }
17542 }
17543
17544 /* Called from do_type_instantiation through binding_table_foreach to
17545    do recursive instantiation for the type bound in ENTRY.  */
17546 static void
17547 bt_instantiate_type_proc (binding_entry entry, void *data)
17548 {
17549   tree storage = *(tree *) data;
17550
17551   if (MAYBE_CLASS_TYPE_P (entry->type)
17552       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17553     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17554 }
17555
17556 /* Called from do_type_instantiation to instantiate a member
17557    (a member function or a static member variable) of an
17558    explicitly instantiated class template.  */
17559 static void
17560 instantiate_class_member (tree decl, int extern_p)
17561 {
17562   mark_decl_instantiated (decl, extern_p);
17563   if (! extern_p)
17564     instantiate_decl (decl, /*defer_ok=*/1,
17565                       /*expl_inst_class_mem_p=*/true);
17566 }
17567
17568 /* Perform an explicit instantiation of template class T.  STORAGE, if
17569    non-null, is the RID for extern, inline or static.  COMPLAIN is
17570    nonzero if this is called from the parser, zero if called recursively,
17571    since the standard is unclear (as detailed below).  */
17572
17573 void
17574 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17575 {
17576   int extern_p = 0;
17577   int nomem_p = 0;
17578   int static_p = 0;
17579   int previous_instantiation_extern_p = 0;
17580
17581   if (TREE_CODE (t) == TYPE_DECL)
17582     t = TREE_TYPE (t);
17583
17584   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17585     {
17586       error ("explicit instantiation of non-template type %qT", t);
17587       return;
17588     }
17589
17590   complete_type (t);
17591
17592   if (!COMPLETE_TYPE_P (t))
17593     {
17594       if (complain & tf_error)
17595         error ("explicit instantiation of %q#T before definition of template",
17596                t);
17597       return;
17598     }
17599
17600   if (storage != NULL_TREE)
17601     {
17602       if (!in_system_header)
17603         {
17604           if (storage == ridpointers[(int) RID_EXTERN])
17605             {
17606               if (cxx_dialect == cxx98)
17607                 pedwarn (input_location, OPT_pedantic, 
17608                          "ISO C++ 1998 forbids the use of %<extern%> on "
17609                          "explicit instantiations");
17610             }
17611           else
17612             pedwarn (input_location, OPT_pedantic, 
17613                      "ISO C++ forbids the use of %qE"
17614                      " on explicit instantiations", storage);
17615         }
17616
17617       if (storage == ridpointers[(int) RID_INLINE])
17618         nomem_p = 1;
17619       else if (storage == ridpointers[(int) RID_EXTERN])
17620         extern_p = 1;
17621       else if (storage == ridpointers[(int) RID_STATIC])
17622         static_p = 1;
17623       else
17624         {
17625           error ("storage class %qD applied to template instantiation",
17626                  storage);
17627           extern_p = 0;
17628         }
17629     }
17630
17631   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17632     {
17633       /* DR 259 [temp.spec].
17634
17635          Both an explicit instantiation and a declaration of an explicit
17636          specialization shall not appear in a program unless the explicit
17637          instantiation follows a declaration of the explicit specialization.
17638
17639          For a given set of template parameters, if an explicit
17640          instantiation of a template appears after a declaration of an
17641          explicit specialization for that template, the explicit
17642          instantiation has no effect.  */
17643       return;
17644     }
17645   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17646     {
17647       /* [temp.spec]
17648
17649          No program shall explicitly instantiate any template more
17650          than once.
17651
17652          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17653          instantiation was `extern'.  If EXTERN_P then the second is.
17654          These cases are OK.  */
17655       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17656
17657       if (!previous_instantiation_extern_p && !extern_p
17658           && (complain & tf_error))
17659         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17660
17661       /* If we've already instantiated the template, just return now.  */
17662       if (!CLASSTYPE_INTERFACE_ONLY (t))
17663         return;
17664     }
17665
17666   check_explicit_instantiation_namespace (TYPE_NAME (t));
17667   mark_class_instantiated (t, extern_p);
17668
17669   if (nomem_p)
17670     return;
17671
17672   {
17673     tree tmp;
17674
17675     /* In contrast to implicit instantiation, where only the
17676        declarations, and not the definitions, of members are
17677        instantiated, we have here:
17678
17679          [temp.explicit]
17680
17681          The explicit instantiation of a class template specialization
17682          implies the instantiation of all of its members not
17683          previously explicitly specialized in the translation unit
17684          containing the explicit instantiation.
17685
17686        Of course, we can't instantiate member template classes, since
17687        we don't have any arguments for them.  Note that the standard
17688        is unclear on whether the instantiation of the members are
17689        *explicit* instantiations or not.  However, the most natural
17690        interpretation is that it should be an explicit instantiation.  */
17691
17692     if (! static_p)
17693       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17694         if (TREE_CODE (tmp) == FUNCTION_DECL
17695             && DECL_TEMPLATE_INSTANTIATION (tmp))
17696           instantiate_class_member (tmp, extern_p);
17697
17698     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17699       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17700         instantiate_class_member (tmp, extern_p);
17701
17702     if (CLASSTYPE_NESTED_UTDS (t))
17703       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17704                              bt_instantiate_type_proc, &storage);
17705   }
17706 }
17707
17708 /* Given a function DECL, which is a specialization of TMPL, modify
17709    DECL to be a re-instantiation of TMPL with the same template
17710    arguments.  TMPL should be the template into which tsubst'ing
17711    should occur for DECL, not the most general template.
17712
17713    One reason for doing this is a scenario like this:
17714
17715      template <class T>
17716      void f(const T&, int i);
17717
17718      void g() { f(3, 7); }
17719
17720      template <class T>
17721      void f(const T& t, const int i) { }
17722
17723    Note that when the template is first instantiated, with
17724    instantiate_template, the resulting DECL will have no name for the
17725    first parameter, and the wrong type for the second.  So, when we go
17726    to instantiate the DECL, we regenerate it.  */
17727
17728 static void
17729 regenerate_decl_from_template (tree decl, tree tmpl)
17730 {
17731   /* The arguments used to instantiate DECL, from the most general
17732      template.  */
17733   tree args;
17734   tree code_pattern;
17735
17736   args = DECL_TI_ARGS (decl);
17737   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17738
17739   /* Make sure that we can see identifiers, and compute access
17740      correctly.  */
17741   push_access_scope (decl);
17742
17743   if (TREE_CODE (decl) == FUNCTION_DECL)
17744     {
17745       tree decl_parm;
17746       tree pattern_parm;
17747       tree specs;
17748       int args_depth;
17749       int parms_depth;
17750
17751       args_depth = TMPL_ARGS_DEPTH (args);
17752       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17753       if (args_depth > parms_depth)
17754         args = get_innermost_template_args (args, parms_depth);
17755
17756       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17757                                               args, tf_error, NULL_TREE,
17758                                               /*defer_ok*/false);
17759       if (specs && specs != error_mark_node)
17760         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17761                                                     specs);
17762
17763       /* Merge parameter declarations.  */
17764       decl_parm = skip_artificial_parms_for (decl,
17765                                              DECL_ARGUMENTS (decl));
17766       pattern_parm
17767         = skip_artificial_parms_for (code_pattern,
17768                                      DECL_ARGUMENTS (code_pattern));
17769       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17770         {
17771           tree parm_type;
17772           tree attributes;
17773           
17774           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17775             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17776           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17777                               NULL_TREE);
17778           parm_type = type_decays_to (parm_type);
17779           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17780             TREE_TYPE (decl_parm) = parm_type;
17781           attributes = DECL_ATTRIBUTES (pattern_parm);
17782           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17783             {
17784               DECL_ATTRIBUTES (decl_parm) = attributes;
17785               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17786             }
17787           decl_parm = DECL_CHAIN (decl_parm);
17788           pattern_parm = DECL_CHAIN (pattern_parm);
17789         }
17790       /* Merge any parameters that match with the function parameter
17791          pack.  */
17792       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17793         {
17794           int i, len;
17795           tree expanded_types;
17796           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17797              the parameters in this function parameter pack.  */
17798           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17799                                                  args, tf_error, NULL_TREE);
17800           len = TREE_VEC_LENGTH (expanded_types);
17801           for (i = 0; i < len; i++)
17802             {
17803               tree parm_type;
17804               tree attributes;
17805           
17806               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17807                 /* Rename the parameter to include the index.  */
17808                 DECL_NAME (decl_parm) = 
17809                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17810               parm_type = TREE_VEC_ELT (expanded_types, i);
17811               parm_type = type_decays_to (parm_type);
17812               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17813                 TREE_TYPE (decl_parm) = parm_type;
17814               attributes = DECL_ATTRIBUTES (pattern_parm);
17815               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17816                 {
17817                   DECL_ATTRIBUTES (decl_parm) = attributes;
17818                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17819                 }
17820               decl_parm = DECL_CHAIN (decl_parm);
17821             }
17822         }
17823       /* Merge additional specifiers from the CODE_PATTERN.  */
17824       if (DECL_DECLARED_INLINE_P (code_pattern)
17825           && !DECL_DECLARED_INLINE_P (decl))
17826         DECL_DECLARED_INLINE_P (decl) = 1;
17827     }
17828   else if (TREE_CODE (decl) == VAR_DECL)
17829     {
17830       DECL_INITIAL (decl) =
17831         tsubst_expr (DECL_INITIAL (code_pattern), args,
17832                      tf_error, DECL_TI_TEMPLATE (decl),
17833                      /*integral_constant_expression_p=*/false);
17834       if (VAR_HAD_UNKNOWN_BOUND (decl))
17835         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17836                                    tf_error, DECL_TI_TEMPLATE (decl));
17837     }
17838   else
17839     gcc_unreachable ();
17840
17841   pop_access_scope (decl);
17842 }
17843
17844 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17845    substituted to get DECL.  */
17846
17847 tree
17848 template_for_substitution (tree decl)
17849 {
17850   tree tmpl = DECL_TI_TEMPLATE (decl);
17851
17852   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17853      for the instantiation.  This is not always the most general
17854      template.  Consider, for example:
17855
17856         template <class T>
17857         struct S { template <class U> void f();
17858                    template <> void f<int>(); };
17859
17860      and an instantiation of S<double>::f<int>.  We want TD to be the
17861      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17862   while (/* An instantiation cannot have a definition, so we need a
17863             more general template.  */
17864          DECL_TEMPLATE_INSTANTIATION (tmpl)
17865            /* We must also deal with friend templates.  Given:
17866
17867                 template <class T> struct S {
17868                   template <class U> friend void f() {};
17869                 };
17870
17871               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17872               so far as the language is concerned, but that's still
17873               where we get the pattern for the instantiation from.  On
17874               other hand, if the definition comes outside the class, say:
17875
17876                 template <class T> struct S {
17877                   template <class U> friend void f();
17878                 };
17879                 template <class U> friend void f() {}
17880
17881               we don't need to look any further.  That's what the check for
17882               DECL_INITIAL is for.  */
17883           || (TREE_CODE (decl) == FUNCTION_DECL
17884               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17885               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17886     {
17887       /* The present template, TD, should not be a definition.  If it
17888          were a definition, we should be using it!  Note that we
17889          cannot restructure the loop to just keep going until we find
17890          a template with a definition, since that might go too far if
17891          a specialization was declared, but not defined.  */
17892       gcc_assert (TREE_CODE (decl) != VAR_DECL
17893                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17894
17895       /* Fetch the more general template.  */
17896       tmpl = DECL_TI_TEMPLATE (tmpl);
17897     }
17898
17899   return tmpl;
17900 }
17901
17902 /* Returns true if we need to instantiate this template instance even if we
17903    know we aren't going to emit it..  */
17904
17905 bool
17906 always_instantiate_p (tree decl)
17907 {
17908   /* We always instantiate inline functions so that we can inline them.  An
17909      explicit instantiation declaration prohibits implicit instantiation of
17910      non-inline functions.  With high levels of optimization, we would
17911      normally inline non-inline functions -- but we're not allowed to do
17912      that for "extern template" functions.  Therefore, we check
17913      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17914   return ((TREE_CODE (decl) == FUNCTION_DECL
17915            && DECL_DECLARED_INLINE_P (decl))
17916           /* And we need to instantiate static data members so that
17917              their initializers are available in integral constant
17918              expressions.  */
17919           || (TREE_CODE (decl) == VAR_DECL
17920               && decl_maybe_constant_var_p (decl)));
17921 }
17922
17923 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17924    instantiate it now, modifying TREE_TYPE (fn).  */
17925
17926 void
17927 maybe_instantiate_noexcept (tree fn)
17928 {
17929   tree fntype, spec, noex, clone;
17930
17931   if (DECL_CLONED_FUNCTION_P (fn))
17932     fn = DECL_CLONED_FUNCTION (fn);
17933   fntype = TREE_TYPE (fn);
17934   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17935
17936   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17937     return;
17938
17939   noex = TREE_PURPOSE (spec);
17940
17941   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17942     {
17943       push_tinst_level (fn);
17944       push_access_scope (fn);
17945       input_location = DECL_SOURCE_LOCATION (fn);
17946       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17947                                     DEFERRED_NOEXCEPT_ARGS (noex),
17948                                     tf_warning_or_error, fn, /*function_p=*/false,
17949                                     /*integral_constant_expression_p=*/true);
17950       pop_access_scope (fn);
17951       pop_tinst_level ();
17952       spec = build_noexcept_spec (noex, tf_warning_or_error);
17953       if (spec == error_mark_node)
17954         spec = noexcept_false_spec;
17955     }
17956   else
17957     {
17958       /* This is an implicitly declared function, so NOEX is a list of
17959          other functions to evaluate and merge.  */
17960       tree elt;
17961       spec = noexcept_true_spec;
17962       for (elt = noex; elt; elt = OVL_NEXT (elt))
17963         {
17964           tree fn = OVL_CURRENT (elt);
17965           tree subspec;
17966           maybe_instantiate_noexcept (fn);
17967           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17968           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17969         }
17970     }
17971
17972   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17973
17974   FOR_EACH_CLONE (clone, fn)
17975     {
17976       if (TREE_TYPE (clone) == fntype)
17977         TREE_TYPE (clone) = TREE_TYPE (fn);
17978       else
17979         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
17980     }
17981 }
17982
17983 /* Produce the definition of D, a _DECL generated from a template.  If
17984    DEFER_OK is nonzero, then we don't have to actually do the
17985    instantiation now; we just have to do it sometime.  Normally it is
17986    an error if this is an explicit instantiation but D is undefined.
17987    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17988    explicitly instantiated class template.  */
17989
17990 tree
17991 instantiate_decl (tree d, int defer_ok,
17992                   bool expl_inst_class_mem_p)
17993 {
17994   tree tmpl = DECL_TI_TEMPLATE (d);
17995   tree gen_args;
17996   tree args;
17997   tree td;
17998   tree code_pattern;
17999   tree spec;
18000   tree gen_tmpl;
18001   bool pattern_defined;
18002   int need_push;
18003   location_t saved_loc = input_location;
18004   bool external_p;
18005
18006   /* This function should only be used to instantiate templates for
18007      functions and static member variables.  */
18008   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18009               || TREE_CODE (d) == VAR_DECL);
18010
18011   /* Variables are never deferred; if instantiation is required, they
18012      are instantiated right away.  That allows for better code in the
18013      case that an expression refers to the value of the variable --
18014      if the variable has a constant value the referring expression can
18015      take advantage of that fact.  */
18016   if (TREE_CODE (d) == VAR_DECL
18017       || DECL_DECLARED_CONSTEXPR_P (d))
18018     defer_ok = 0;
18019
18020   /* Don't instantiate cloned functions.  Instead, instantiate the
18021      functions they cloned.  */
18022   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18023     d = DECL_CLONED_FUNCTION (d);
18024
18025   if (DECL_TEMPLATE_INSTANTIATED (d)
18026       || DECL_TEMPLATE_SPECIALIZATION (d))
18027     /* D has already been instantiated or explicitly specialized, so
18028        there's nothing for us to do here.
18029
18030        It might seem reasonable to check whether or not D is an explicit
18031        instantiation, and, if so, stop here.  But when an explicit
18032        instantiation is deferred until the end of the compilation,
18033        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18034        the instantiation.  */
18035     return d;
18036
18037   /* Check to see whether we know that this template will be
18038      instantiated in some other file, as with "extern template"
18039      extension.  */
18040   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18041
18042   /* In general, we do not instantiate such templates.  */
18043   if (external_p && !always_instantiate_p (d))
18044     return d;
18045
18046   gen_tmpl = most_general_template (tmpl);
18047   gen_args = DECL_TI_ARGS (d);
18048
18049   if (tmpl != gen_tmpl)
18050     /* We should already have the extra args.  */
18051     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18052                 == TMPL_ARGS_DEPTH (gen_args));
18053   /* And what's in the hash table should match D.  */
18054   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18055               || spec == NULL_TREE);
18056
18057   /* This needs to happen before any tsubsting.  */
18058   if (! push_tinst_level (d))
18059     return d;
18060
18061   timevar_push (TV_TEMPLATE_INST);
18062
18063   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18064      for the instantiation.  */
18065   td = template_for_substitution (d);
18066   code_pattern = DECL_TEMPLATE_RESULT (td);
18067
18068   /* We should never be trying to instantiate a member of a class
18069      template or partial specialization.  */
18070   gcc_assert (d != code_pattern);
18071
18072   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18073       || DECL_TEMPLATE_SPECIALIZATION (td))
18074     /* In the case of a friend template whose definition is provided
18075        outside the class, we may have too many arguments.  Drop the
18076        ones we don't need.  The same is true for specializations.  */
18077     args = get_innermost_template_args
18078       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18079   else
18080     args = gen_args;
18081
18082   if (TREE_CODE (d) == FUNCTION_DECL)
18083     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18084                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18085   else
18086     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18087
18088   /* We may be in the middle of deferred access check.  Disable it now.  */
18089   push_deferring_access_checks (dk_no_deferred);
18090
18091   /* Unless an explicit instantiation directive has already determined
18092      the linkage of D, remember that a definition is available for
18093      this entity.  */
18094   if (pattern_defined
18095       && !DECL_INTERFACE_KNOWN (d)
18096       && !DECL_NOT_REALLY_EXTERN (d))
18097     mark_definable (d);
18098
18099   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18100   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18101   input_location = DECL_SOURCE_LOCATION (d);
18102
18103   /* If D is a member of an explicitly instantiated class template,
18104      and no definition is available, treat it like an implicit
18105      instantiation.  */
18106   if (!pattern_defined && expl_inst_class_mem_p
18107       && DECL_EXPLICIT_INSTANTIATION (d))
18108     {
18109       /* Leave linkage flags alone on instantiations with anonymous
18110          visibility.  */
18111       if (TREE_PUBLIC (d))
18112         {
18113           DECL_NOT_REALLY_EXTERN (d) = 0;
18114           DECL_INTERFACE_KNOWN (d) = 0;
18115         }
18116       SET_DECL_IMPLICIT_INSTANTIATION (d);
18117     }
18118
18119   if (TREE_CODE (d) == FUNCTION_DECL)
18120     maybe_instantiate_noexcept (d);
18121
18122   /* Recheck the substitutions to obtain any warning messages
18123      about ignoring cv qualifiers.  Don't do this for artificial decls,
18124      as it breaks the context-sensitive substitution for lambda op(). */
18125   if (!defer_ok && !DECL_ARTIFICIAL (d))
18126     {
18127       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18128       tree type = TREE_TYPE (gen);
18129
18130       /* Make sure that we can see identifiers, and compute access
18131          correctly.  D is already the target FUNCTION_DECL with the
18132          right context.  */
18133       push_access_scope (d);
18134
18135       if (TREE_CODE (gen) == FUNCTION_DECL)
18136         {
18137           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18138           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18139                                           d, /*defer_ok*/true);
18140           /* Don't simply tsubst the function type, as that will give
18141              duplicate warnings about poor parameter qualifications.
18142              The function arguments are the same as the decl_arguments
18143              without the top level cv qualifiers.  */
18144           type = TREE_TYPE (type);
18145         }
18146       tsubst (type, gen_args, tf_warning_or_error, d);
18147
18148       pop_access_scope (d);
18149     }
18150
18151   /* Defer all other templates, unless we have been explicitly
18152      forbidden from doing so.  */
18153   if (/* If there is no definition, we cannot instantiate the
18154          template.  */
18155       ! pattern_defined
18156       /* If it's OK to postpone instantiation, do so.  */
18157       || defer_ok
18158       /* If this is a static data member that will be defined
18159          elsewhere, we don't want to instantiate the entire data
18160          member, but we do want to instantiate the initializer so that
18161          we can substitute that elsewhere.  */
18162       || (external_p && TREE_CODE (d) == VAR_DECL))
18163     {
18164       /* The definition of the static data member is now required so
18165          we must substitute the initializer.  */
18166       if (TREE_CODE (d) == VAR_DECL
18167           && !DECL_INITIAL (d)
18168           && DECL_INITIAL (code_pattern))
18169         {
18170           tree ns;
18171           tree init;
18172           bool const_init = false;
18173
18174           ns = decl_namespace_context (d);
18175           push_nested_namespace (ns);
18176           push_nested_class (DECL_CONTEXT (d));
18177           init = tsubst_expr (DECL_INITIAL (code_pattern),
18178                               args,
18179                               tf_warning_or_error, NULL_TREE,
18180                               /*integral_constant_expression_p=*/false);
18181           /* Make sure the initializer is still constant, in case of
18182              circular dependency (template/instantiate6.C). */
18183           const_init
18184             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18185           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18186                           /*asmspec_tree=*/NULL_TREE,
18187                           LOOKUP_ONLYCONVERTING);
18188           pop_nested_class ();
18189           pop_nested_namespace (ns);
18190         }
18191
18192       /* We restore the source position here because it's used by
18193          add_pending_template.  */
18194       input_location = saved_loc;
18195
18196       if (at_eof && !pattern_defined
18197           && DECL_EXPLICIT_INSTANTIATION (d)
18198           && DECL_NOT_REALLY_EXTERN (d))
18199         /* [temp.explicit]
18200
18201            The definition of a non-exported function template, a
18202            non-exported member function template, or a non-exported
18203            member function or static data member of a class template
18204            shall be present in every translation unit in which it is
18205            explicitly instantiated.  */
18206         permerror (input_location,  "explicit instantiation of %qD "
18207                    "but no definition available", d);
18208
18209       /* If we're in unevaluated context, we just wanted to get the
18210          constant value; this isn't an odr use, so don't queue
18211          a full instantiation.  */
18212       if (cp_unevaluated_operand != 0)
18213         goto out;
18214       /* ??? Historically, we have instantiated inline functions, even
18215          when marked as "extern template".  */
18216       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18217         add_pending_template (d);
18218       goto out;
18219     }
18220   /* Tell the repository that D is available in this translation unit
18221      -- and see if it is supposed to be instantiated here.  */
18222   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18223     {
18224       /* In a PCH file, despite the fact that the repository hasn't
18225          requested instantiation in the PCH it is still possible that
18226          an instantiation will be required in a file that includes the
18227          PCH.  */
18228       if (pch_file)
18229         add_pending_template (d);
18230       /* Instantiate inline functions so that the inliner can do its
18231          job, even though we'll not be emitting a copy of this
18232          function.  */
18233       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18234         goto out;
18235     }
18236
18237   need_push = !cfun || !global_bindings_p ();
18238   if (need_push)
18239     push_to_top_level ();
18240
18241   /* Mark D as instantiated so that recursive calls to
18242      instantiate_decl do not try to instantiate it again.  */
18243   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18244
18245   /* Regenerate the declaration in case the template has been modified
18246      by a subsequent redeclaration.  */
18247   regenerate_decl_from_template (d, td);
18248
18249   /* We already set the file and line above.  Reset them now in case
18250      they changed as a result of calling regenerate_decl_from_template.  */
18251   input_location = DECL_SOURCE_LOCATION (d);
18252
18253   if (TREE_CODE (d) == VAR_DECL)
18254     {
18255       tree init;
18256       bool const_init = false;
18257
18258       /* Clear out DECL_RTL; whatever was there before may not be right
18259          since we've reset the type of the declaration.  */
18260       SET_DECL_RTL (d, NULL);
18261       DECL_IN_AGGR_P (d) = 0;
18262
18263       /* The initializer is placed in DECL_INITIAL by
18264          regenerate_decl_from_template so we don't need to
18265          push/pop_access_scope again here.  Pull it out so that
18266          cp_finish_decl can process it.  */
18267       init = DECL_INITIAL (d);
18268       DECL_INITIAL (d) = NULL_TREE;
18269       DECL_INITIALIZED_P (d) = 0;
18270
18271       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18272          initializer.  That function will defer actual emission until
18273          we have a chance to determine linkage.  */
18274       DECL_EXTERNAL (d) = 0;
18275
18276       /* Enter the scope of D so that access-checking works correctly.  */
18277       push_nested_class (DECL_CONTEXT (d));
18278       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18279       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18280       pop_nested_class ();
18281     }
18282   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18283     synthesize_method (d);
18284   else if (TREE_CODE (d) == FUNCTION_DECL)
18285     {
18286       htab_t saved_local_specializations;
18287       tree subst_decl;
18288       tree tmpl_parm;
18289       tree spec_parm;
18290
18291       /* Save away the current list, in case we are instantiating one
18292          template from within the body of another.  */
18293       saved_local_specializations = local_specializations;
18294
18295       /* Set up the list of local specializations.  */
18296       local_specializations = htab_create (37,
18297                                            hash_local_specialization,
18298                                            eq_local_specializations,
18299                                            NULL);
18300
18301       /* Set up context.  */
18302       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18303
18304       /* Create substitution entries for the parameters.  */
18305       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18306       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18307       spec_parm = DECL_ARGUMENTS (d);
18308       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18309         {
18310           register_local_specialization (spec_parm, tmpl_parm);
18311           spec_parm = skip_artificial_parms_for (d, spec_parm);
18312           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18313         }
18314       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18315         {
18316           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18317             {
18318               register_local_specialization (spec_parm, tmpl_parm);
18319               spec_parm = DECL_CHAIN (spec_parm);
18320             }
18321           else
18322             {
18323               /* Register the (value) argument pack as a specialization of
18324                  TMPL_PARM, then move on.  */
18325               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18326               register_local_specialization (argpack, tmpl_parm);
18327             }
18328         }
18329       gcc_assert (!spec_parm);
18330
18331       /* Substitute into the body of the function.  */
18332       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18333                    tf_warning_or_error, tmpl,
18334                    /*integral_constant_expression_p=*/false);
18335
18336       /* Set the current input_location to the end of the function
18337          so that finish_function knows where we are.  */
18338       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18339
18340       /* We don't need the local specializations any more.  */
18341       htab_delete (local_specializations);
18342       local_specializations = saved_local_specializations;
18343
18344       /* Finish the function.  */
18345       d = finish_function (0);
18346       expand_or_defer_fn (d);
18347     }
18348
18349   /* We're not deferring instantiation any more.  */
18350   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18351
18352   if (need_push)
18353     pop_from_top_level ();
18354
18355 out:
18356   input_location = saved_loc;
18357   pop_deferring_access_checks ();
18358   pop_tinst_level ();
18359
18360   timevar_pop (TV_TEMPLATE_INST);
18361
18362   return d;
18363 }
18364
18365 /* Run through the list of templates that we wish we could
18366    instantiate, and instantiate any we can.  RETRIES is the
18367    number of times we retry pending template instantiation.  */
18368
18369 void
18370 instantiate_pending_templates (int retries)
18371 {
18372   int reconsider;
18373   location_t saved_loc = input_location;
18374
18375   /* Instantiating templates may trigger vtable generation.  This in turn
18376      may require further template instantiations.  We place a limit here
18377      to avoid infinite loop.  */
18378   if (pending_templates && retries >= max_tinst_depth)
18379     {
18380       tree decl = pending_templates->tinst->decl;
18381
18382       error ("template instantiation depth exceeds maximum of %d"
18383              " instantiating %q+D, possibly from virtual table generation"
18384              " (use -ftemplate-depth= to increase the maximum)",
18385              max_tinst_depth, decl);
18386       if (TREE_CODE (decl) == FUNCTION_DECL)
18387         /* Pretend that we defined it.  */
18388         DECL_INITIAL (decl) = error_mark_node;
18389       return;
18390     }
18391
18392   do
18393     {
18394       struct pending_template **t = &pending_templates;
18395       struct pending_template *last = NULL;
18396       reconsider = 0;
18397       while (*t)
18398         {
18399           tree instantiation = reopen_tinst_level ((*t)->tinst);
18400           bool complete = false;
18401
18402           if (TYPE_P (instantiation))
18403             {
18404               tree fn;
18405
18406               if (!COMPLETE_TYPE_P (instantiation))
18407                 {
18408                   instantiate_class_template (instantiation);
18409                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18410                     for (fn = TYPE_METHODS (instantiation);
18411                          fn;
18412                          fn = TREE_CHAIN (fn))
18413                       if (! DECL_ARTIFICIAL (fn))
18414                         instantiate_decl (fn,
18415                                           /*defer_ok=*/0,
18416                                           /*expl_inst_class_mem_p=*/false);
18417                   if (COMPLETE_TYPE_P (instantiation))
18418                     reconsider = 1;
18419                 }
18420
18421               complete = COMPLETE_TYPE_P (instantiation);
18422             }
18423           else
18424             {
18425               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18426                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18427                 {
18428                   instantiation
18429                     = instantiate_decl (instantiation,
18430                                         /*defer_ok=*/0,
18431                                         /*expl_inst_class_mem_p=*/false);
18432                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18433                     reconsider = 1;
18434                 }
18435
18436               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18437                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18438             }
18439
18440           if (complete)
18441             /* If INSTANTIATION has been instantiated, then we don't
18442                need to consider it again in the future.  */
18443             *t = (*t)->next;
18444           else
18445             {
18446               last = *t;
18447               t = &(*t)->next;
18448             }
18449           tinst_depth = 0;
18450           current_tinst_level = NULL;
18451         }
18452       last_pending_template = last;
18453     }
18454   while (reconsider);
18455
18456   input_location = saved_loc;
18457 }
18458
18459 /* Substitute ARGVEC into T, which is a list of initializers for
18460    either base class or a non-static data member.  The TREE_PURPOSEs
18461    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18462    instantiate_decl.  */
18463
18464 static tree
18465 tsubst_initializer_list (tree t, tree argvec)
18466 {
18467   tree inits = NULL_TREE;
18468
18469   for (; t; t = TREE_CHAIN (t))
18470     {
18471       tree decl;
18472       tree init;
18473       tree expanded_bases = NULL_TREE;
18474       tree expanded_arguments = NULL_TREE;
18475       int i, len = 1;
18476
18477       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18478         {
18479           tree expr;
18480           tree arg;
18481
18482           /* Expand the base class expansion type into separate base
18483              classes.  */
18484           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18485                                                  tf_warning_or_error,
18486                                                  NULL_TREE);
18487           if (expanded_bases == error_mark_node)
18488             continue;
18489           
18490           /* We'll be building separate TREE_LISTs of arguments for
18491              each base.  */
18492           len = TREE_VEC_LENGTH (expanded_bases);
18493           expanded_arguments = make_tree_vec (len);
18494           for (i = 0; i < len; i++)
18495             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18496
18497           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18498              expand each argument in the TREE_VALUE of t.  */
18499           expr = make_node (EXPR_PACK_EXPANSION);
18500           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18501             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18502
18503           if (TREE_VALUE (t) == void_type_node)
18504             /* VOID_TYPE_NODE is used to indicate
18505                value-initialization.  */
18506             {
18507               for (i = 0; i < len; i++)
18508                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18509             }
18510           else
18511             {
18512               /* Substitute parameter packs into each argument in the
18513                  TREE_LIST.  */
18514               in_base_initializer = 1;
18515               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18516                 {
18517                   tree expanded_exprs;
18518
18519                   /* Expand the argument.  */
18520                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18521                   expanded_exprs 
18522                     = tsubst_pack_expansion (expr, argvec,
18523                                              tf_warning_or_error,
18524                                              NULL_TREE);
18525                   if (expanded_exprs == error_mark_node)
18526                     continue;
18527
18528                   /* Prepend each of the expanded expressions to the
18529                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18530                   for (i = 0; i < len; i++)
18531                     {
18532                       TREE_VEC_ELT (expanded_arguments, i) = 
18533                         tree_cons (NULL_TREE, 
18534                                    TREE_VEC_ELT (expanded_exprs, i),
18535                                    TREE_VEC_ELT (expanded_arguments, i));
18536                     }
18537                 }
18538               in_base_initializer = 0;
18539
18540               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18541                  since we built them backwards.  */
18542               for (i = 0; i < len; i++)
18543                 {
18544                   TREE_VEC_ELT (expanded_arguments, i) = 
18545                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18546                 }
18547             }
18548         }
18549
18550       for (i = 0; i < len; ++i)
18551         {
18552           if (expanded_bases)
18553             {
18554               decl = TREE_VEC_ELT (expanded_bases, i);
18555               decl = expand_member_init (decl);
18556               init = TREE_VEC_ELT (expanded_arguments, i);
18557             }
18558           else
18559             {
18560               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18561                                   tf_warning_or_error, NULL_TREE);
18562
18563               decl = expand_member_init (decl);
18564               if (decl && !DECL_P (decl))
18565                 in_base_initializer = 1;
18566
18567               init = TREE_VALUE (t);
18568               if (init != void_type_node)
18569                 init = tsubst_expr (init, argvec,
18570                                     tf_warning_or_error, NULL_TREE,
18571                                     /*integral_constant_expression_p=*/false);
18572               in_base_initializer = 0;
18573             }
18574
18575           if (decl)
18576             {
18577               init = build_tree_list (decl, init);
18578               TREE_CHAIN (init) = inits;
18579               inits = init;
18580             }
18581         }
18582     }
18583   return inits;
18584 }
18585
18586 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18587
18588 static void
18589 set_current_access_from_decl (tree decl)
18590 {
18591   if (TREE_PRIVATE (decl))
18592     current_access_specifier = access_private_node;
18593   else if (TREE_PROTECTED (decl))
18594     current_access_specifier = access_protected_node;
18595   else
18596     current_access_specifier = access_public_node;
18597 }
18598
18599 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18600    is the instantiation (which should have been created with
18601    start_enum) and ARGS are the template arguments to use.  */
18602
18603 static void
18604 tsubst_enum (tree tag, tree newtag, tree args)
18605 {
18606   tree e;
18607
18608   if (SCOPED_ENUM_P (newtag))
18609     begin_scope (sk_scoped_enum, newtag);
18610
18611   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18612     {
18613       tree value;
18614       tree decl;
18615
18616       decl = TREE_VALUE (e);
18617       /* Note that in a template enum, the TREE_VALUE is the
18618          CONST_DECL, not the corresponding INTEGER_CST.  */
18619       value = tsubst_expr (DECL_INITIAL (decl),
18620                            args, tf_warning_or_error, NULL_TREE,
18621                            /*integral_constant_expression_p=*/true);
18622
18623       /* Give this enumeration constant the correct access.  */
18624       set_current_access_from_decl (decl);
18625
18626       /* Actually build the enumerator itself.  */
18627       build_enumerator
18628         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18629     }
18630
18631   if (SCOPED_ENUM_P (newtag))
18632     finish_scope ();
18633
18634   finish_enum_value_list (newtag);
18635   finish_enum (newtag);
18636
18637   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18638     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18639 }
18640
18641 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18642    its type -- but without substituting the innermost set of template
18643    arguments.  So, innermost set of template parameters will appear in
18644    the type.  */
18645
18646 tree
18647 get_mostly_instantiated_function_type (tree decl)
18648 {
18649   tree fn_type;
18650   tree tmpl;
18651   tree targs;
18652   tree tparms;
18653   int parm_depth;
18654
18655   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18656   targs = DECL_TI_ARGS (decl);
18657   tparms = DECL_TEMPLATE_PARMS (tmpl);
18658   parm_depth = TMPL_PARMS_DEPTH (tparms);
18659
18660   /* There should be as many levels of arguments as there are levels
18661      of parameters.  */
18662   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18663
18664   fn_type = TREE_TYPE (tmpl);
18665
18666   if (parm_depth == 1)
18667     /* No substitution is necessary.  */
18668     ;
18669   else
18670     {
18671       int i;
18672       tree partial_args;
18673
18674       /* Replace the innermost level of the TARGS with NULL_TREEs to
18675          let tsubst know not to substitute for those parameters.  */
18676       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18677       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18678         SET_TMPL_ARGS_LEVEL (partial_args, i,
18679                              TMPL_ARGS_LEVEL (targs, i));
18680       SET_TMPL_ARGS_LEVEL (partial_args,
18681                            TMPL_ARGS_DEPTH (targs),
18682                            make_tree_vec (DECL_NTPARMS (tmpl)));
18683
18684       /* Make sure that we can see identifiers, and compute access
18685          correctly.  */
18686       push_access_scope (decl);
18687
18688       ++processing_template_decl;
18689       /* Now, do the (partial) substitution to figure out the
18690          appropriate function type.  */
18691       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18692       --processing_template_decl;
18693
18694       /* Substitute into the template parameters to obtain the real
18695          innermost set of parameters.  This step is important if the
18696          innermost set of template parameters contains value
18697          parameters whose types depend on outer template parameters.  */
18698       TREE_VEC_LENGTH (partial_args)--;
18699       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18700
18701       pop_access_scope (decl);
18702     }
18703
18704   return fn_type;
18705 }
18706
18707 /* Return truthvalue if we're processing a template different from
18708    the last one involved in diagnostics.  */
18709 int
18710 problematic_instantiation_changed (void)
18711 {
18712   return current_tinst_level != last_error_tinst_level;
18713 }
18714
18715 /* Remember current template involved in diagnostics.  */
18716 void
18717 record_last_problematic_instantiation (void)
18718 {
18719   last_error_tinst_level = current_tinst_level;
18720 }
18721
18722 struct tinst_level *
18723 current_instantiation (void)
18724 {
18725   return current_tinst_level;
18726 }
18727
18728 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18729    type. Return zero for ok, nonzero for disallowed. Issue error and
18730    warning messages under control of COMPLAIN.  */
18731
18732 static int
18733 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18734 {
18735   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18736     return 0;
18737   else if (POINTER_TYPE_P (type))
18738     return 0;
18739   else if (TYPE_PTR_TO_MEMBER_P (type))
18740     return 0;
18741   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18742     return 0;
18743   else if (TREE_CODE (type) == TYPENAME_TYPE)
18744     return 0;
18745   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18746     return 0;
18747   else if (TREE_CODE (type) == NULLPTR_TYPE)
18748     return 0;
18749
18750   if (complain & tf_error)
18751     error ("%q#T is not a valid type for a template constant parameter", type);
18752   return 1;
18753 }
18754
18755 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18756    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18757
18758 static bool
18759 dependent_type_p_r (tree type)
18760 {
18761   tree scope;
18762
18763   /* [temp.dep.type]
18764
18765      A type is dependent if it is:
18766
18767      -- a template parameter. Template template parameters are types
18768         for us (since TYPE_P holds true for them) so we handle
18769         them here.  */
18770   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18771       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18772     return true;
18773   /* -- a qualified-id with a nested-name-specifier which contains a
18774         class-name that names a dependent type or whose unqualified-id
18775         names a dependent type.  */
18776   if (TREE_CODE (type) == TYPENAME_TYPE)
18777     return true;
18778   /* -- a cv-qualified type where the cv-unqualified type is
18779         dependent.  */
18780   type = TYPE_MAIN_VARIANT (type);
18781   /* -- a compound type constructed from any dependent type.  */
18782   if (TYPE_PTR_TO_MEMBER_P (type))
18783     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18784             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18785                                            (type)));
18786   else if (TREE_CODE (type) == POINTER_TYPE
18787            || TREE_CODE (type) == REFERENCE_TYPE)
18788     return dependent_type_p (TREE_TYPE (type));
18789   else if (TREE_CODE (type) == FUNCTION_TYPE
18790            || TREE_CODE (type) == METHOD_TYPE)
18791     {
18792       tree arg_type;
18793
18794       if (dependent_type_p (TREE_TYPE (type)))
18795         return true;
18796       for (arg_type = TYPE_ARG_TYPES (type);
18797            arg_type;
18798            arg_type = TREE_CHAIN (arg_type))
18799         if (dependent_type_p (TREE_VALUE (arg_type)))
18800           return true;
18801       return false;
18802     }
18803   /* -- an array type constructed from any dependent type or whose
18804         size is specified by a constant expression that is
18805         value-dependent.
18806
18807         We checked for type- and value-dependence of the bounds in
18808         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18809   if (TREE_CODE (type) == ARRAY_TYPE)
18810     {
18811       if (TYPE_DOMAIN (type)
18812           && dependent_type_p (TYPE_DOMAIN (type)))
18813         return true;
18814       return dependent_type_p (TREE_TYPE (type));
18815     }
18816
18817   /* -- a template-id in which either the template name is a template
18818      parameter ...  */
18819   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18820     return true;
18821   /* ... or any of the template arguments is a dependent type or
18822         an expression that is type-dependent or value-dependent.  */
18823   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18824            && (any_dependent_template_arguments_p
18825                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18826     return true;
18827
18828   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18829      dependent; if the argument of the `typeof' expression is not
18830      type-dependent, then it should already been have resolved.  */
18831   if (TREE_CODE (type) == TYPEOF_TYPE
18832       || TREE_CODE (type) == DECLTYPE_TYPE
18833       || TREE_CODE (type) == UNDERLYING_TYPE)
18834     return true;
18835
18836   /* A template argument pack is dependent if any of its packed
18837      arguments are.  */
18838   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18839     {
18840       tree args = ARGUMENT_PACK_ARGS (type);
18841       int i, len = TREE_VEC_LENGTH (args);
18842       for (i = 0; i < len; ++i)
18843         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18844           return true;
18845     }
18846
18847   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18848      be template parameters.  */
18849   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18850     return true;
18851
18852   /* The standard does not specifically mention types that are local
18853      to template functions or local classes, but they should be
18854      considered dependent too.  For example:
18855
18856        template <int I> void f() {
18857          enum E { a = I };
18858          S<sizeof (E)> s;
18859        }
18860
18861      The size of `E' cannot be known until the value of `I' has been
18862      determined.  Therefore, `E' must be considered dependent.  */
18863   scope = TYPE_CONTEXT (type);
18864   if (scope && TYPE_P (scope))
18865     return dependent_type_p (scope);
18866   /* Don't use type_dependent_expression_p here, as it can lead
18867      to infinite recursion trying to determine whether a lambda
18868      nested in a lambda is dependent (c++/47687).  */
18869   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18870            && DECL_LANG_SPECIFIC (scope)
18871            && DECL_TEMPLATE_INFO (scope)
18872            && (any_dependent_template_arguments_p
18873                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18874     return true;
18875
18876   /* Other types are non-dependent.  */
18877   return false;
18878 }
18879
18880 /* Returns TRUE if TYPE is dependent, in the sense of
18881    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18882
18883 bool
18884 dependent_type_p (tree type)
18885 {
18886   /* If there are no template parameters in scope, then there can't be
18887      any dependent types.  */
18888   if (!processing_template_decl)
18889     {
18890       /* If we are not processing a template, then nobody should be
18891          providing us with a dependent type.  */
18892       gcc_assert (type);
18893       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18894       return false;
18895     }
18896
18897   /* If the type is NULL, we have not computed a type for the entity
18898      in question; in that case, the type is dependent.  */
18899   if (!type)
18900     return true;
18901
18902   /* Erroneous types can be considered non-dependent.  */
18903   if (type == error_mark_node)
18904     return false;
18905
18906   /* If we have not already computed the appropriate value for TYPE,
18907      do so now.  */
18908   if (!TYPE_DEPENDENT_P_VALID (type))
18909     {
18910       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18911       TYPE_DEPENDENT_P_VALID (type) = 1;
18912     }
18913
18914   return TYPE_DEPENDENT_P (type);
18915 }
18916
18917 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18918    lookup.  In other words, a dependent type that is not the current
18919    instantiation.  */
18920
18921 bool
18922 dependent_scope_p (tree scope)
18923 {
18924   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18925           && !currently_open_class (scope));
18926 }
18927
18928 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18929    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18930    expression.  */
18931
18932 /* Note that this predicate is not appropriate for general expressions;
18933    only constant expressions (that satisfy potential_constant_expression)
18934    can be tested for value dependence.
18935
18936    We should really also have a predicate for "instantiation-dependent".
18937
18938    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18939      (what about instantiation-dependent constant-expressions?)
18940    is_late_template_attribute: defer if instantiation-dependent.
18941    compute_array_index_type: proceed if constant and not t- or v-dependent
18942      if instantiation-dependent, need to remember full expression
18943    uses_template_parms: FIXME - need to audit callers
18944    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18945    dependent_type_p [array_type]: dependent if index type is dependent
18946      (or non-constant?)
18947    static_assert - instantiation-dependent */
18948
18949 bool
18950 value_dependent_expression_p (tree expression)
18951 {
18952   if (!processing_template_decl)
18953     return false;
18954
18955   /* A name declared with a dependent type.  */
18956   if (DECL_P (expression) && type_dependent_expression_p (expression))
18957     return true;
18958
18959   switch (TREE_CODE (expression))
18960     {
18961     case IDENTIFIER_NODE:
18962       /* A name that has not been looked up -- must be dependent.  */
18963       return true;
18964
18965     case TEMPLATE_PARM_INDEX:
18966       /* A non-type template parm.  */
18967       return true;
18968
18969     case CONST_DECL:
18970       /* A non-type template parm.  */
18971       if (DECL_TEMPLATE_PARM_P (expression))
18972         return true;
18973       return value_dependent_expression_p (DECL_INITIAL (expression));
18974
18975     case VAR_DECL:
18976        /* A constant with literal type and is initialized
18977           with an expression that is value-dependent.  */
18978       if (DECL_INITIAL (expression)
18979           && decl_constant_var_p (expression)
18980           && value_dependent_expression_p (DECL_INITIAL (expression)))
18981         return true;
18982       return false;
18983
18984     case DYNAMIC_CAST_EXPR:
18985     case STATIC_CAST_EXPR:
18986     case CONST_CAST_EXPR:
18987     case REINTERPRET_CAST_EXPR:
18988     case CAST_EXPR:
18989       /* These expressions are value-dependent if the type to which
18990          the cast occurs is dependent or the expression being casted
18991          is value-dependent.  */
18992       {
18993         tree type = TREE_TYPE (expression);
18994
18995         if (dependent_type_p (type))
18996           return true;
18997
18998         /* A functional cast has a list of operands.  */
18999         expression = TREE_OPERAND (expression, 0);
19000         if (!expression)
19001           {
19002             /* If there are no operands, it must be an expression such
19003                as "int()". This should not happen for aggregate types
19004                because it would form non-constant expressions.  */
19005             gcc_assert (cxx_dialect >= cxx0x
19006                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19007
19008             return false;
19009           }
19010
19011         if (TREE_CODE (expression) == TREE_LIST)
19012           return any_value_dependent_elements_p (expression);
19013
19014         return value_dependent_expression_p (expression);
19015       }
19016
19017     case SIZEOF_EXPR:
19018     case ALIGNOF_EXPR:
19019     case TYPEID_EXPR:
19020       /* A `sizeof' expression is value-dependent if the operand is
19021          type-dependent or is a pack expansion.  */
19022       expression = TREE_OPERAND (expression, 0);
19023       if (PACK_EXPANSION_P (expression))
19024         return true;
19025       else if (TYPE_P (expression))
19026         return dependent_type_p (expression);
19027       return type_dependent_expression_p (expression);
19028
19029     case AT_ENCODE_EXPR:
19030       /* An 'encode' expression is value-dependent if the operand is
19031          type-dependent.  */
19032       expression = TREE_OPERAND (expression, 0);
19033       return dependent_type_p (expression);
19034
19035     case NOEXCEPT_EXPR:
19036       expression = TREE_OPERAND (expression, 0);
19037       return type_dependent_expression_p (expression);
19038
19039     case SCOPE_REF:
19040       {
19041         tree name = TREE_OPERAND (expression, 1);
19042         return value_dependent_expression_p (name);
19043       }
19044
19045     case COMPONENT_REF:
19046       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19047               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19048
19049     case NONTYPE_ARGUMENT_PACK:
19050       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19051          is value-dependent.  */
19052       {
19053         tree values = ARGUMENT_PACK_ARGS (expression);
19054         int i, len = TREE_VEC_LENGTH (values);
19055         
19056         for (i = 0; i < len; ++i)
19057           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19058             return true;
19059         
19060         return false;
19061       }
19062
19063     case TRAIT_EXPR:
19064       {
19065         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19066         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19067                 || (type2 ? dependent_type_p (type2) : false));
19068       }
19069
19070     case MODOP_EXPR:
19071       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19072               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19073
19074     case ARRAY_REF:
19075       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19076               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19077
19078     case ADDR_EXPR:
19079       {
19080         tree op = TREE_OPERAND (expression, 0);
19081         return (value_dependent_expression_p (op)
19082                 || has_value_dependent_address (op));
19083       }
19084
19085     case CALL_EXPR:
19086       {
19087         tree fn = get_callee_fndecl (expression);
19088         int i, nargs;
19089         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19090           return true;
19091         nargs = call_expr_nargs (expression);
19092         for (i = 0; i < nargs; ++i)
19093           {
19094             tree op = CALL_EXPR_ARG (expression, i);
19095             /* In a call to a constexpr member function, look through the
19096                implicit ADDR_EXPR on the object argument so that it doesn't
19097                cause the call to be considered value-dependent.  We also
19098                look through it in potential_constant_expression.  */
19099             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19100                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19101                 && TREE_CODE (op) == ADDR_EXPR)
19102               op = TREE_OPERAND (op, 0);
19103             if (value_dependent_expression_p (op))
19104               return true;
19105           }
19106         return false;
19107       }
19108
19109     case TEMPLATE_ID_EXPR:
19110       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19111          type-dependent.  */
19112       return type_dependent_expression_p (expression);
19113
19114     case CONSTRUCTOR:
19115       {
19116         unsigned ix;
19117         tree val;
19118         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19119           if (value_dependent_expression_p (val))
19120             return true;
19121         return false;
19122       }
19123
19124     default:
19125       /* A constant expression is value-dependent if any subexpression is
19126          value-dependent.  */
19127       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19128         {
19129         case tcc_reference:
19130         case tcc_unary:
19131         case tcc_comparison:
19132         case tcc_binary:
19133         case tcc_expression:
19134         case tcc_vl_exp:
19135           {
19136             int i, len = cp_tree_operand_length (expression);
19137
19138             for (i = 0; i < len; i++)
19139               {
19140                 tree t = TREE_OPERAND (expression, i);
19141
19142                 /* In some cases, some of the operands may be missing.l
19143                    (For example, in the case of PREDECREMENT_EXPR, the
19144                    amount to increment by may be missing.)  That doesn't
19145                    make the expression dependent.  */
19146                 if (t && value_dependent_expression_p (t))
19147                   return true;
19148               }
19149           }
19150           break;
19151         default:
19152           break;
19153         }
19154       break;
19155     }
19156
19157   /* The expression is not value-dependent.  */
19158   return false;
19159 }
19160
19161 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19162    [temp.dep.expr].  Note that an expression with no type is
19163    considered dependent.  Other parts of the compiler arrange for an
19164    expression with type-dependent subexpressions to have no type, so
19165    this function doesn't have to be fully recursive.  */
19166
19167 bool
19168 type_dependent_expression_p (tree expression)
19169 {
19170   if (!processing_template_decl)
19171     return false;
19172
19173   if (expression == error_mark_node)
19174     return false;
19175
19176   /* An unresolved name is always dependent.  */
19177   if (TREE_CODE (expression) == IDENTIFIER_NODE
19178       || TREE_CODE (expression) == USING_DECL)
19179     return true;
19180
19181   /* Some expression forms are never type-dependent.  */
19182   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19183       || TREE_CODE (expression) == SIZEOF_EXPR
19184       || TREE_CODE (expression) == ALIGNOF_EXPR
19185       || TREE_CODE (expression) == AT_ENCODE_EXPR
19186       || TREE_CODE (expression) == NOEXCEPT_EXPR
19187       || TREE_CODE (expression) == TRAIT_EXPR
19188       || TREE_CODE (expression) == TYPEID_EXPR
19189       || TREE_CODE (expression) == DELETE_EXPR
19190       || TREE_CODE (expression) == VEC_DELETE_EXPR
19191       || TREE_CODE (expression) == THROW_EXPR)
19192     return false;
19193
19194   /* The types of these expressions depends only on the type to which
19195      the cast occurs.  */
19196   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19197       || TREE_CODE (expression) == STATIC_CAST_EXPR
19198       || TREE_CODE (expression) == CONST_CAST_EXPR
19199       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19200       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19201       || TREE_CODE (expression) == CAST_EXPR)
19202     return dependent_type_p (TREE_TYPE (expression));
19203
19204   /* The types of these expressions depends only on the type created
19205      by the expression.  */
19206   if (TREE_CODE (expression) == NEW_EXPR
19207       || TREE_CODE (expression) == VEC_NEW_EXPR)
19208     {
19209       /* For NEW_EXPR tree nodes created inside a template, either
19210          the object type itself or a TREE_LIST may appear as the
19211          operand 1.  */
19212       tree type = TREE_OPERAND (expression, 1);
19213       if (TREE_CODE (type) == TREE_LIST)
19214         /* This is an array type.  We need to check array dimensions
19215            as well.  */
19216         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19217                || value_dependent_expression_p
19218                     (TREE_OPERAND (TREE_VALUE (type), 1));
19219       else
19220         return dependent_type_p (type);
19221     }
19222
19223   if (TREE_CODE (expression) == SCOPE_REF)
19224     {
19225       tree scope = TREE_OPERAND (expression, 0);
19226       tree name = TREE_OPERAND (expression, 1);
19227
19228       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19229          contains an identifier associated by name lookup with one or more
19230          declarations declared with a dependent type, or...a
19231          nested-name-specifier or qualified-id that names a member of an
19232          unknown specialization.  */
19233       return (type_dependent_expression_p (name)
19234               || dependent_scope_p (scope));
19235     }
19236
19237   if (TREE_CODE (expression) == FUNCTION_DECL
19238       && DECL_LANG_SPECIFIC (expression)
19239       && DECL_TEMPLATE_INFO (expression)
19240       && (any_dependent_template_arguments_p
19241           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19242     return true;
19243
19244   if (TREE_CODE (expression) == TEMPLATE_DECL
19245       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19246     return false;
19247
19248   if (TREE_CODE (expression) == STMT_EXPR)
19249     expression = stmt_expr_value_expr (expression);
19250
19251   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19252     {
19253       tree elt;
19254       unsigned i;
19255
19256       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19257         {
19258           if (type_dependent_expression_p (elt))
19259             return true;
19260         }
19261       return false;
19262     }
19263
19264   /* A static data member of the current instantiation with incomplete
19265      array type is type-dependent, as the definition and specializations
19266      can have different bounds.  */
19267   if (TREE_CODE (expression) == VAR_DECL
19268       && DECL_CLASS_SCOPE_P (expression)
19269       && dependent_type_p (DECL_CONTEXT (expression))
19270       && VAR_HAD_UNKNOWN_BOUND (expression))
19271     return true;
19272
19273   if (TREE_TYPE (expression) == unknown_type_node)
19274     {
19275       if (TREE_CODE (expression) == ADDR_EXPR)
19276         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19277       if (TREE_CODE (expression) == COMPONENT_REF
19278           || TREE_CODE (expression) == OFFSET_REF)
19279         {
19280           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19281             return true;
19282           expression = TREE_OPERAND (expression, 1);
19283           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19284             return false;
19285         }
19286       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19287       if (TREE_CODE (expression) == SCOPE_REF)
19288         return false;
19289
19290       if (TREE_CODE (expression) == BASELINK)
19291         expression = BASELINK_FUNCTIONS (expression);
19292
19293       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19294         {
19295           if (any_dependent_template_arguments_p
19296               (TREE_OPERAND (expression, 1)))
19297             return true;
19298           expression = TREE_OPERAND (expression, 0);
19299         }
19300       gcc_assert (TREE_CODE (expression) == OVERLOAD
19301                   || TREE_CODE (expression) == FUNCTION_DECL);
19302
19303       while (expression)
19304         {
19305           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19306             return true;
19307           expression = OVL_NEXT (expression);
19308         }
19309       return false;
19310     }
19311
19312   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19313
19314   return (dependent_type_p (TREE_TYPE (expression)));
19315 }
19316
19317 /* Like type_dependent_expression_p, but it also works while not processing
19318    a template definition, i.e. during substitution or mangling.  */
19319
19320 bool
19321 type_dependent_expression_p_push (tree expr)
19322 {
19323   bool b;
19324   ++processing_template_decl;
19325   b = type_dependent_expression_p (expr);
19326   --processing_template_decl;
19327   return b;
19328 }
19329
19330 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19331
19332 bool
19333 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19334 {
19335   unsigned int i;
19336   tree arg;
19337
19338   FOR_EACH_VEC_ELT (tree, args, i, arg)
19339     {
19340       if (type_dependent_expression_p (arg))
19341         return true;
19342     }
19343   return false;
19344 }
19345
19346 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19347    expressions) contains any type-dependent expressions.  */
19348
19349 bool
19350 any_type_dependent_elements_p (const_tree list)
19351 {
19352   for (; list; list = TREE_CHAIN (list))
19353     if (value_dependent_expression_p (TREE_VALUE (list)))
19354       return true;
19355
19356   return false;
19357 }
19358
19359 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19360    expressions) contains any value-dependent expressions.  */
19361
19362 bool
19363 any_value_dependent_elements_p (const_tree list)
19364 {
19365   for (; list; list = TREE_CHAIN (list))
19366     if (value_dependent_expression_p (TREE_VALUE (list)))
19367       return true;
19368
19369   return false;
19370 }
19371
19372 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19373
19374 bool
19375 dependent_template_arg_p (tree arg)
19376 {
19377   if (!processing_template_decl)
19378     return false;
19379
19380   /* Assume a template argument that was wrongly written by the user
19381      is dependent. This is consistent with what
19382      any_dependent_template_arguments_p [that calls this function]
19383      does.  */
19384   if (!arg || arg == error_mark_node)
19385     return true;
19386
19387   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19388     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19389
19390   if (TREE_CODE (arg) == TEMPLATE_DECL
19391       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19392     return dependent_template_p (arg);
19393   else if (ARGUMENT_PACK_P (arg))
19394     {
19395       tree args = ARGUMENT_PACK_ARGS (arg);
19396       int i, len = TREE_VEC_LENGTH (args);
19397       for (i = 0; i < len; ++i)
19398         {
19399           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19400             return true;
19401         }
19402
19403       return false;
19404     }
19405   else if (TYPE_P (arg))
19406     return dependent_type_p (arg);
19407   else
19408     return (type_dependent_expression_p (arg)
19409             || value_dependent_expression_p (arg));
19410 }
19411
19412 /* Returns true if ARGS (a collection of template arguments) contains
19413    any types that require structural equality testing.  */
19414
19415 bool
19416 any_template_arguments_need_structural_equality_p (tree args)
19417 {
19418   int i;
19419   int j;
19420
19421   if (!args)
19422     return false;
19423   if (args == error_mark_node)
19424     return true;
19425
19426   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19427     {
19428       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19429       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19430         {
19431           tree arg = TREE_VEC_ELT (level, j);
19432           tree packed_args = NULL_TREE;
19433           int k, len = 1;
19434
19435           if (ARGUMENT_PACK_P (arg))
19436             {
19437               /* Look inside the argument pack.  */
19438               packed_args = ARGUMENT_PACK_ARGS (arg);
19439               len = TREE_VEC_LENGTH (packed_args);
19440             }
19441
19442           for (k = 0; k < len; ++k)
19443             {
19444               if (packed_args)
19445                 arg = TREE_VEC_ELT (packed_args, k);
19446
19447               if (error_operand_p (arg))
19448                 return true;
19449               else if (TREE_CODE (arg) == TEMPLATE_DECL
19450                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19451                 continue;
19452               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19453                 return true;
19454               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19455                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19456                 return true;
19457             }
19458         }
19459     }
19460
19461   return false;
19462 }
19463
19464 /* Returns true if ARGS (a collection of template arguments) contains
19465    any dependent arguments.  */
19466
19467 bool
19468 any_dependent_template_arguments_p (const_tree args)
19469 {
19470   int i;
19471   int j;
19472
19473   if (!args)
19474     return false;
19475   if (args == error_mark_node)
19476     return true;
19477
19478   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19479     {
19480       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19481       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19482         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19483           return true;
19484     }
19485
19486   return false;
19487 }
19488
19489 /* Returns TRUE if the template TMPL is dependent.  */
19490
19491 bool
19492 dependent_template_p (tree tmpl)
19493 {
19494   if (TREE_CODE (tmpl) == OVERLOAD)
19495     {
19496       while (tmpl)
19497         {
19498           if (dependent_template_p (OVL_CURRENT (tmpl)))
19499             return true;
19500           tmpl = OVL_NEXT (tmpl);
19501         }
19502       return false;
19503     }
19504
19505   /* Template template parameters are dependent.  */
19506   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19507       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19508     return true;
19509   /* So are names that have not been looked up.  */
19510   if (TREE_CODE (tmpl) == SCOPE_REF
19511       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19512     return true;
19513   /* So are member templates of dependent classes.  */
19514   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19515     return dependent_type_p (DECL_CONTEXT (tmpl));
19516   return false;
19517 }
19518
19519 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19520
19521 bool
19522 dependent_template_id_p (tree tmpl, tree args)
19523 {
19524   return (dependent_template_p (tmpl)
19525           || any_dependent_template_arguments_p (args));
19526 }
19527
19528 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19529    is dependent.  */
19530
19531 bool
19532 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19533 {
19534   int i;
19535
19536   if (!processing_template_decl)
19537     return false;
19538
19539   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19540     {
19541       tree decl = TREE_VEC_ELT (declv, i);
19542       tree init = TREE_VEC_ELT (initv, i);
19543       tree cond = TREE_VEC_ELT (condv, i);
19544       tree incr = TREE_VEC_ELT (incrv, i);
19545
19546       if (type_dependent_expression_p (decl))
19547         return true;
19548
19549       if (init && type_dependent_expression_p (init))
19550         return true;
19551
19552       if (type_dependent_expression_p (cond))
19553         return true;
19554
19555       if (COMPARISON_CLASS_P (cond)
19556           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19557               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19558         return true;
19559
19560       if (TREE_CODE (incr) == MODOP_EXPR)
19561         {
19562           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19563               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19564             return true;
19565         }
19566       else if (type_dependent_expression_p (incr))
19567         return true;
19568       else if (TREE_CODE (incr) == MODIFY_EXPR)
19569         {
19570           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19571             return true;
19572           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19573             {
19574               tree t = TREE_OPERAND (incr, 1);
19575               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19576                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19577                 return true;
19578             }
19579         }
19580     }
19581
19582   return false;
19583 }
19584
19585 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19586    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19587    no such TYPE can be found.  Note that this function peers inside
19588    uninstantiated templates and therefore should be used only in
19589    extremely limited situations.  ONLY_CURRENT_P restricts this
19590    peering to the currently open classes hierarchy (which is required
19591    when comparing types).  */
19592
19593 tree
19594 resolve_typename_type (tree type, bool only_current_p)
19595 {
19596   tree scope;
19597   tree name;
19598   tree decl;
19599   int quals;
19600   tree pushed_scope;
19601   tree result;
19602
19603   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19604
19605   scope = TYPE_CONTEXT (type);
19606   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19607      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19608      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19609      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19610      identifier  of the TYPENAME_TYPE anymore.
19611      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19612      TYPENAME_TYPE instead, we avoid messing up with a possible
19613      typedef variant case.  */
19614   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19615
19616   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19617      it first before we can figure out what NAME refers to.  */
19618   if (TREE_CODE (scope) == TYPENAME_TYPE)
19619     scope = resolve_typename_type (scope, only_current_p);
19620   /* If we don't know what SCOPE refers to, then we cannot resolve the
19621      TYPENAME_TYPE.  */
19622   if (TREE_CODE (scope) == TYPENAME_TYPE)
19623     return type;
19624   /* If the SCOPE is a template type parameter, we have no way of
19625      resolving the name.  */
19626   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19627     return type;
19628   /* If the SCOPE is not the current instantiation, there's no reason
19629      to look inside it.  */
19630   if (only_current_p && !currently_open_class (scope))
19631     return type;
19632   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19633   if (typedef_variant_p (type))
19634     return type;
19635   /* If SCOPE isn't the template itself, it will not have a valid
19636      TYPE_FIELDS list.  */
19637   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19638     /* scope is either the template itself or a compatible instantiation
19639        like X<T>, so look up the name in the original template.  */
19640     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19641   else
19642     /* scope is a partial instantiation, so we can't do the lookup or we
19643        will lose the template arguments.  */
19644     return type;
19645   /* Enter the SCOPE so that name lookup will be resolved as if we
19646      were in the class definition.  In particular, SCOPE will no
19647      longer be considered a dependent type.  */
19648   pushed_scope = push_scope (scope);
19649   /* Look up the declaration.  */
19650   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19651
19652   result = NULL_TREE;
19653   
19654   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19655      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19656   if (!decl)
19657     /*nop*/;
19658   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19659            && TREE_CODE (decl) == TYPE_DECL)
19660     {
19661       result = TREE_TYPE (decl);
19662       if (result == error_mark_node)
19663         result = NULL_TREE;
19664     }
19665   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19666            && DECL_CLASS_TEMPLATE_P (decl))
19667     {
19668       tree tmpl;
19669       tree args;
19670       /* Obtain the template and the arguments.  */
19671       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19672       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19673       /* Instantiate the template.  */
19674       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19675                                       /*entering_scope=*/0,
19676                                       tf_error | tf_user);
19677       if (result == error_mark_node)
19678         result = NULL_TREE;
19679     }
19680   
19681   /* Leave the SCOPE.  */
19682   if (pushed_scope)
19683     pop_scope (pushed_scope);
19684
19685   /* If we failed to resolve it, return the original typename.  */
19686   if (!result)
19687     return type;
19688   
19689   /* If lookup found a typename type, resolve that too.  */
19690   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19691     {
19692       /* Ill-formed programs can cause infinite recursion here, so we
19693          must catch that.  */
19694       TYPENAME_IS_RESOLVING_P (type) = 1;
19695       result = resolve_typename_type (result, only_current_p);
19696       TYPENAME_IS_RESOLVING_P (type) = 0;
19697     }
19698   
19699   /* Qualify the resulting type.  */
19700   quals = cp_type_quals (type);
19701   if (quals)
19702     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19703
19704   return result;
19705 }
19706
19707 /* EXPR is an expression which is not type-dependent.  Return a proxy
19708    for EXPR that can be used to compute the types of larger
19709    expressions containing EXPR.  */
19710
19711 tree
19712 build_non_dependent_expr (tree expr)
19713 {
19714   tree inner_expr;
19715
19716 #ifdef ENABLE_CHECKING
19717   /* Try to get a constant value for all non-type-dependent expressions in
19718       order to expose bugs in *_dependent_expression_p and constexpr.  */
19719   if (cxx_dialect >= cxx0x)
19720     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19721 #endif
19722
19723   /* Preserve OVERLOADs; the functions must be available to resolve
19724      types.  */
19725   inner_expr = expr;
19726   if (TREE_CODE (inner_expr) == STMT_EXPR)
19727     inner_expr = stmt_expr_value_expr (inner_expr);
19728   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19729     inner_expr = TREE_OPERAND (inner_expr, 0);
19730   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19731     inner_expr = TREE_OPERAND (inner_expr, 1);
19732   if (is_overloaded_fn (inner_expr)
19733       || TREE_CODE (inner_expr) == OFFSET_REF)
19734     return expr;
19735   /* There is no need to return a proxy for a variable.  */
19736   if (TREE_CODE (expr) == VAR_DECL)
19737     return expr;
19738   /* Preserve string constants; conversions from string constants to
19739      "char *" are allowed, even though normally a "const char *"
19740      cannot be used to initialize a "char *".  */
19741   if (TREE_CODE (expr) == STRING_CST)
19742     return expr;
19743   /* Preserve arithmetic constants, as an optimization -- there is no
19744      reason to create a new node.  */
19745   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19746     return expr;
19747   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19748      There is at least one place where we want to know that a
19749      particular expression is a throw-expression: when checking a ?:
19750      expression, there are special rules if the second or third
19751      argument is a throw-expression.  */
19752   if (TREE_CODE (expr) == THROW_EXPR)
19753     return expr;
19754
19755   /* Don't wrap an initializer list, we need to be able to look inside.  */
19756   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19757     return expr;
19758
19759   if (TREE_CODE (expr) == COND_EXPR)
19760     return build3 (COND_EXPR,
19761                    TREE_TYPE (expr),
19762                    TREE_OPERAND (expr, 0),
19763                    (TREE_OPERAND (expr, 1)
19764                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19765                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19766                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19767   if (TREE_CODE (expr) == COMPOUND_EXPR
19768       && !COMPOUND_EXPR_OVERLOADED (expr))
19769     return build2 (COMPOUND_EXPR,
19770                    TREE_TYPE (expr),
19771                    TREE_OPERAND (expr, 0),
19772                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19773
19774   /* If the type is unknown, it can't really be non-dependent */
19775   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19776
19777   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19778   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19779 }
19780
19781 /* ARGS is a vector of expressions as arguments to a function call.
19782    Replace the arguments with equivalent non-dependent expressions.
19783    This modifies ARGS in place.  */
19784
19785 void
19786 make_args_non_dependent (VEC(tree,gc) *args)
19787 {
19788   unsigned int ix;
19789   tree arg;
19790
19791   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19792     {
19793       tree newarg = build_non_dependent_expr (arg);
19794       if (newarg != arg)
19795         VEC_replace (tree, args, ix, newarg);
19796     }
19797 }
19798
19799 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19800    with a level one deeper than the actual template parms.  */
19801
19802 tree
19803 make_auto (void)
19804 {
19805   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19806   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19807                                TYPE_DECL, get_identifier ("auto"), au);
19808   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19809   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19810     (0, processing_template_decl + 1, processing_template_decl + 1,
19811      0, TYPE_NAME (au), NULL_TREE);
19812   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19813   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19814   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19815
19816   return au;
19817 }
19818
19819 /* Given type ARG, return std::initializer_list<ARG>.  */
19820
19821 static tree
19822 listify (tree arg)
19823 {
19824   tree std_init_list = namespace_binding
19825     (get_identifier ("initializer_list"), std_node);
19826   tree argvec;
19827   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19828     {    
19829       error ("deducing from brace-enclosed initializer list requires "
19830              "#include <initializer_list>");
19831       return error_mark_node;
19832     }
19833   argvec = make_tree_vec (1);
19834   TREE_VEC_ELT (argvec, 0) = arg;
19835   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19836                                 NULL_TREE, 0, tf_warning_or_error);
19837 }
19838
19839 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19840
19841 static tree
19842 listify_autos (tree type, tree auto_node)
19843 {
19844   tree init_auto = listify (auto_node);
19845   tree argvec = make_tree_vec (1);
19846   TREE_VEC_ELT (argvec, 0) = init_auto;
19847   if (processing_template_decl)
19848     argvec = add_to_template_args (current_template_args (), argvec);
19849   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19850 }
19851
19852 /* walk_tree helper for do_auto_deduction.  */
19853
19854 static tree
19855 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19856                  void *type)
19857 {
19858   /* Is this a variable with the type we're looking for?  */
19859   if (DECL_P (*tp)
19860       && TREE_TYPE (*tp) == type)
19861     return *tp;
19862   else
19863     return NULL_TREE;
19864 }
19865
19866 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19867    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19868
19869 tree
19870 do_auto_deduction (tree type, tree init, tree auto_node)
19871 {
19872   tree parms, tparms, targs;
19873   tree args[1];
19874   tree decl;
19875   int val;
19876
19877   if (processing_template_decl
19878       && (TREE_TYPE (init) == NULL_TREE
19879           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19880     /* Not enough information to try this yet.  */
19881     return type;
19882
19883   /* The name of the object being declared shall not appear in the
19884      initializer expression.  */
19885   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19886   if (decl)
19887     {
19888       error ("variable %q#D with %<auto%> type used in its own "
19889              "initializer", decl);
19890       return error_mark_node;
19891     }
19892
19893   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19894      with either a new invented type template parameter U or, if the
19895      initializer is a braced-init-list (8.5.4), with
19896      std::initializer_list<U>.  */
19897   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19898     type = listify_autos (type, auto_node);
19899
19900   init = resolve_nondeduced_context (init);
19901
19902   parms = build_tree_list (NULL_TREE, type);
19903   args[0] = init;
19904   tparms = make_tree_vec (1);
19905   targs = make_tree_vec (1);
19906   TREE_VEC_ELT (tparms, 0)
19907     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19908   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19909                                DEDUCE_CALL, LOOKUP_NORMAL,
19910                                /*explain_p=*/false);
19911   if (val > 0)
19912     {
19913       if (processing_template_decl)
19914         /* Try again at instantiation time.  */
19915         return type;
19916       if (type && type != error_mark_node)
19917         /* If type is error_mark_node a diagnostic must have been
19918            emitted by now.  Also, having a mention to '<type error>'
19919            in the diagnostic is not really useful to the user.  */
19920         error ("unable to deduce %qT from %qE", type, init);
19921       return error_mark_node;
19922     }
19923
19924   /* If the list of declarators contains more than one declarator, the type
19925      of each declared variable is determined as described above. If the
19926      type deduced for the template parameter U is not the same in each
19927      deduction, the program is ill-formed.  */
19928   if (TREE_TYPE (auto_node)
19929       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19930     {
19931       error ("inconsistent deduction for %qT: %qT and then %qT",
19932              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19933       return error_mark_node;
19934     }
19935   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19936
19937   if (processing_template_decl)
19938     targs = add_to_template_args (current_template_args (), targs);
19939   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19940 }
19941
19942 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19943    result.  */
19944
19945 tree
19946 splice_late_return_type (tree type, tree late_return_type)
19947 {
19948   tree argvec;
19949
19950   if (late_return_type == NULL_TREE)
19951     return type;
19952   argvec = make_tree_vec (1);
19953   TREE_VEC_ELT (argvec, 0) = late_return_type;
19954   if (processing_template_parmlist)
19955     /* For a late-specified return type in a template type-parameter, we
19956        need to add a dummy argument level for its parmlist.  */
19957     argvec = add_to_template_args
19958       (make_tree_vec (processing_template_parmlist), argvec);
19959   if (current_template_parms)
19960     argvec = add_to_template_args (current_template_args (), argvec);
19961   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19962 }
19963
19964 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19965
19966 bool
19967 is_auto (const_tree type)
19968 {
19969   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19970       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19971     return true;
19972   else
19973     return false;
19974 }
19975
19976 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19977    appear as a type-specifier for the declaration in question, we don't
19978    have to look through the whole type.  */
19979
19980 tree
19981 type_uses_auto (tree type)
19982 {
19983   enum tree_code code;
19984   if (is_auto (type))
19985     return type;
19986
19987   code = TREE_CODE (type);
19988
19989   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19990       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19991       || code == METHOD_TYPE || code == ARRAY_TYPE)
19992     return type_uses_auto (TREE_TYPE (type));
19993
19994   if (TYPE_PTRMEMFUNC_P (type))
19995     return type_uses_auto (TREE_TYPE (TREE_TYPE
19996                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19997
19998   return NULL_TREE;
19999 }
20000
20001 /* For a given template T, return the vector of typedefs referenced
20002    in T for which access check is needed at T instantiation time.
20003    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20004    Those typedefs were added to T by the function
20005    append_type_to_template_for_access_check.  */
20006
20007 VEC(qualified_typedef_usage_t,gc)*
20008 get_types_needing_access_check (tree t)
20009 {
20010   tree ti;
20011   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20012
20013   if (!t || t == error_mark_node)
20014     return NULL;
20015
20016   if (!(ti = get_template_info (t)))
20017     return NULL;
20018
20019   if (CLASS_TYPE_P (t)
20020       || TREE_CODE (t) == FUNCTION_DECL)
20021     {
20022       if (!TI_TEMPLATE (ti))
20023         return NULL;
20024
20025       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20026     }
20027
20028   return result;
20029 }
20030
20031 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20032    tied to T. That list of typedefs will be access checked at
20033    T instantiation time.
20034    T is either a FUNCTION_DECL or a RECORD_TYPE.
20035    TYPE_DECL is a TYPE_DECL node representing a typedef.
20036    SCOPE is the scope through which TYPE_DECL is accessed.
20037    LOCATION is the location of the usage point of TYPE_DECL.
20038
20039    This function is a subroutine of
20040    append_type_to_template_for_access_check.  */
20041
20042 static void
20043 append_type_to_template_for_access_check_1 (tree t,
20044                                             tree type_decl,
20045                                             tree scope,
20046                                             location_t location)
20047 {
20048   qualified_typedef_usage_t typedef_usage;
20049   tree ti;
20050
20051   if (!t || t == error_mark_node)
20052     return;
20053
20054   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20055                || CLASS_TYPE_P (t))
20056               && type_decl
20057               && TREE_CODE (type_decl) == TYPE_DECL
20058               && scope);
20059
20060   if (!(ti = get_template_info (t)))
20061     return;
20062
20063   gcc_assert (TI_TEMPLATE (ti));
20064
20065   typedef_usage.typedef_decl = type_decl;
20066   typedef_usage.context = scope;
20067   typedef_usage.locus = location;
20068
20069   VEC_safe_push (qualified_typedef_usage_t, gc,
20070                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20071                  &typedef_usage);
20072 }
20073
20074 /* Append TYPE_DECL to the template TEMPL.
20075    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20076    At TEMPL instanciation time, TYPE_DECL will be checked to see
20077    if it can be accessed through SCOPE.
20078    LOCATION is the location of the usage point of TYPE_DECL.
20079
20080    e.g. consider the following code snippet:
20081
20082      class C
20083      {
20084        typedef int myint;
20085      };
20086
20087      template<class U> struct S
20088      {
20089        C::myint mi; // <-- usage point of the typedef C::myint
20090      };
20091
20092      S<char> s;
20093
20094    At S<char> instantiation time, we need to check the access of C::myint
20095    In other words, we need to check the access of the myint typedef through
20096    the C scope. For that purpose, this function will add the myint typedef
20097    and the scope C through which its being accessed to a list of typedefs
20098    tied to the template S. That list will be walked at template instantiation
20099    time and access check performed on each typedefs it contains.
20100    Note that this particular code snippet should yield an error because
20101    myint is private to C.  */
20102
20103 void
20104 append_type_to_template_for_access_check (tree templ,
20105                                           tree type_decl,
20106                                           tree scope,
20107                                           location_t location)
20108 {
20109   qualified_typedef_usage_t *iter;
20110   int i;
20111
20112   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20113
20114   /* Make sure we don't append the type to the template twice.  */
20115   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20116                     get_types_needing_access_check (templ),
20117                     i, iter)
20118     if (iter->typedef_decl == type_decl && scope == iter->context)
20119       return;
20120
20121   append_type_to_template_for_access_check_1 (templ, type_decl,
20122                                               scope, location);
20123 }
20124
20125 /* Set up the hash tables for template instantiations.  */
20126
20127 void
20128 init_template_processing (void)
20129 {
20130   decl_specializations = htab_create_ggc (37,
20131                                           hash_specialization,
20132                                           eq_specializations,
20133                                           ggc_free);
20134   type_specializations = htab_create_ggc (37,
20135                                           hash_specialization,
20136                                           eq_specializations,
20137                                           ggc_free);
20138 }
20139
20140 /* Print stats about the template hash tables for -fstats.  */
20141
20142 void
20143 print_template_statistics (void)
20144 {
20145   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20146            "%f collisions\n", (long) htab_size (decl_specializations),
20147            (long) htab_elements (decl_specializations),
20148            htab_collisions (decl_specializations));
20149   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20150            "%f collisions\n", (long) htab_size (type_specializations),
20151            (long) htab_elements (type_specializations),
20152            htab_collisions (type_specializations));
20153 }
20154
20155 #include "gt-cp-pt.h"