OSDN Git Service

* pt.c (tsubst_aggr_type): Check TYPE_P before tsubsting.
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010, 2011
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY ((chain_next ("%h.next"))) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 enum template_base_result {
113   tbr_incomplete_type,
114   tbr_ambiguous_baseclass,
115   tbr_success
116 };
117
118 static void push_access_scope (tree);
119 static void pop_access_scope (tree);
120 static void push_deduction_access_scope (tree);
121 static void pop_deduction_access_scope (tree);
122 static bool resolve_overloaded_unification (tree, tree, tree, tree,
123                                             unification_kind_t, int,
124                                             bool);
125 static int try_one_overload (tree, tree, tree, tree, tree,
126                              unification_kind_t, int, bool, bool);
127 static int unify (tree, tree, tree, tree, int, bool);
128 static void add_pending_template (tree);
129 static tree reopen_tinst_level (struct tinst_level *);
130 static tree tsubst_initializer_list (tree, tree);
131 static tree get_class_bindings (tree, tree, tree);
132 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
133                                    bool, bool);
134 static void tsubst_enum (tree, tree, tree);
135 static tree add_to_template_args (tree, tree);
136 static tree add_outermost_template_args (tree, tree);
137 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
138 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
139                                              tree);
140 static int type_unification_real (tree, tree, tree, const tree *,
141                                   unsigned int, int, unification_kind_t, int,
142                                   bool);
143 static void note_template_header (int);
144 static tree convert_nontype_argument_function (tree, tree);
145 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
146 static tree convert_template_argument (tree, tree, tree,
147                                        tsubst_flags_t, int, tree);
148 static int for_each_template_parm (tree, tree_fn_t, void*,
149                                    struct pointer_set_t*, bool);
150 static tree expand_template_argument_pack (tree);
151 static tree build_template_parm_index (int, int, int, int, tree, tree);
152 static bool inline_needs_template_parms (tree);
153 static void push_inline_template_parms_recursive (tree, int);
154 static tree retrieve_local_specialization (tree);
155 static void register_local_specialization (tree, tree);
156 static hashval_t hash_specialization (const void *p);
157 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
158 static int mark_template_parm (tree, void *);
159 static int template_parm_this_level_p (tree, void *);
160 static tree tsubst_friend_function (tree, tree);
161 static tree tsubst_friend_class (tree, tree);
162 static int can_complete_type_without_circularity (tree);
163 static tree get_bindings (tree, tree, tree, bool);
164 static int template_decl_level (tree);
165 static int check_cv_quals_for_unify (int, tree, tree);
166 static void template_parm_level_and_index (tree, int*, int*);
167 static int unify_pack_expansion (tree, tree, tree,
168                                  tree, int, bool, bool, bool);
169 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
171 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
172 static void regenerate_decl_from_template (tree, tree);
173 static tree most_specialized_class (tree, tree, tsubst_flags_t);
174 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
175 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
177 static bool check_specialization_scope (void);
178 static tree process_partial_specialization (tree);
179 static void set_current_access_from_decl (tree);
180 static enum template_base_result get_template_base (tree, tree, tree, tree,
181                                                     bool , tree *);
182 static tree try_class_unification (tree, tree, tree, tree, bool);
183 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
184                                            tree, tree);
185 static bool template_template_parm_bindings_ok_p (tree, tree);
186 static int template_args_equal (tree, tree);
187 static void tsubst_default_arguments (tree);
188 static tree for_each_template_parm_r (tree *, int *, void *);
189 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
190 static void copy_default_args_to_explicit_spec (tree);
191 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
192 static int eq_local_specializations (const void *, const void *);
193 static bool dependent_template_arg_p (tree);
194 static bool any_template_arguments_need_structural_equality_p (tree);
195 static bool dependent_type_p_r (tree);
196 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
197 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
198 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
199 static tree tsubst_decl (tree, tree, tsubst_flags_t);
200 static void perform_typedefs_access_check (tree tmpl, tree targs);
201 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
202                                                         location_t);
203 static tree listify (tree);
204 static tree listify_autos (tree, tree);
205 static tree template_parm_to_arg (tree t);
206 static tree current_template_args (void);
207 static tree fixup_template_type_parm_type (tree, int);
208 static tree fixup_template_parm_index (tree, tree, int);
209 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
210
211 /* Make the current scope suitable for access checking when we are
212    processing T.  T can be FUNCTION_DECL for instantiated function
213    template, or VAR_DECL for static member variable (need by
214    instantiate_decl).  */
215
216 static void
217 push_access_scope (tree t)
218 {
219   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
220               || TREE_CODE (t) == VAR_DECL);
221
222   if (DECL_FRIEND_CONTEXT (t))
223     push_nested_class (DECL_FRIEND_CONTEXT (t));
224   else if (DECL_CLASS_SCOPE_P (t))
225     push_nested_class (DECL_CONTEXT (t));
226   else
227     push_to_top_level ();
228
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       saved_access_scope = tree_cons
232         (NULL_TREE, current_function_decl, saved_access_scope);
233       current_function_decl = t;
234     }
235 }
236
237 /* Restore the scope set up by push_access_scope.  T is the node we
238    are processing.  */
239
240 static void
241 pop_access_scope (tree t)
242 {
243   if (TREE_CODE (t) == FUNCTION_DECL)
244     {
245       current_function_decl = TREE_VALUE (saved_access_scope);
246       saved_access_scope = TREE_CHAIN (saved_access_scope);
247     }
248
249   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
250     pop_nested_class ();
251   else
252     pop_from_top_level ();
253 }
254
255 /* Do any processing required when DECL (a member template
256    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
257    to DECL, unless it is a specialization, in which case the DECL
258    itself is returned.  */
259
260 tree
261 finish_member_template_decl (tree decl)
262 {
263   if (decl == error_mark_node)
264     return error_mark_node;
265
266   gcc_assert (DECL_P (decl));
267
268   if (TREE_CODE (decl) == TYPE_DECL)
269     {
270       tree type;
271
272       type = TREE_TYPE (decl);
273       if (type == error_mark_node)
274         return error_mark_node;
275       if (MAYBE_CLASS_TYPE_P (type)
276           && CLASSTYPE_TEMPLATE_INFO (type)
277           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
278         {
279           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
280           check_member_template (tmpl);
281           return tmpl;
282         }
283       return NULL_TREE;
284     }
285   else if (TREE_CODE (decl) == FIELD_DECL)
286     error ("data member %qD cannot be a member template", decl);
287   else if (DECL_TEMPLATE_INFO (decl))
288     {
289       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
290         {
291           check_member_template (DECL_TI_TEMPLATE (decl));
292           return DECL_TI_TEMPLATE (decl);
293         }
294       else
295         return decl;
296     }
297   else
298     error ("invalid member template declaration %qD", decl);
299
300   return error_mark_node;
301 }
302
303 /* Create a template info node.  */
304
305 tree
306 build_template_info (tree template_decl, tree template_args)
307 {
308   tree result = make_node (TEMPLATE_INFO);
309   TI_TEMPLATE (result) = template_decl;
310   TI_ARGS (result) = template_args;
311   return result;
312 }
313
314 /* Return the template info node corresponding to T, whatever T is.  */
315
316 tree
317 get_template_info (const_tree t)
318 {
319   tree tinfo = NULL_TREE;
320
321   if (!t || t == error_mark_node)
322     return NULL;
323
324   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
325     tinfo = DECL_TEMPLATE_INFO (t);
326
327   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
328     t = TREE_TYPE (t);
329
330   if (TAGGED_TYPE_P (t))
331     tinfo = TYPE_TEMPLATE_INFO (t);
332   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
333     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
334
335   return tinfo;
336 }
337
338 /* Returns the template nesting level of the indicated class TYPE.
339
340    For example, in:
341      template <class T>
342      struct A
343      {
344        template <class U>
345        struct B {};
346      };
347
348    A<T>::B<U> has depth two, while A<T> has depth one.
349    Both A<T>::B<int> and A<int>::B<U> have depth one, if
350    they are instantiations, not specializations.
351
352    This function is guaranteed to return 0 if passed NULL_TREE so
353    that, for example, `template_class_depth (current_class_type)' is
354    always safe.  */
355
356 int
357 template_class_depth (tree type)
358 {
359   int depth;
360
361   for (depth = 0;
362        type && TREE_CODE (type) != NAMESPACE_DECL;
363        type = (TREE_CODE (type) == FUNCTION_DECL)
364          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
365     {
366       tree tinfo = get_template_info (type);
367
368       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
369           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
370         ++depth;
371     }
372
373   return depth;
374 }
375
376 /* Subroutine of maybe_begin_member_template_processing.
377    Returns true if processing DECL needs us to push template parms.  */
378
379 static bool
380 inline_needs_template_parms (tree decl)
381 {
382   if (! DECL_TEMPLATE_INFO (decl))
383     return false;
384
385   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
386           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
387 }
388
389 /* Subroutine of maybe_begin_member_template_processing.
390    Push the template parms in PARMS, starting from LEVELS steps into the
391    chain, and ending at the beginning, since template parms are listed
392    innermost first.  */
393
394 static void
395 push_inline_template_parms_recursive (tree parmlist, int levels)
396 {
397   tree parms = TREE_VALUE (parmlist);
398   int i;
399
400   if (levels > 1)
401     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
402
403   ++processing_template_decl;
404   current_template_parms
405     = tree_cons (size_int (processing_template_decl),
406                  parms, current_template_parms);
407   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
408
409   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
410                NULL);
411   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
412     {
413       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
414
415       if (parm == error_mark_node)
416         continue;
417
418       gcc_assert (DECL_P (parm));
419
420       switch (TREE_CODE (parm))
421         {
422         case TYPE_DECL:
423         case TEMPLATE_DECL:
424           pushdecl (parm);
425           break;
426
427         case PARM_DECL:
428           {
429             /* Make a CONST_DECL as is done in process_template_parm.
430                It is ugly that we recreate this here; the original
431                version built in process_template_parm is no longer
432                available.  */
433             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
434                                     CONST_DECL, DECL_NAME (parm),
435                                     TREE_TYPE (parm));
436             DECL_ARTIFICIAL (decl) = 1;
437             TREE_CONSTANT (decl) = 1;
438             TREE_READONLY (decl) = 1;
439             DECL_INITIAL (decl) = DECL_INITIAL (parm);
440             SET_DECL_TEMPLATE_PARM_P (decl);
441             pushdecl (decl);
442           }
443           break;
444
445         default:
446           gcc_unreachable ();
447         }
448     }
449 }
450
451 /* Restore the template parameter context for a member template or
452    a friend template defined in a class definition.  */
453
454 void
455 maybe_begin_member_template_processing (tree decl)
456 {
457   tree parms;
458   int levels = 0;
459
460   if (inline_needs_template_parms (decl))
461     {
462       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
463       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
464
465       if (DECL_TEMPLATE_SPECIALIZATION (decl))
466         {
467           --levels;
468           parms = TREE_CHAIN (parms);
469         }
470
471       push_inline_template_parms_recursive (parms, levels);
472     }
473
474   /* Remember how many levels of template parameters we pushed so that
475      we can pop them later.  */
476   VEC_safe_push (int, heap, inline_parm_levels, levels);
477 }
478
479 /* Undo the effects of maybe_begin_member_template_processing.  */
480
481 void
482 maybe_end_member_template_processing (void)
483 {
484   int i;
485   int last;
486
487   if (VEC_length (int, inline_parm_levels) == 0)
488     return;
489
490   last = VEC_pop (int, inline_parm_levels);
491   for (i = 0; i < last; ++i)
492     {
493       --processing_template_decl;
494       current_template_parms = TREE_CHAIN (current_template_parms);
495       poplevel (0, 0, 0);
496     }
497 }
498
499 /* Return a new template argument vector which contains all of ARGS,
500    but has as its innermost set of arguments the EXTRA_ARGS.  */
501
502 static tree
503 add_to_template_args (tree args, tree extra_args)
504 {
505   tree new_args;
506   int extra_depth;
507   int i;
508   int j;
509
510   if (args == NULL_TREE || extra_args == error_mark_node)
511     return extra_args;
512
513   extra_depth = TMPL_ARGS_DEPTH (extra_args);
514   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
515
516   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
517     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
518
519   for (j = 1; j <= extra_depth; ++j, ++i)
520     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
521
522   return new_args;
523 }
524
525 /* Like add_to_template_args, but only the outermost ARGS are added to
526    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
527    (EXTRA_ARGS) levels are added.  This function is used to combine
528    the template arguments from a partial instantiation with the
529    template arguments used to attain the full instantiation from the
530    partial instantiation.  */
531
532 static tree
533 add_outermost_template_args (tree args, tree extra_args)
534 {
535   tree new_args;
536
537   /* If there are more levels of EXTRA_ARGS than there are ARGS,
538      something very fishy is going on.  */
539   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
540
541   /* If *all* the new arguments will be the EXTRA_ARGS, just return
542      them.  */
543   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
544     return extra_args;
545
546   /* For the moment, we make ARGS look like it contains fewer levels.  */
547   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
548
549   new_args = add_to_template_args (args, extra_args);
550
551   /* Now, we restore ARGS to its full dimensions.  */
552   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
553
554   return new_args;
555 }
556
557 /* Return the N levels of innermost template arguments from the ARGS.  */
558
559 tree
560 get_innermost_template_args (tree args, int n)
561 {
562   tree new_args;
563   int extra_levels;
564   int i;
565
566   gcc_assert (n >= 0);
567
568   /* If N is 1, just return the innermost set of template arguments.  */
569   if (n == 1)
570     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
571
572   /* If we're not removing anything, just return the arguments we were
573      given.  */
574   extra_levels = TMPL_ARGS_DEPTH (args) - n;
575   gcc_assert (extra_levels >= 0);
576   if (extra_levels == 0)
577     return args;
578
579   /* Make a new set of arguments, not containing the outer arguments.  */
580   new_args = make_tree_vec (n);
581   for (i = 1; i <= n; ++i)
582     SET_TMPL_ARGS_LEVEL (new_args, i,
583                          TMPL_ARGS_LEVEL (args, i + extra_levels));
584
585   return new_args;
586 }
587
588 /* The inverse of get_innermost_template_args: Return all but the innermost
589    EXTRA_LEVELS levels of template arguments from the ARGS.  */
590
591 static tree
592 strip_innermost_template_args (tree args, int extra_levels)
593 {
594   tree new_args;
595   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
596   int i;
597
598   gcc_assert (n >= 0);
599
600   /* If N is 1, just return the outermost set of template arguments.  */
601   if (n == 1)
602     return TMPL_ARGS_LEVEL (args, 1);
603
604   /* If we're not removing anything, just return the arguments we were
605      given.  */
606   gcc_assert (extra_levels >= 0);
607   if (extra_levels == 0)
608     return args;
609
610   /* Make a new set of arguments, not containing the inner arguments.  */
611   new_args = make_tree_vec (n);
612   for (i = 1; i <= n; ++i)
613     SET_TMPL_ARGS_LEVEL (new_args, i,
614                          TMPL_ARGS_LEVEL (args, i));
615
616   return new_args;
617 }
618
619 /* We've got a template header coming up; push to a new level for storing
620    the parms.  */
621
622 void
623 begin_template_parm_list (void)
624 {
625   /* We use a non-tag-transparent scope here, which causes pushtag to
626      put tags in this scope, rather than in the enclosing class or
627      namespace scope.  This is the right thing, since we want
628      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
629      global template class, push_template_decl handles putting the
630      TEMPLATE_DECL into top-level scope.  For a nested template class,
631      e.g.:
632
633        template <class T> struct S1 {
634          template <class T> struct S2 {};
635        };
636
637      pushtag contains special code to call pushdecl_with_scope on the
638      TEMPLATE_DECL for S2.  */
639   begin_scope (sk_template_parms, NULL);
640   ++processing_template_decl;
641   ++processing_template_parmlist;
642   note_template_header (0);
643 }
644
645 /* This routine is called when a specialization is declared.  If it is
646    invalid to declare a specialization here, an error is reported and
647    false is returned, otherwise this routine will return true.  */
648
649 static bool
650 check_specialization_scope (void)
651 {
652   tree scope = current_scope ();
653
654   /* [temp.expl.spec]
655
656      An explicit specialization shall be declared in the namespace of
657      which the template is a member, or, for member templates, in the
658      namespace of which the enclosing class or enclosing class
659      template is a member.  An explicit specialization of a member
660      function, member class or static data member of a class template
661      shall be declared in the namespace of which the class template
662      is a member.  */
663   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
664     {
665       error ("explicit specialization in non-namespace scope %qD", scope);
666       return false;
667     }
668
669   /* [temp.expl.spec]
670
671      In an explicit specialization declaration for a member of a class
672      template or a member template that appears in namespace scope,
673      the member template and some of its enclosing class templates may
674      remain unspecialized, except that the declaration shall not
675      explicitly specialize a class member template if its enclosing
676      class templates are not explicitly specialized as well.  */
677   if (current_template_parms)
678     {
679       error ("enclosing class templates are not explicitly specialized");
680       return false;
681     }
682
683   return true;
684 }
685
686 /* We've just seen template <>.  */
687
688 bool
689 begin_specialization (void)
690 {
691   begin_scope (sk_template_spec, NULL);
692   note_template_header (1);
693   return check_specialization_scope ();
694 }
695
696 /* Called at then end of processing a declaration preceded by
697    template<>.  */
698
699 void
700 end_specialization (void)
701 {
702   finish_scope ();
703   reset_specialization ();
704 }
705
706 /* Any template <>'s that we have seen thus far are not referring to a
707    function specialization.  */
708
709 void
710 reset_specialization (void)
711 {
712   processing_specialization = 0;
713   template_header_count = 0;
714 }
715
716 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
717    it was of the form template <>.  */
718
719 static void
720 note_template_header (int specialization)
721 {
722   processing_specialization = specialization;
723   template_header_count++;
724 }
725
726 /* We're beginning an explicit instantiation.  */
727
728 void
729 begin_explicit_instantiation (void)
730 {
731   gcc_assert (!processing_explicit_instantiation);
732   processing_explicit_instantiation = true;
733 }
734
735
736 void
737 end_explicit_instantiation (void)
738 {
739   gcc_assert (processing_explicit_instantiation);
740   processing_explicit_instantiation = false;
741 }
742
743 /* An explicit specialization or partial specialization TMPL is being
744    declared.  Check that the namespace in which the specialization is
745    occurring is permissible.  Returns false iff it is invalid to
746    specialize TMPL in the current namespace.  */
747
748 static bool
749 check_specialization_namespace (tree tmpl)
750 {
751   tree tpl_ns = decl_namespace_context (tmpl);
752
753   /* [tmpl.expl.spec]
754
755      An explicit specialization shall be declared in the namespace of
756      which the template is a member, or, for member templates, in the
757      namespace of which the enclosing class or enclosing class
758      template is a member.  An explicit specialization of a member
759      function, member class or static data member of a class template
760      shall be declared in the namespace of which the class template is
761      a member.  */
762   if (current_scope() != DECL_CONTEXT (tmpl)
763       && !at_namespace_scope_p ())
764     {
765       error ("specialization of %qD must appear at namespace scope", tmpl);
766       return false;
767     }
768   if (is_associated_namespace (current_namespace, tpl_ns))
769     /* Same or super-using namespace.  */
770     return true;
771   else
772     {
773       permerror (input_location, "specialization of %qD in different namespace", tmpl);
774       permerror (input_location, "  from definition of %q+#D", tmpl);
775       return false;
776     }
777 }
778
779 /* SPEC is an explicit instantiation.  Check that it is valid to
780    perform this explicit instantiation in the current namespace.  */
781
782 static void
783 check_explicit_instantiation_namespace (tree spec)
784 {
785   tree ns;
786
787   /* DR 275: An explicit instantiation shall appear in an enclosing
788      namespace of its template.  */
789   ns = decl_namespace_context (spec);
790   if (!is_ancestor (current_namespace, ns))
791     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
792                "(which does not enclose namespace %qD)",
793                spec, current_namespace, ns);
794 }
795
796 /* The TYPE is being declared.  If it is a template type, that means it
797    is a partial specialization.  Do appropriate error-checking.  */
798
799 tree
800 maybe_process_partial_specialization (tree type)
801 {
802   tree context;
803
804   if (type == error_mark_node)
805     return error_mark_node;
806
807   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
808     {
809       error ("name of class shadows template template parameter %qD",
810              TYPE_NAME (type));
811       return error_mark_node;
812     }
813
814   context = TYPE_CONTEXT (type);
815
816   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
817     {
818       /* This is for ordinary explicit specialization and partial
819          specialization of a template class such as:
820
821            template <> class C<int>;
822
823          or:
824
825            template <class T> class C<T*>;
826
827          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
828
829       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
830           && !COMPLETE_TYPE_P (type))
831         {
832           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
833           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
834           if (processing_template_decl)
835             {
836               if (push_template_decl (TYPE_MAIN_DECL (type))
837                   == error_mark_node)
838                 return error_mark_node;
839             }
840         }
841       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
842         error ("specialization of %qT after instantiation", type);
843     }
844   else if (CLASS_TYPE_P (type)
845            && !CLASSTYPE_USE_TEMPLATE (type)
846            && CLASSTYPE_TEMPLATE_INFO (type)
847            && context && CLASS_TYPE_P (context)
848            && CLASSTYPE_TEMPLATE_INFO (context))
849     {
850       /* This is for an explicit specialization of member class
851          template according to [temp.expl.spec/18]:
852
853            template <> template <class U> class C<int>::D;
854
855          The context `C<int>' must be an implicit instantiation.
856          Otherwise this is just a member class template declared
857          earlier like:
858
859            template <> class C<int> { template <class U> class D; };
860            template <> template <class U> class C<int>::D;
861
862          In the first case, `C<int>::D' is a specialization of `C<T>::D'
863          while in the second case, `C<int>::D' is a primary template
864          and `C<T>::D' may not exist.  */
865
866       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
867           && !COMPLETE_TYPE_P (type))
868         {
869           tree t;
870           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
871
872           if (current_namespace
873               != decl_namespace_context (tmpl))
874             {
875               permerror (input_location, "specializing %q#T in different namespace", type);
876               permerror (input_location, "  from definition of %q+#D", tmpl);
877             }
878
879           /* Check for invalid specialization after instantiation:
880
881                template <> template <> class C<int>::D<int>;
882                template <> template <class U> class C<int>::D;  */
883
884           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
885                t; t = TREE_CHAIN (t))
886             {
887               tree inst = TREE_VALUE (t);
888               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
889                 {
890                   /* We already have a full specialization of this partial
891                      instantiation.  Reassign it to the new member
892                      specialization template.  */
893                   spec_entry elt;
894                   spec_entry **slot;
895
896                   elt.tmpl = most_general_template (tmpl);
897                   elt.args = CLASSTYPE_TI_ARGS (inst);
898                   elt.spec = inst;
899
900                   htab_remove_elt (type_specializations, &elt);
901
902                   elt.tmpl = tmpl;
903                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
904
905                   slot = (spec_entry **)
906                     htab_find_slot (type_specializations, &elt, INSERT);
907                   *slot = ggc_alloc_spec_entry ();
908                   **slot = elt;
909                 }
910               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
911                 /* But if we've had an implicit instantiation, that's a
912                    problem ([temp.expl.spec]/6).  */
913                 error ("specialization %qT after instantiation %qT",
914                        type, inst);
915             }
916
917           /* Mark TYPE as a specialization.  And as a result, we only
918              have one level of template argument for the innermost
919              class template.  */
920           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
921           CLASSTYPE_TI_ARGS (type)
922             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
923         }
924     }
925   else if (processing_specialization)
926     {
927        /* Someday C++0x may allow for enum template specialization.  */
928       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
929           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
930         pedwarn (input_location, OPT_pedantic, "template specialization "
931                  "of %qD not allowed by ISO C++", type);
932       else
933         {
934           error ("explicit specialization of non-template %qT", type);
935           return error_mark_node;
936         }
937     }
938
939   return type;
940 }
941
942 /* Returns nonzero if we can optimize the retrieval of specializations
943    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
944    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
945
946 static inline bool
947 optimize_specialization_lookup_p (tree tmpl)
948 {
949   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
950           && DECL_CLASS_SCOPE_P (tmpl)
951           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
952              parameter.  */
953           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
954           /* The optimized lookup depends on the fact that the
955              template arguments for the member function template apply
956              purely to the containing class, which is not true if the
957              containing class is an explicit or partial
958              specialization.  */
959           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
960           && !DECL_MEMBER_TEMPLATE_P (tmpl)
961           && !DECL_CONV_FN_P (tmpl)
962           /* It is possible to have a template that is not a member
963              template and is not a member of a template class:
964
965              template <typename T>
966              struct S { friend A::f(); };
967
968              Here, the friend function is a template, but the context does
969              not have template information.  The optimized lookup relies
970              on having ARGS be the template arguments for both the class
971              and the function template.  */
972           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
973 }
974
975 /* Retrieve the specialization (in the sense of [temp.spec] - a
976    specialization is either an instantiation or an explicit
977    specialization) of TMPL for the given template ARGS.  If there is
978    no such specialization, return NULL_TREE.  The ARGS are a vector of
979    arguments, or a vector of vectors of arguments, in the case of
980    templates with more than one level of parameters.
981
982    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
983    then we search for a partial specialization matching ARGS.  This
984    parameter is ignored if TMPL is not a class template.  */
985
986 static tree
987 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
988 {
989   if (args == error_mark_node)
990     return NULL_TREE;
991
992   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
993
994   /* There should be as many levels of arguments as there are
995      levels of parameters.  */
996   gcc_assert (TMPL_ARGS_DEPTH (args)
997               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
998
999   if (optimize_specialization_lookup_p (tmpl))
1000     {
1001       tree class_template;
1002       tree class_specialization;
1003       VEC(tree,gc) *methods;
1004       tree fns;
1005       int idx;
1006
1007       /* The template arguments actually apply to the containing
1008          class.  Find the class specialization with those
1009          arguments.  */
1010       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1011       class_specialization
1012         = retrieve_specialization (class_template, args, 0);
1013       if (!class_specialization)
1014         return NULL_TREE;
1015       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1016          for the specialization.  */
1017       idx = class_method_index_for_fn (class_specialization, tmpl);
1018       if (idx == -1)
1019         return NULL_TREE;
1020       /* Iterate through the methods with the indicated name, looking
1021          for the one that has an instance of TMPL.  */
1022       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1023       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1024         {
1025           tree fn = OVL_CURRENT (fns);
1026           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1027               /* using-declarations can add base methods to the method vec,
1028                  and we don't want those here.  */
1029               && DECL_CONTEXT (fn) == class_specialization)
1030             return fn;
1031         }
1032       return NULL_TREE;
1033     }
1034   else
1035     {
1036       spec_entry *found;
1037       spec_entry elt;
1038       htab_t specializations;
1039
1040       elt.tmpl = tmpl;
1041       elt.args = args;
1042       elt.spec = NULL_TREE;
1043
1044       if (DECL_CLASS_TEMPLATE_P (tmpl))
1045         specializations = type_specializations;
1046       else
1047         specializations = decl_specializations;
1048
1049       if (hash == 0)
1050         hash = hash_specialization (&elt);
1051       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1052       if (found)
1053         return found->spec;
1054     }
1055
1056   return NULL_TREE;
1057 }
1058
1059 /* Like retrieve_specialization, but for local declarations.  */
1060
1061 static tree
1062 retrieve_local_specialization (tree tmpl)
1063 {
1064   tree spec;
1065
1066   if (local_specializations == NULL)
1067     return NULL_TREE;
1068
1069   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1070                                      htab_hash_pointer (tmpl));
1071   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1072 }
1073
1074 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1075
1076 int
1077 is_specialization_of (tree decl, tree tmpl)
1078 {
1079   tree t;
1080
1081   if (TREE_CODE (decl) == FUNCTION_DECL)
1082     {
1083       for (t = decl;
1084            t != NULL_TREE;
1085            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1086         if (t == tmpl)
1087           return 1;
1088     }
1089   else
1090     {
1091       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1092
1093       for (t = TREE_TYPE (decl);
1094            t != NULL_TREE;
1095            t = CLASSTYPE_USE_TEMPLATE (t)
1096              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1097         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1098           return 1;
1099     }
1100
1101   return 0;
1102 }
1103
1104 /* Returns nonzero iff DECL is a specialization of friend declaration
1105    FRIEND_DECL according to [temp.friend].  */
1106
1107 bool
1108 is_specialization_of_friend (tree decl, tree friend_decl)
1109 {
1110   bool need_template = true;
1111   int template_depth;
1112
1113   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1114               || TREE_CODE (decl) == TYPE_DECL);
1115
1116   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1117      of a template class, we want to check if DECL is a specialization
1118      if this.  */
1119   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1120       && DECL_TEMPLATE_INFO (friend_decl)
1121       && !DECL_USE_TEMPLATE (friend_decl))
1122     {
1123       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1124       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1125       need_template = false;
1126     }
1127   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1128            && !PRIMARY_TEMPLATE_P (friend_decl))
1129     need_template = false;
1130
1131   /* There is nothing to do if this is not a template friend.  */
1132   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1133     return false;
1134
1135   if (is_specialization_of (decl, friend_decl))
1136     return true;
1137
1138   /* [temp.friend/6]
1139      A member of a class template may be declared to be a friend of a
1140      non-template class.  In this case, the corresponding member of
1141      every specialization of the class template is a friend of the
1142      class granting friendship.
1143
1144      For example, given a template friend declaration
1145
1146        template <class T> friend void A<T>::f();
1147
1148      the member function below is considered a friend
1149
1150        template <> struct A<int> {
1151          void f();
1152        };
1153
1154      For this type of template friend, TEMPLATE_DEPTH below will be
1155      nonzero.  To determine if DECL is a friend of FRIEND, we first
1156      check if the enclosing class is a specialization of another.  */
1157
1158   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1159   if (template_depth
1160       && DECL_CLASS_SCOPE_P (decl)
1161       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1162                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1163     {
1164       /* Next, we check the members themselves.  In order to handle
1165          a few tricky cases, such as when FRIEND_DECL's are
1166
1167            template <class T> friend void A<T>::g(T t);
1168            template <class T> template <T t> friend void A<T>::h();
1169
1170          and DECL's are
1171
1172            void A<int>::g(int);
1173            template <int> void A<int>::h();
1174
1175          we need to figure out ARGS, the template arguments from
1176          the context of DECL.  This is required for template substitution
1177          of `T' in the function parameter of `g' and template parameter
1178          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1179
1180       tree context = DECL_CONTEXT (decl);
1181       tree args = NULL_TREE;
1182       int current_depth = 0;
1183
1184       while (current_depth < template_depth)
1185         {
1186           if (CLASSTYPE_TEMPLATE_INFO (context))
1187             {
1188               if (current_depth == 0)
1189                 args = TYPE_TI_ARGS (context);
1190               else
1191                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1192               current_depth++;
1193             }
1194           context = TYPE_CONTEXT (context);
1195         }
1196
1197       if (TREE_CODE (decl) == FUNCTION_DECL)
1198         {
1199           bool is_template;
1200           tree friend_type;
1201           tree decl_type;
1202           tree friend_args_type;
1203           tree decl_args_type;
1204
1205           /* Make sure that both DECL and FRIEND_DECL are templates or
1206              non-templates.  */
1207           is_template = DECL_TEMPLATE_INFO (decl)
1208                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1209           if (need_template ^ is_template)
1210             return false;
1211           else if (is_template)
1212             {
1213               /* If both are templates, check template parameter list.  */
1214               tree friend_parms
1215                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1216                                          args, tf_none);
1217               if (!comp_template_parms
1218                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1219                       friend_parms))
1220                 return false;
1221
1222               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1223             }
1224           else
1225             decl_type = TREE_TYPE (decl);
1226
1227           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1228                                               tf_none, NULL_TREE);
1229           if (friend_type == error_mark_node)
1230             return false;
1231
1232           /* Check if return types match.  */
1233           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1234             return false;
1235
1236           /* Check if function parameter types match, ignoring the
1237              `this' parameter.  */
1238           friend_args_type = TYPE_ARG_TYPES (friend_type);
1239           decl_args_type = TYPE_ARG_TYPES (decl_type);
1240           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1241             friend_args_type = TREE_CHAIN (friend_args_type);
1242           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1243             decl_args_type = TREE_CHAIN (decl_args_type);
1244
1245           return compparms (decl_args_type, friend_args_type);
1246         }
1247       else
1248         {
1249           /* DECL is a TYPE_DECL */
1250           bool is_template;
1251           tree decl_type = TREE_TYPE (decl);
1252
1253           /* Make sure that both DECL and FRIEND_DECL are templates or
1254              non-templates.  */
1255           is_template
1256             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1257               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1258
1259           if (need_template ^ is_template)
1260             return false;
1261           else if (is_template)
1262             {
1263               tree friend_parms;
1264               /* If both are templates, check the name of the two
1265                  TEMPLATE_DECL's first because is_friend didn't.  */
1266               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1267                   != DECL_NAME (friend_decl))
1268                 return false;
1269
1270               /* Now check template parameter list.  */
1271               friend_parms
1272                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1273                                          args, tf_none);
1274               return comp_template_parms
1275                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1276                  friend_parms);
1277             }
1278           else
1279             return (DECL_NAME (decl)
1280                     == DECL_NAME (friend_decl));
1281         }
1282     }
1283   return false;
1284 }
1285
1286 /* Register the specialization SPEC as a specialization of TMPL with
1287    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1288    is actually just a friend declaration.  Returns SPEC, or an
1289    equivalent prior declaration, if available.  */
1290
1291 static tree
1292 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1293                          hashval_t hash)
1294 {
1295   tree fn;
1296   spec_entry **slot = NULL;
1297   spec_entry elt;
1298
1299   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1300
1301   if (TREE_CODE (spec) == FUNCTION_DECL
1302       && uses_template_parms (DECL_TI_ARGS (spec)))
1303     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1304        register it; we want the corresponding TEMPLATE_DECL instead.
1305        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1306        the more obvious `uses_template_parms (spec)' to avoid problems
1307        with default function arguments.  In particular, given
1308        something like this:
1309
1310           template <class T> void f(T t1, T t = T())
1311
1312        the default argument expression is not substituted for in an
1313        instantiation unless and until it is actually needed.  */
1314     return spec;
1315
1316   if (optimize_specialization_lookup_p (tmpl))
1317     /* We don't put these specializations in the hash table, but we might
1318        want to give an error about a mismatch.  */
1319     fn = retrieve_specialization (tmpl, args, 0);
1320   else
1321     {
1322       elt.tmpl = tmpl;
1323       elt.args = args;
1324       elt.spec = spec;
1325
1326       if (hash == 0)
1327         hash = hash_specialization (&elt);
1328
1329       slot = (spec_entry **)
1330         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1331       if (*slot)
1332         fn = (*slot)->spec;
1333       else
1334         fn = NULL_TREE;
1335     }
1336
1337   /* We can sometimes try to re-register a specialization that we've
1338      already got.  In particular, regenerate_decl_from_template calls
1339      duplicate_decls which will update the specialization list.  But,
1340      we'll still get called again here anyhow.  It's more convenient
1341      to simply allow this than to try to prevent it.  */
1342   if (fn == spec)
1343     return spec;
1344   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1345     {
1346       if (DECL_TEMPLATE_INSTANTIATION (fn))
1347         {
1348           if (DECL_ODR_USED (fn)
1349               || DECL_EXPLICIT_INSTANTIATION (fn))
1350             {
1351               error ("specialization of %qD after instantiation",
1352                      fn);
1353               return error_mark_node;
1354             }
1355           else
1356             {
1357               tree clone;
1358               /* This situation should occur only if the first
1359                  specialization is an implicit instantiation, the
1360                  second is an explicit specialization, and the
1361                  implicit instantiation has not yet been used.  That
1362                  situation can occur if we have implicitly
1363                  instantiated a member function and then specialized
1364                  it later.
1365
1366                  We can also wind up here if a friend declaration that
1367                  looked like an instantiation turns out to be a
1368                  specialization:
1369
1370                    template <class T> void foo(T);
1371                    class S { friend void foo<>(int) };
1372                    template <> void foo(int);
1373
1374                  We transform the existing DECL in place so that any
1375                  pointers to it become pointers to the updated
1376                  declaration.
1377
1378                  If there was a definition for the template, but not
1379                  for the specialization, we want this to look as if
1380                  there were no definition, and vice versa.  */
1381               DECL_INITIAL (fn) = NULL_TREE;
1382               duplicate_decls (spec, fn, is_friend);
1383               /* The call to duplicate_decls will have applied
1384                  [temp.expl.spec]:
1385
1386                    An explicit specialization of a function template
1387                    is inline only if it is explicitly declared to be,
1388                    and independently of whether its function template
1389                    is.
1390
1391                 to the primary function; now copy the inline bits to
1392                 the various clones.  */
1393               FOR_EACH_CLONE (clone, fn)
1394                 {
1395                   DECL_DECLARED_INLINE_P (clone)
1396                     = DECL_DECLARED_INLINE_P (fn);
1397                   DECL_SOURCE_LOCATION (clone)
1398                     = DECL_SOURCE_LOCATION (fn);
1399                 }
1400               check_specialization_namespace (fn);
1401
1402               return fn;
1403             }
1404         }
1405       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1406         {
1407           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1408             /* Dup decl failed, but this is a new definition. Set the
1409                line number so any errors match this new
1410                definition.  */
1411             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1412
1413           return fn;
1414         }
1415     }
1416   else if (fn)
1417     return duplicate_decls (spec, fn, is_friend);
1418
1419   /* A specialization must be declared in the same namespace as the
1420      template it is specializing.  */
1421   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1422       && !check_specialization_namespace (tmpl))
1423     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1424
1425   if (!optimize_specialization_lookup_p (tmpl))
1426     {
1427       gcc_assert (tmpl && args && spec);
1428       *slot = ggc_alloc_spec_entry ();
1429       **slot = elt;
1430       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1431           && PRIMARY_TEMPLATE_P (tmpl)
1432           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1433         /* TMPL is a forward declaration of a template function; keep a list
1434            of all specializations in case we need to reassign them to a friend
1435            template later in tsubst_friend_function.  */
1436         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1437           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1438     }
1439
1440   return spec;
1441 }
1442
1443 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1444    TMPL and ARGS members, ignores SPEC.  */
1445
1446 static int
1447 eq_specializations (const void *p1, const void *p2)
1448 {
1449   const spec_entry *e1 = (const spec_entry *)p1;
1450   const spec_entry *e2 = (const spec_entry *)p2;
1451
1452   return (e1->tmpl == e2->tmpl
1453           && comp_template_args (e1->args, e2->args));
1454 }
1455
1456 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1457
1458 static hashval_t
1459 hash_tmpl_and_args (tree tmpl, tree args)
1460 {
1461   hashval_t val = DECL_UID (tmpl);
1462   return iterative_hash_template_arg (args, val);
1463 }
1464
1465 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1466    ignoring SPEC.  */
1467
1468 static hashval_t
1469 hash_specialization (const void *p)
1470 {
1471   const spec_entry *e = (const spec_entry *)p;
1472   return hash_tmpl_and_args (e->tmpl, e->args);
1473 }
1474
1475 /* Recursively calculate a hash value for a template argument ARG, for use
1476    in the hash tables of template specializations.  */
1477
1478 hashval_t
1479 iterative_hash_template_arg (tree arg, hashval_t val)
1480 {
1481   unsigned HOST_WIDE_INT i;
1482   enum tree_code code;
1483   char tclass;
1484
1485   if (arg == NULL_TREE)
1486     return iterative_hash_object (arg, val);
1487
1488   if (!TYPE_P (arg))
1489     STRIP_NOPS (arg);
1490
1491   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1492     /* We can get one of these when re-hashing a previous entry in the middle
1493        of substituting into a pack expansion.  Just look through it.  */
1494     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1495
1496   code = TREE_CODE (arg);
1497   tclass = TREE_CODE_CLASS (code);
1498
1499   val = iterative_hash_object (code, val);
1500
1501   switch (code)
1502     {
1503     case ERROR_MARK:
1504       return val;
1505
1506     case IDENTIFIER_NODE:
1507       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1508
1509     case TREE_VEC:
1510       {
1511         int i, len = TREE_VEC_LENGTH (arg);
1512         for (i = 0; i < len; ++i)
1513           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1514         return val;
1515       }
1516
1517     case TYPE_PACK_EXPANSION:
1518     case EXPR_PACK_EXPANSION:
1519       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1520
1521     case TYPE_ARGUMENT_PACK:
1522     case NONTYPE_ARGUMENT_PACK:
1523       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1524
1525     case TREE_LIST:
1526       for (; arg; arg = TREE_CHAIN (arg))
1527         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1528       return val;
1529
1530     case OVERLOAD:
1531       for (; arg; arg = OVL_NEXT (arg))
1532         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1533       return val;
1534
1535     case CONSTRUCTOR:
1536       {
1537         tree field, value;
1538         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1539           {
1540             val = iterative_hash_template_arg (field, val);
1541             val = iterative_hash_template_arg (value, val);
1542           }
1543         return val;
1544       }
1545
1546     case PARM_DECL:
1547       if (!DECL_ARTIFICIAL (arg))
1548         {
1549           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1550           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1551         }
1552       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1553
1554     case TARGET_EXPR:
1555       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1556
1557     case PTRMEM_CST:
1558       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1559       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1560
1561     case TEMPLATE_PARM_INDEX:
1562       val = iterative_hash_template_arg
1563         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1564       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1565       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1566
1567     case TRAIT_EXPR:
1568       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1569       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1570       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1571
1572     case BASELINK:
1573       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1574                                          val);
1575       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1576                                           val);
1577
1578     case MODOP_EXPR:
1579       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1580       code = TREE_CODE (TREE_OPERAND (arg, 1));
1581       val = iterative_hash_object (code, val);
1582       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1583
1584     case LAMBDA_EXPR:
1585       /* A lambda can't appear in a template arg, but don't crash on
1586          erroneous input.  */
1587       gcc_assert (seen_error ());
1588       return val;
1589
1590     case CAST_EXPR:
1591     case STATIC_CAST_EXPR:
1592     case REINTERPRET_CAST_EXPR:
1593     case CONST_CAST_EXPR:
1594     case DYNAMIC_CAST_EXPR:
1595     case NEW_EXPR:
1596       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1597       /* Now hash operands as usual.  */
1598       break;
1599
1600     default:
1601       break;
1602     }
1603
1604   switch (tclass)
1605     {
1606     case tcc_type:
1607       if (TYPE_CANONICAL (arg))
1608         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1609                                       val);
1610       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1611         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1612       /* Otherwise just compare the types during lookup.  */
1613       return val;
1614
1615     case tcc_declaration:
1616     case tcc_constant:
1617       return iterative_hash_expr (arg, val);
1618
1619     default:
1620       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1621       {
1622         unsigned n = cp_tree_operand_length (arg);
1623         for (i = 0; i < n; ++i)
1624           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1625         return val;
1626       }
1627     }
1628   gcc_unreachable ();
1629   return 0;
1630 }
1631
1632 /* Unregister the specialization SPEC as a specialization of TMPL.
1633    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1634    if the SPEC was listed as a specialization of TMPL.
1635
1636    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1637
1638 bool
1639 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1640 {
1641   spec_entry **slot;
1642   spec_entry elt;
1643
1644   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1645   elt.args = TI_ARGS (tinfo);
1646   elt.spec = NULL_TREE;
1647
1648   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1649   if (*slot)
1650     {
1651       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1652       gcc_assert (new_spec != NULL_TREE);
1653       (*slot)->spec = new_spec;
1654       return 1;
1655     }
1656
1657   return 0;
1658 }
1659
1660 /* Compare an entry in the local specializations hash table P1 (which
1661    is really a pointer to a TREE_LIST) with P2 (which is really a
1662    DECL).  */
1663
1664 static int
1665 eq_local_specializations (const void *p1, const void *p2)
1666 {
1667   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1668 }
1669
1670 /* Hash P1, an entry in the local specializations table.  */
1671
1672 static hashval_t
1673 hash_local_specialization (const void* p1)
1674 {
1675   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1676 }
1677
1678 /* Like register_specialization, but for local declarations.  We are
1679    registering SPEC, an instantiation of TMPL.  */
1680
1681 static void
1682 register_local_specialization (tree spec, tree tmpl)
1683 {
1684   void **slot;
1685
1686   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1687                                    htab_hash_pointer (tmpl), INSERT);
1688   *slot = build_tree_list (spec, tmpl);
1689 }
1690
1691 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1692    specialized class.  */
1693
1694 bool
1695 explicit_class_specialization_p (tree type)
1696 {
1697   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1698     return false;
1699   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1700 }
1701
1702 /* Print the list of functions at FNS, going through all the overloads
1703    for each element of the list.  Alternatively, FNS can not be a
1704    TREE_LIST, in which case it will be printed together with all the
1705    overloads.
1706
1707    MORE and *STR should respectively be FALSE and NULL when the function
1708    is called from the outside.  They are used internally on recursive
1709    calls.  print_candidates manages the two parameters and leaves NULL
1710    in *STR when it ends.  */
1711
1712 static void
1713 print_candidates_1 (tree fns, bool more, const char **str)
1714 {
1715   tree fn, fn2;
1716   char *spaces = NULL;
1717
1718   for (fn = fns; fn; fn = OVL_NEXT (fn))
1719     if (TREE_CODE (fn) == TREE_LIST)
1720       {
1721         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1722           print_candidates_1 (TREE_VALUE (fn2),
1723                               TREE_CHAIN (fn2) || more, str);
1724       }
1725     else
1726       {
1727         if (!*str)
1728           {
1729             /* Pick the prefix string.  */
1730             if (!more && !OVL_NEXT (fns))
1731               {
1732                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1733                 continue;
1734               }
1735
1736             *str = _("candidates are:");
1737             spaces = get_spaces (*str);
1738           }
1739         error ("%s %+#D", *str, OVL_CURRENT (fn));
1740         *str = spaces ? spaces : *str;
1741       }
1742
1743   if (!more)
1744     {
1745       free (spaces);
1746       *str = NULL;
1747     }
1748 }
1749
1750 /* Print the list of candidate FNS in an error message.  FNS can also
1751    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1752
1753 void
1754 print_candidates (tree fns)
1755 {
1756   const char *str = NULL;
1757   print_candidates_1 (fns, false, &str);
1758   gcc_assert (str == NULL);
1759 }
1760
1761 /* Returns the template (one of the functions given by TEMPLATE_ID)
1762    which can be specialized to match the indicated DECL with the
1763    explicit template args given in TEMPLATE_ID.  The DECL may be
1764    NULL_TREE if none is available.  In that case, the functions in
1765    TEMPLATE_ID are non-members.
1766
1767    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1768    specialization of a member template.
1769
1770    The TEMPLATE_COUNT is the number of references to qualifying
1771    template classes that appeared in the name of the function. See
1772    check_explicit_specialization for a more accurate description.
1773
1774    TSK indicates what kind of template declaration (if any) is being
1775    declared.  TSK_TEMPLATE indicates that the declaration given by
1776    DECL, though a FUNCTION_DECL, has template parameters, and is
1777    therefore a template function.
1778
1779    The template args (those explicitly specified and those deduced)
1780    are output in a newly created vector *TARGS_OUT.
1781
1782    If it is impossible to determine the result, an error message is
1783    issued.  The error_mark_node is returned to indicate failure.  */
1784
1785 static tree
1786 determine_specialization (tree template_id,
1787                           tree decl,
1788                           tree* targs_out,
1789                           int need_member_template,
1790                           int template_count,
1791                           tmpl_spec_kind tsk)
1792 {
1793   tree fns;
1794   tree targs;
1795   tree explicit_targs;
1796   tree candidates = NULL_TREE;
1797   /* A TREE_LIST of templates of which DECL may be a specialization.
1798      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1799      corresponding TREE_PURPOSE is the set of template arguments that,
1800      when used to instantiate the template, would produce a function
1801      with the signature of DECL.  */
1802   tree templates = NULL_TREE;
1803   int header_count;
1804   cp_binding_level *b;
1805
1806   *targs_out = NULL_TREE;
1807
1808   if (template_id == error_mark_node || decl == error_mark_node)
1809     return error_mark_node;
1810
1811   fns = TREE_OPERAND (template_id, 0);
1812   explicit_targs = TREE_OPERAND (template_id, 1);
1813
1814   if (fns == error_mark_node)
1815     return error_mark_node;
1816
1817   /* Check for baselinks.  */
1818   if (BASELINK_P (fns))
1819     fns = BASELINK_FUNCTIONS (fns);
1820
1821   if (!is_overloaded_fn (fns))
1822     {
1823       error ("%qD is not a function template", fns);
1824       return error_mark_node;
1825     }
1826
1827   /* Count the number of template headers specified for this
1828      specialization.  */
1829   header_count = 0;
1830   for (b = current_binding_level;
1831        b->kind == sk_template_parms;
1832        b = b->level_chain)
1833     ++header_count;
1834
1835   for (; fns; fns = OVL_NEXT (fns))
1836     {
1837       tree fn = OVL_CURRENT (fns);
1838
1839       if (TREE_CODE (fn) == TEMPLATE_DECL)
1840         {
1841           tree decl_arg_types;
1842           tree fn_arg_types;
1843
1844           /* In case of explicit specialization, we need to check if
1845              the number of template headers appearing in the specialization
1846              is correct. This is usually done in check_explicit_specialization,
1847              but the check done there cannot be exhaustive when specializing
1848              member functions. Consider the following code:
1849
1850              template <> void A<int>::f(int);
1851              template <> template <> void A<int>::f(int);
1852
1853              Assuming that A<int> is not itself an explicit specialization
1854              already, the first line specializes "f" which is a non-template
1855              member function, whilst the second line specializes "f" which
1856              is a template member function. So both lines are syntactically
1857              correct, and check_explicit_specialization does not reject
1858              them.
1859
1860              Here, we can do better, as we are matching the specialization
1861              against the declarations. We count the number of template
1862              headers, and we check if they match TEMPLATE_COUNT + 1
1863              (TEMPLATE_COUNT is the number of qualifying template classes,
1864              plus there must be another header for the member template
1865              itself).
1866
1867              Notice that if header_count is zero, this is not a
1868              specialization but rather a template instantiation, so there
1869              is no check we can perform here.  */
1870           if (header_count && header_count != template_count + 1)
1871             continue;
1872
1873           /* Check that the number of template arguments at the
1874              innermost level for DECL is the same as for FN.  */
1875           if (current_binding_level->kind == sk_template_parms
1876               && !current_binding_level->explicit_spec_p
1877               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1878                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1879                                       (current_template_parms))))
1880             continue;
1881
1882           /* DECL might be a specialization of FN.  */
1883           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1884           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1885
1886           /* For a non-static member function, we need to make sure
1887              that the const qualification is the same.  Since
1888              get_bindings does not try to merge the "this" parameter,
1889              we must do the comparison explicitly.  */
1890           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1891               && !same_type_p (TREE_VALUE (fn_arg_types),
1892                                TREE_VALUE (decl_arg_types)))
1893             continue;
1894
1895           /* Skip the "this" parameter and, for constructors of
1896              classes with virtual bases, the VTT parameter.  A
1897              full specialization of a constructor will have a VTT
1898              parameter, but a template never will.  */ 
1899           decl_arg_types 
1900             = skip_artificial_parms_for (decl, decl_arg_types);
1901           fn_arg_types 
1902             = skip_artificial_parms_for (fn, fn_arg_types);
1903
1904           /* Check that the number of function parameters matches.
1905              For example,
1906                template <class T> void f(int i = 0);
1907                template <> void f<int>();
1908              The specialization f<int> is invalid but is not caught
1909              by get_bindings below.  */
1910           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1911             continue;
1912
1913           /* Function templates cannot be specializations; there are
1914              no partial specializations of functions.  Therefore, if
1915              the type of DECL does not match FN, there is no
1916              match.  */
1917           if (tsk == tsk_template)
1918             {
1919               if (compparms (fn_arg_types, decl_arg_types))
1920                 candidates = tree_cons (NULL_TREE, fn, candidates);
1921               continue;
1922             }
1923
1924           /* See whether this function might be a specialization of this
1925              template.  */
1926           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1927
1928           if (!targs)
1929             /* We cannot deduce template arguments that when used to
1930                specialize TMPL will produce DECL.  */
1931             continue;
1932
1933           /* Save this template, and the arguments deduced.  */
1934           templates = tree_cons (targs, fn, templates);
1935         }
1936       else if (need_member_template)
1937         /* FN is an ordinary member function, and we need a
1938            specialization of a member template.  */
1939         ;
1940       else if (TREE_CODE (fn) != FUNCTION_DECL)
1941         /* We can get IDENTIFIER_NODEs here in certain erroneous
1942            cases.  */
1943         ;
1944       else if (!DECL_FUNCTION_MEMBER_P (fn))
1945         /* This is just an ordinary non-member function.  Nothing can
1946            be a specialization of that.  */
1947         ;
1948       else if (DECL_ARTIFICIAL (fn))
1949         /* Cannot specialize functions that are created implicitly.  */
1950         ;
1951       else
1952         {
1953           tree decl_arg_types;
1954
1955           /* This is an ordinary member function.  However, since
1956              we're here, we can assume it's enclosing class is a
1957              template class.  For example,
1958
1959                template <typename T> struct S { void f(); };
1960                template <> void S<int>::f() {}
1961
1962              Here, S<int>::f is a non-template, but S<int> is a
1963              template class.  If FN has the same type as DECL, we
1964              might be in business.  */
1965
1966           if (!DECL_TEMPLATE_INFO (fn))
1967             /* Its enclosing class is an explicit specialization
1968                of a template class.  This is not a candidate.  */
1969             continue;
1970
1971           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1972                             TREE_TYPE (TREE_TYPE (fn))))
1973             /* The return types differ.  */
1974             continue;
1975
1976           /* Adjust the type of DECL in case FN is a static member.  */
1977           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1978           if (DECL_STATIC_FUNCTION_P (fn)
1979               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1980             decl_arg_types = TREE_CHAIN (decl_arg_types);
1981
1982           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1983                          decl_arg_types))
1984             /* They match!  */
1985             candidates = tree_cons (NULL_TREE, fn, candidates);
1986         }
1987     }
1988
1989   if (templates && TREE_CHAIN (templates))
1990     {
1991       /* We have:
1992
1993            [temp.expl.spec]
1994
1995            It is possible for a specialization with a given function
1996            signature to be instantiated from more than one function
1997            template.  In such cases, explicit specification of the
1998            template arguments must be used to uniquely identify the
1999            function template specialization being specialized.
2000
2001          Note that here, there's no suggestion that we're supposed to
2002          determine which of the candidate templates is most
2003          specialized.  However, we, also have:
2004
2005            [temp.func.order]
2006
2007            Partial ordering of overloaded function template
2008            declarations is used in the following contexts to select
2009            the function template to which a function template
2010            specialization refers:
2011
2012            -- when an explicit specialization refers to a function
2013               template.
2014
2015          So, we do use the partial ordering rules, at least for now.
2016          This extension can only serve to make invalid programs valid,
2017          so it's safe.  And, there is strong anecdotal evidence that
2018          the committee intended the partial ordering rules to apply;
2019          the EDG front end has that behavior, and John Spicer claims
2020          that the committee simply forgot to delete the wording in
2021          [temp.expl.spec].  */
2022       tree tmpl = most_specialized_instantiation (templates);
2023       if (tmpl != error_mark_node)
2024         {
2025           templates = tmpl;
2026           TREE_CHAIN (templates) = NULL_TREE;
2027         }
2028     }
2029
2030   if (templates == NULL_TREE && candidates == NULL_TREE)
2031     {
2032       error ("template-id %qD for %q+D does not match any template "
2033              "declaration", template_id, decl);
2034       if (header_count && header_count != template_count + 1)
2035         inform (input_location, "saw %d %<template<>%>, need %d for "
2036                 "specializing a member function template",
2037                 header_count, template_count + 1);
2038       return error_mark_node;
2039     }
2040   else if ((templates && TREE_CHAIN (templates))
2041            || (candidates && TREE_CHAIN (candidates))
2042            || (templates && candidates))
2043     {
2044       error ("ambiguous template specialization %qD for %q+D",
2045              template_id, decl);
2046       candidates = chainon (candidates, templates);
2047       print_candidates (candidates);
2048       return error_mark_node;
2049     }
2050
2051   /* We have one, and exactly one, match.  */
2052   if (candidates)
2053     {
2054       tree fn = TREE_VALUE (candidates);
2055       *targs_out = copy_node (DECL_TI_ARGS (fn));
2056       /* DECL is a re-declaration or partial instantiation of a template
2057          function.  */
2058       if (TREE_CODE (fn) == TEMPLATE_DECL)
2059         return fn;
2060       /* It was a specialization of an ordinary member function in a
2061          template class.  */
2062       return DECL_TI_TEMPLATE (fn);
2063     }
2064
2065   /* It was a specialization of a template.  */
2066   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2067   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2068     {
2069       *targs_out = copy_node (targs);
2070       SET_TMPL_ARGS_LEVEL (*targs_out,
2071                            TMPL_ARGS_DEPTH (*targs_out),
2072                            TREE_PURPOSE (templates));
2073     }
2074   else
2075     *targs_out = TREE_PURPOSE (templates);
2076   return TREE_VALUE (templates);
2077 }
2078
2079 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2080    but with the default argument values filled in from those in the
2081    TMPL_TYPES.  */
2082
2083 static tree
2084 copy_default_args_to_explicit_spec_1 (tree spec_types,
2085                                       tree tmpl_types)
2086 {
2087   tree new_spec_types;
2088
2089   if (!spec_types)
2090     return NULL_TREE;
2091
2092   if (spec_types == void_list_node)
2093     return void_list_node;
2094
2095   /* Substitute into the rest of the list.  */
2096   new_spec_types =
2097     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2098                                           TREE_CHAIN (tmpl_types));
2099
2100   /* Add the default argument for this parameter.  */
2101   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2102                          TREE_VALUE (spec_types),
2103                          new_spec_types);
2104 }
2105
2106 /* DECL is an explicit specialization.  Replicate default arguments
2107    from the template it specializes.  (That way, code like:
2108
2109      template <class T> void f(T = 3);
2110      template <> void f(double);
2111      void g () { f (); }
2112
2113    works, as required.)  An alternative approach would be to look up
2114    the correct default arguments at the call-site, but this approach
2115    is consistent with how implicit instantiations are handled.  */
2116
2117 static void
2118 copy_default_args_to_explicit_spec (tree decl)
2119 {
2120   tree tmpl;
2121   tree spec_types;
2122   tree tmpl_types;
2123   tree new_spec_types;
2124   tree old_type;
2125   tree new_type;
2126   tree t;
2127   tree object_type = NULL_TREE;
2128   tree in_charge = NULL_TREE;
2129   tree vtt = NULL_TREE;
2130
2131   /* See if there's anything we need to do.  */
2132   tmpl = DECL_TI_TEMPLATE (decl);
2133   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2134   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2135     if (TREE_PURPOSE (t))
2136       break;
2137   if (!t)
2138     return;
2139
2140   old_type = TREE_TYPE (decl);
2141   spec_types = TYPE_ARG_TYPES (old_type);
2142
2143   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2144     {
2145       /* Remove the this pointer, but remember the object's type for
2146          CV quals.  */
2147       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2148       spec_types = TREE_CHAIN (spec_types);
2149       tmpl_types = TREE_CHAIN (tmpl_types);
2150
2151       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2152         {
2153           /* DECL may contain more parameters than TMPL due to the extra
2154              in-charge parameter in constructors and destructors.  */
2155           in_charge = spec_types;
2156           spec_types = TREE_CHAIN (spec_types);
2157         }
2158       if (DECL_HAS_VTT_PARM_P (decl))
2159         {
2160           vtt = spec_types;
2161           spec_types = TREE_CHAIN (spec_types);
2162         }
2163     }
2164
2165   /* Compute the merged default arguments.  */
2166   new_spec_types =
2167     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2168
2169   /* Compute the new FUNCTION_TYPE.  */
2170   if (object_type)
2171     {
2172       if (vtt)
2173         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2174                                          TREE_VALUE (vtt),
2175                                          new_spec_types);
2176
2177       if (in_charge)
2178         /* Put the in-charge parameter back.  */
2179         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2180                                          TREE_VALUE (in_charge),
2181                                          new_spec_types);
2182
2183       new_type = build_method_type_directly (object_type,
2184                                              TREE_TYPE (old_type),
2185                                              new_spec_types);
2186     }
2187   else
2188     new_type = build_function_type (TREE_TYPE (old_type),
2189                                     new_spec_types);
2190   new_type = cp_build_type_attribute_variant (new_type,
2191                                               TYPE_ATTRIBUTES (old_type));
2192   new_type = build_exception_variant (new_type,
2193                                       TYPE_RAISES_EXCEPTIONS (old_type));
2194   TREE_TYPE (decl) = new_type;
2195 }
2196
2197 /* Check to see if the function just declared, as indicated in
2198    DECLARATOR, and in DECL, is a specialization of a function
2199    template.  We may also discover that the declaration is an explicit
2200    instantiation at this point.
2201
2202    Returns DECL, or an equivalent declaration that should be used
2203    instead if all goes well.  Issues an error message if something is
2204    amiss.  Returns error_mark_node if the error is not easily
2205    recoverable.
2206
2207    FLAGS is a bitmask consisting of the following flags:
2208
2209    2: The function has a definition.
2210    4: The function is a friend.
2211
2212    The TEMPLATE_COUNT is the number of references to qualifying
2213    template classes that appeared in the name of the function.  For
2214    example, in
2215
2216      template <class T> struct S { void f(); };
2217      void S<int>::f();
2218
2219    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2220    classes are not counted in the TEMPLATE_COUNT, so that in
2221
2222      template <class T> struct S {};
2223      template <> struct S<int> { void f(); }
2224      template <> void S<int>::f();
2225
2226    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2227    invalid; there should be no template <>.)
2228
2229    If the function is a specialization, it is marked as such via
2230    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2231    is set up correctly, and it is added to the list of specializations
2232    for that template.  */
2233
2234 tree
2235 check_explicit_specialization (tree declarator,
2236                                tree decl,
2237                                int template_count,
2238                                int flags)
2239 {
2240   int have_def = flags & 2;
2241   int is_friend = flags & 4;
2242   int specialization = 0;
2243   int explicit_instantiation = 0;
2244   int member_specialization = 0;
2245   tree ctype = DECL_CLASS_CONTEXT (decl);
2246   tree dname = DECL_NAME (decl);
2247   tmpl_spec_kind tsk;
2248
2249   if (is_friend)
2250     {
2251       if (!processing_specialization)
2252         tsk = tsk_none;
2253       else
2254         tsk = tsk_excessive_parms;
2255     }
2256   else
2257     tsk = current_tmpl_spec_kind (template_count);
2258
2259   switch (tsk)
2260     {
2261     case tsk_none:
2262       if (processing_specialization)
2263         {
2264           specialization = 1;
2265           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2266         }
2267       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2268         {
2269           if (is_friend)
2270             /* This could be something like:
2271
2272                template <class T> void f(T);
2273                class S { friend void f<>(int); }  */
2274             specialization = 1;
2275           else
2276             {
2277               /* This case handles bogus declarations like template <>
2278                  template <class T> void f<int>(); */
2279
2280               error ("template-id %qD in declaration of primary template",
2281                      declarator);
2282               return decl;
2283             }
2284         }
2285       break;
2286
2287     case tsk_invalid_member_spec:
2288       /* The error has already been reported in
2289          check_specialization_scope.  */
2290       return error_mark_node;
2291
2292     case tsk_invalid_expl_inst:
2293       error ("template parameter list used in explicit instantiation");
2294
2295       /* Fall through.  */
2296
2297     case tsk_expl_inst:
2298       if (have_def)
2299         error ("definition provided for explicit instantiation");
2300
2301       explicit_instantiation = 1;
2302       break;
2303
2304     case tsk_excessive_parms:
2305     case tsk_insufficient_parms:
2306       if (tsk == tsk_excessive_parms)
2307         error ("too many template parameter lists in declaration of %qD",
2308                decl);
2309       else if (template_header_count)
2310         error("too few template parameter lists in declaration of %qD", decl);
2311       else
2312         error("explicit specialization of %qD must be introduced by "
2313               "%<template <>%>", decl);
2314
2315       /* Fall through.  */
2316     case tsk_expl_spec:
2317       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2318       if (ctype)
2319         member_specialization = 1;
2320       else
2321         specialization = 1;
2322       break;
2323
2324     case tsk_template:
2325       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2326         {
2327           /* This case handles bogus declarations like template <>
2328              template <class T> void f<int>(); */
2329
2330           if (uses_template_parms (declarator))
2331             error ("function template partial specialization %qD "
2332                    "is not allowed", declarator);
2333           else
2334             error ("template-id %qD in declaration of primary template",
2335                    declarator);
2336           return decl;
2337         }
2338
2339       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2340         /* This is a specialization of a member template, without
2341            specialization the containing class.  Something like:
2342
2343              template <class T> struct S {
2344                template <class U> void f (U);
2345              };
2346              template <> template <class U> void S<int>::f(U) {}
2347
2348            That's a specialization -- but of the entire template.  */
2349         specialization = 1;
2350       break;
2351
2352     default:
2353       gcc_unreachable ();
2354     }
2355
2356   if (specialization || member_specialization)
2357     {
2358       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2359       for (; t; t = TREE_CHAIN (t))
2360         if (TREE_PURPOSE (t))
2361           {
2362             permerror (input_location, 
2363                        "default argument specified in explicit specialization");
2364             break;
2365           }
2366     }
2367
2368   if (specialization || member_specialization || explicit_instantiation)
2369     {
2370       tree tmpl = NULL_TREE;
2371       tree targs = NULL_TREE;
2372
2373       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2374       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2375         {
2376           tree fns;
2377
2378           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2379           if (ctype)
2380             fns = dname;
2381           else
2382             {
2383               /* If there is no class context, the explicit instantiation
2384                  must be at namespace scope.  */
2385               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2386
2387               /* Find the namespace binding, using the declaration
2388                  context.  */
2389               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2390                                            false, true);
2391               if (fns == error_mark_node || !is_overloaded_fn (fns))
2392                 {
2393                   error ("%qD is not a template function", dname);
2394                   fns = error_mark_node;
2395                 }
2396               else
2397                 {
2398                   tree fn = OVL_CURRENT (fns);
2399                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2400                                                 CP_DECL_CONTEXT (fn)))
2401                     error ("%qD is not declared in %qD",
2402                            decl, current_namespace);
2403                 }
2404             }
2405
2406           declarator = lookup_template_function (fns, NULL_TREE);
2407         }
2408
2409       if (declarator == error_mark_node)
2410         return error_mark_node;
2411
2412       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2413         {
2414           if (!explicit_instantiation)
2415             /* A specialization in class scope.  This is invalid,
2416                but the error will already have been flagged by
2417                check_specialization_scope.  */
2418             return error_mark_node;
2419           else
2420             {
2421               /* It's not valid to write an explicit instantiation in
2422                  class scope, e.g.:
2423
2424                    class C { template void f(); }
2425
2426                    This case is caught by the parser.  However, on
2427                    something like:
2428
2429                    template class C { void f(); };
2430
2431                    (which is invalid) we can get here.  The error will be
2432                    issued later.  */
2433               ;
2434             }
2435
2436           return decl;
2437         }
2438       else if (ctype != NULL_TREE
2439                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2440                    IDENTIFIER_NODE))
2441         {
2442           /* Find the list of functions in ctype that have the same
2443              name as the declared function.  */
2444           tree name = TREE_OPERAND (declarator, 0);
2445           tree fns = NULL_TREE;
2446           int idx;
2447
2448           if (constructor_name_p (name, ctype))
2449             {
2450               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2451
2452               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2453                   : !CLASSTYPE_DESTRUCTORS (ctype))
2454                 {
2455                   /* From [temp.expl.spec]:
2456
2457                      If such an explicit specialization for the member
2458                      of a class template names an implicitly-declared
2459                      special member function (clause _special_), the
2460                      program is ill-formed.
2461
2462                      Similar language is found in [temp.explicit].  */
2463                   error ("specialization of implicitly-declared special member function");
2464                   return error_mark_node;
2465                 }
2466
2467               name = is_constructor ? ctor_identifier : dtor_identifier;
2468             }
2469
2470           if (!DECL_CONV_FN_P (decl))
2471             {
2472               idx = lookup_fnfields_1 (ctype, name);
2473               if (idx >= 0)
2474                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2475             }
2476           else
2477             {
2478               VEC(tree,gc) *methods;
2479               tree ovl;
2480
2481               /* For a type-conversion operator, we cannot do a
2482                  name-based lookup.  We might be looking for `operator
2483                  int' which will be a specialization of `operator T'.
2484                  So, we find *all* the conversion operators, and then
2485                  select from them.  */
2486               fns = NULL_TREE;
2487
2488               methods = CLASSTYPE_METHOD_VEC (ctype);
2489               if (methods)
2490                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2491                      VEC_iterate (tree, methods, idx, ovl);
2492                      ++idx)
2493                   {
2494                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2495                       /* There are no more conversion functions.  */
2496                       break;
2497
2498                     /* Glue all these conversion functions together
2499                        with those we already have.  */
2500                     for (; ovl; ovl = OVL_NEXT (ovl))
2501                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2502                   }
2503             }
2504
2505           if (fns == NULL_TREE)
2506             {
2507               error ("no member function %qD declared in %qT", name, ctype);
2508               return error_mark_node;
2509             }
2510           else
2511             TREE_OPERAND (declarator, 0) = fns;
2512         }
2513
2514       /* Figure out what exactly is being specialized at this point.
2515          Note that for an explicit instantiation, even one for a
2516          member function, we cannot tell apriori whether the
2517          instantiation is for a member template, or just a member
2518          function of a template class.  Even if a member template is
2519          being instantiated, the member template arguments may be
2520          elided if they can be deduced from the rest of the
2521          declaration.  */
2522       tmpl = determine_specialization (declarator, decl,
2523                                        &targs,
2524                                        member_specialization,
2525                                        template_count,
2526                                        tsk);
2527
2528       if (!tmpl || tmpl == error_mark_node)
2529         /* We couldn't figure out what this declaration was
2530            specializing.  */
2531         return error_mark_node;
2532       else
2533         {
2534           tree gen_tmpl = most_general_template (tmpl);
2535
2536           if (explicit_instantiation)
2537             {
2538               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2539                  is done by do_decl_instantiation later.  */
2540
2541               int arg_depth = TMPL_ARGS_DEPTH (targs);
2542               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2543
2544               if (arg_depth > parm_depth)
2545                 {
2546                   /* If TMPL is not the most general template (for
2547                      example, if TMPL is a friend template that is
2548                      injected into namespace scope), then there will
2549                      be too many levels of TARGS.  Remove some of them
2550                      here.  */
2551                   int i;
2552                   tree new_targs;
2553
2554                   new_targs = make_tree_vec (parm_depth);
2555                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2556                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2557                       = TREE_VEC_ELT (targs, i);
2558                   targs = new_targs;
2559                 }
2560
2561               return instantiate_template (tmpl, targs, tf_error);
2562             }
2563
2564           /* If we thought that the DECL was a member function, but it
2565              turns out to be specializing a static member function,
2566              make DECL a static member function as well.  */
2567           if (DECL_STATIC_FUNCTION_P (tmpl)
2568               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2569             revert_static_member_fn (decl);
2570
2571           /* If this is a specialization of a member template of a
2572              template class, we want to return the TEMPLATE_DECL, not
2573              the specialization of it.  */
2574           if (tsk == tsk_template)
2575             {
2576               tree result = DECL_TEMPLATE_RESULT (tmpl);
2577               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2578               DECL_INITIAL (result) = NULL_TREE;
2579               if (have_def)
2580                 {
2581                   tree parm;
2582                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2583                   DECL_SOURCE_LOCATION (result)
2584                     = DECL_SOURCE_LOCATION (decl);
2585                   /* We want to use the argument list specified in the
2586                      definition, not in the original declaration.  */
2587                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2588                   for (parm = DECL_ARGUMENTS (result); parm;
2589                        parm = DECL_CHAIN (parm))
2590                     DECL_CONTEXT (parm) = result;
2591                 }
2592               return register_specialization (tmpl, gen_tmpl, targs,
2593                                               is_friend, 0);
2594             }
2595
2596           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2597           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2598
2599           /* Inherit default function arguments from the template
2600              DECL is specializing.  */
2601           copy_default_args_to_explicit_spec (decl);
2602
2603           /* This specialization has the same protection as the
2604              template it specializes.  */
2605           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2606           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2607
2608           /* 7.1.1-1 [dcl.stc]
2609
2610              A storage-class-specifier shall not be specified in an
2611              explicit specialization...
2612
2613              The parser rejects these, so unless action is taken here,
2614              explicit function specializations will always appear with
2615              global linkage.
2616
2617              The action recommended by the C++ CWG in response to C++
2618              defect report 605 is to make the storage class and linkage
2619              of the explicit specialization match the templated function:
2620
2621              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2622            */
2623           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2624             {
2625               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2626               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2627
2628               /* This specialization has the same linkage and visibility as
2629                  the function template it specializes.  */
2630               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2631               if (! TREE_PUBLIC (decl))
2632                 {
2633                   DECL_INTERFACE_KNOWN (decl) = 1;
2634                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2635                 }
2636               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2637               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2638                 {
2639                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2640                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2641                 }
2642             }
2643
2644           /* If DECL is a friend declaration, declared using an
2645              unqualified name, the namespace associated with DECL may
2646              have been set incorrectly.  For example, in:
2647
2648                template <typename T> void f(T);
2649                namespace N {
2650                  struct S { friend void f<int>(int); }
2651                }
2652
2653              we will have set the DECL_CONTEXT for the friend
2654              declaration to N, rather than to the global namespace.  */
2655           if (DECL_NAMESPACE_SCOPE_P (decl))
2656             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2657
2658           if (is_friend && !have_def)
2659             /* This is not really a declaration of a specialization.
2660                It's just the name of an instantiation.  But, it's not
2661                a request for an instantiation, either.  */
2662             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2663           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2664             /* This is indeed a specialization.  In case of constructors
2665                and destructors, we need in-charge and not-in-charge
2666                versions in V3 ABI.  */
2667             clone_function_decl (decl, /*update_method_vec_p=*/0);
2668
2669           /* Register this specialization so that we can find it
2670              again.  */
2671           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2672         }
2673     }
2674
2675   return decl;
2676 }
2677
2678 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2679    parameters.  These are represented in the same format used for
2680    DECL_TEMPLATE_PARMS.  */
2681
2682 int
2683 comp_template_parms (const_tree parms1, const_tree parms2)
2684 {
2685   const_tree p1;
2686   const_tree p2;
2687
2688   if (parms1 == parms2)
2689     return 1;
2690
2691   for (p1 = parms1, p2 = parms2;
2692        p1 != NULL_TREE && p2 != NULL_TREE;
2693        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2694     {
2695       tree t1 = TREE_VALUE (p1);
2696       tree t2 = TREE_VALUE (p2);
2697       int i;
2698
2699       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2700       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2701
2702       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2703         return 0;
2704
2705       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2706         {
2707           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2708           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2709
2710           /* If either of the template parameters are invalid, assume
2711              they match for the sake of error recovery. */
2712           if (parm1 == error_mark_node || parm2 == error_mark_node)
2713             return 1;
2714
2715           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2716             return 0;
2717
2718           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2719               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2720                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2721             continue;
2722           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2723             return 0;
2724         }
2725     }
2726
2727   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2728     /* One set of parameters has more parameters lists than the
2729        other.  */
2730     return 0;
2731
2732   return 1;
2733 }
2734
2735 /* Determine whether PARM is a parameter pack.  */
2736
2737 bool 
2738 template_parameter_pack_p (const_tree parm)
2739 {
2740   /* Determine if we have a non-type template parameter pack.  */
2741   if (TREE_CODE (parm) == PARM_DECL)
2742     return (DECL_TEMPLATE_PARM_P (parm) 
2743             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2744
2745   /* If this is a list of template parameters, we could get a
2746      TYPE_DECL or a TEMPLATE_DECL.  */ 
2747   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2748     parm = TREE_TYPE (parm);
2749
2750   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2751            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2752           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2753 }
2754
2755 /* Determine if T is a function parameter pack.  */
2756
2757 bool
2758 function_parameter_pack_p (const_tree t)
2759 {
2760   if (t && TREE_CODE (t) == PARM_DECL)
2761     return FUNCTION_PARAMETER_PACK_P (t);
2762   return false;
2763 }
2764
2765 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2766    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2767
2768 tree
2769 get_function_template_decl (const_tree primary_func_tmpl_inst)
2770 {
2771   if (! primary_func_tmpl_inst
2772       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2773       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2774     return NULL;
2775
2776   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2777 }
2778
2779 /* Return true iff the function parameter PARAM_DECL was expanded
2780    from the function parameter pack PACK.  */
2781
2782 bool
2783 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2784 {
2785   if (DECL_ARTIFICIAL (param_decl)
2786       || !function_parameter_pack_p (pack))
2787     return false;
2788
2789   /* The parameter pack and its pack arguments have the same
2790      DECL_PARM_INDEX.  */
2791   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2792 }
2793
2794 /* Determine whether ARGS describes a variadic template args list,
2795    i.e., one that is terminated by a template argument pack.  */
2796
2797 static bool 
2798 template_args_variadic_p (tree args)
2799 {
2800   int nargs;
2801   tree last_parm;
2802
2803   if (args == NULL_TREE)
2804     return false;
2805
2806   args = INNERMOST_TEMPLATE_ARGS (args);
2807   nargs = TREE_VEC_LENGTH (args);
2808
2809   if (nargs == 0)
2810     return false;
2811
2812   last_parm = TREE_VEC_ELT (args, nargs - 1);
2813
2814   return ARGUMENT_PACK_P (last_parm);
2815 }
2816
2817 /* Generate a new name for the parameter pack name NAME (an
2818    IDENTIFIER_NODE) that incorporates its */
2819
2820 static tree
2821 make_ith_pack_parameter_name (tree name, int i)
2822 {
2823   /* Munge the name to include the parameter index.  */
2824 #define NUMBUF_LEN 128
2825   char numbuf[NUMBUF_LEN];
2826   char* newname;
2827   int newname_len;
2828
2829   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2830   newname_len = IDENTIFIER_LENGTH (name)
2831                 + strlen (numbuf) + 2;
2832   newname = (char*)alloca (newname_len);
2833   snprintf (newname, newname_len,
2834             "%s#%i", IDENTIFIER_POINTER (name), i);
2835   return get_identifier (newname);
2836 }
2837
2838 /* Return true if T is a primary function
2839    or class template instantiation.  */
2840
2841 bool
2842 primary_template_instantiation_p (const_tree t)
2843 {
2844   if (!t)
2845     return false;
2846
2847   if (TREE_CODE (t) == FUNCTION_DECL)
2848     return DECL_LANG_SPECIFIC (t)
2849            && DECL_TEMPLATE_INSTANTIATION (t)
2850            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2851   else if (CLASS_TYPE_P (t))
2852     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2853            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2854   return false;
2855 }
2856
2857 /* Return true if PARM is a template template parameter.  */
2858
2859 bool
2860 template_template_parameter_p (const_tree parm)
2861 {
2862   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2863 }
2864
2865 /* Return the template parameters of T if T is a
2866    primary template instantiation, NULL otherwise.  */
2867
2868 tree
2869 get_primary_template_innermost_parameters (const_tree t)
2870 {
2871   tree parms = NULL, template_info = NULL;
2872
2873   if ((template_info = get_template_info (t))
2874       && primary_template_instantiation_p (t))
2875     parms = INNERMOST_TEMPLATE_PARMS
2876         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2877
2878   return parms;
2879 }
2880
2881 /* Return the template parameters of the LEVELth level from the full list
2882    of template parameters PARMS.  */
2883
2884 tree
2885 get_template_parms_at_level (tree parms, int level)
2886 {
2887   tree p;
2888   if (!parms
2889       || TREE_CODE (parms) != TREE_LIST
2890       || level > TMPL_PARMS_DEPTH (parms))
2891     return NULL_TREE;
2892
2893   for (p = parms; p; p = TREE_CHAIN (p))
2894     if (TMPL_PARMS_DEPTH (p) == level)
2895       return p;
2896
2897   return NULL_TREE;
2898 }
2899
2900 /* Returns the template arguments of T if T is a template instantiation,
2901    NULL otherwise.  */
2902
2903 tree
2904 get_template_innermost_arguments (const_tree t)
2905 {
2906   tree args = NULL, template_info = NULL;
2907
2908   if ((template_info = get_template_info (t))
2909       && TI_ARGS (template_info))
2910     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2911
2912   return args;
2913 }
2914
2915 /* Return the argument pack elements of T if T is a template argument pack,
2916    NULL otherwise.  */
2917
2918 tree
2919 get_template_argument_pack_elems (const_tree t)
2920 {
2921   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2922       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2923     return NULL;
2924
2925   return ARGUMENT_PACK_ARGS (t);
2926 }
2927
2928 /* Structure used to track the progress of find_parameter_packs_r.  */
2929 struct find_parameter_pack_data 
2930 {
2931   /* TREE_LIST that will contain all of the parameter packs found by
2932      the traversal.  */
2933   tree* parameter_packs;
2934
2935   /* Set of AST nodes that have been visited by the traversal.  */
2936   struct pointer_set_t *visited;
2937 };
2938
2939 /* Identifies all of the argument packs that occur in a template
2940    argument and appends them to the TREE_LIST inside DATA, which is a
2941    find_parameter_pack_data structure. This is a subroutine of
2942    make_pack_expansion and uses_parameter_packs.  */
2943 static tree
2944 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2945 {
2946   tree t = *tp;
2947   struct find_parameter_pack_data* ppd = 
2948     (struct find_parameter_pack_data*)data;
2949   bool parameter_pack_p = false;
2950
2951   /* Identify whether this is a parameter pack or not.  */
2952   switch (TREE_CODE (t))
2953     {
2954     case TEMPLATE_PARM_INDEX:
2955       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2956         parameter_pack_p = true;
2957       break;
2958
2959     case TEMPLATE_TYPE_PARM:
2960     case TEMPLATE_TEMPLATE_PARM:
2961       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2962         parameter_pack_p = true;
2963       break;
2964
2965     case PARM_DECL:
2966       if (FUNCTION_PARAMETER_PACK_P (t))
2967         {
2968           /* We don't want to walk into the type of a PARM_DECL,
2969              because we don't want to see the type parameter pack.  */
2970           *walk_subtrees = 0;
2971           parameter_pack_p = true;
2972         }
2973       break;
2974
2975     default:
2976       /* Not a parameter pack.  */
2977       break;
2978     }
2979
2980   if (parameter_pack_p)
2981     {
2982       /* Add this parameter pack to the list.  */
2983       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2984     }
2985
2986   if (TYPE_P (t))
2987     cp_walk_tree (&TYPE_CONTEXT (t), 
2988                   &find_parameter_packs_r, ppd, ppd->visited);
2989
2990   /* This switch statement will return immediately if we don't find a
2991      parameter pack.  */
2992   switch (TREE_CODE (t)) 
2993     {
2994     case TEMPLATE_PARM_INDEX:
2995       return NULL_TREE;
2996
2997     case BOUND_TEMPLATE_TEMPLATE_PARM:
2998       /* Check the template itself.  */
2999       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3000                     &find_parameter_packs_r, ppd, ppd->visited);
3001       /* Check the template arguments.  */
3002       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3003                     ppd->visited);
3004       *walk_subtrees = 0;
3005       return NULL_TREE;
3006
3007     case TEMPLATE_TYPE_PARM:
3008     case TEMPLATE_TEMPLATE_PARM:
3009       return NULL_TREE;
3010
3011     case PARM_DECL:
3012       return NULL_TREE;
3013
3014     case RECORD_TYPE:
3015       if (TYPE_PTRMEMFUNC_P (t))
3016         return NULL_TREE;
3017       /* Fall through.  */
3018
3019     case UNION_TYPE:
3020     case ENUMERAL_TYPE:
3021       if (TYPE_TEMPLATE_INFO (t))
3022         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3023                       &find_parameter_packs_r, ppd, ppd->visited);
3024
3025       *walk_subtrees = 0;
3026       return NULL_TREE;
3027
3028     case CONSTRUCTOR:
3029     case TEMPLATE_DECL:
3030       cp_walk_tree (&TREE_TYPE (t),
3031                     &find_parameter_packs_r, ppd, ppd->visited);
3032       return NULL_TREE;
3033  
3034     case TYPENAME_TYPE:
3035       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3036                    ppd, ppd->visited);
3037       *walk_subtrees = 0;
3038       return NULL_TREE;
3039       
3040     case TYPE_PACK_EXPANSION:
3041     case EXPR_PACK_EXPANSION:
3042       *walk_subtrees = 0;
3043       return NULL_TREE;
3044
3045     case INTEGER_TYPE:
3046       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3047                     ppd, ppd->visited);
3048       *walk_subtrees = 0;
3049       return NULL_TREE;
3050
3051     case IDENTIFIER_NODE:
3052       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3053                     ppd->visited);
3054       *walk_subtrees = 0;
3055       return NULL_TREE;
3056
3057     default:
3058       return NULL_TREE;
3059     }
3060
3061   return NULL_TREE;
3062 }
3063
3064 /* Determines if the expression or type T uses any parameter packs.  */
3065 bool
3066 uses_parameter_packs (tree t)
3067 {
3068   tree parameter_packs = NULL_TREE;
3069   struct find_parameter_pack_data ppd;
3070   ppd.parameter_packs = &parameter_packs;
3071   ppd.visited = pointer_set_create ();
3072   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3073   pointer_set_destroy (ppd.visited);
3074   return parameter_packs != NULL_TREE;
3075 }
3076
3077 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3078    representation a base-class initializer into a parameter pack
3079    expansion. If all goes well, the resulting node will be an
3080    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3081    respectively.  */
3082 tree 
3083 make_pack_expansion (tree arg)
3084 {
3085   tree result;
3086   tree parameter_packs = NULL_TREE;
3087   bool for_types = false;
3088   struct find_parameter_pack_data ppd;
3089
3090   if (!arg || arg == error_mark_node)
3091     return arg;
3092
3093   if (TREE_CODE (arg) == TREE_LIST)
3094     {
3095       /* The only time we will see a TREE_LIST here is for a base
3096          class initializer.  In this case, the TREE_PURPOSE will be a
3097          _TYPE node (representing the base class expansion we're
3098          initializing) and the TREE_VALUE will be a TREE_LIST
3099          containing the initialization arguments. 
3100
3101          The resulting expansion looks somewhat different from most
3102          expansions. Rather than returning just one _EXPANSION, we
3103          return a TREE_LIST whose TREE_PURPOSE is a
3104          TYPE_PACK_EXPANSION containing the bases that will be
3105          initialized.  The TREE_VALUE will be identical to the
3106          original TREE_VALUE, which is a list of arguments that will
3107          be passed to each base.  We do not introduce any new pack
3108          expansion nodes into the TREE_VALUE (although it is possible
3109          that some already exist), because the TREE_PURPOSE and
3110          TREE_VALUE all need to be expanded together with the same
3111          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3112          resulting TREE_PURPOSE will mention the parameter packs in
3113          both the bases and the arguments to the bases.  */
3114       tree purpose;
3115       tree value;
3116       tree parameter_packs = NULL_TREE;
3117
3118       /* Determine which parameter packs will be used by the base
3119          class expansion.  */
3120       ppd.visited = pointer_set_create ();
3121       ppd.parameter_packs = &parameter_packs;
3122       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3123                     &ppd, ppd.visited);
3124
3125       if (parameter_packs == NULL_TREE)
3126         {
3127           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3128           pointer_set_destroy (ppd.visited);
3129           return error_mark_node;
3130         }
3131
3132       if (TREE_VALUE (arg) != void_type_node)
3133         {
3134           /* Collect the sets of parameter packs used in each of the
3135              initialization arguments.  */
3136           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3137             {
3138               /* Determine which parameter packs will be expanded in this
3139                  argument.  */
3140               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3141                             &ppd, ppd.visited);
3142             }
3143         }
3144
3145       pointer_set_destroy (ppd.visited);
3146
3147       /* Create the pack expansion type for the base type.  */
3148       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3149       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3150       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3151
3152       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3153          they will rarely be compared to anything.  */
3154       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3155
3156       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3157     }
3158
3159   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3160     for_types = true;
3161
3162   /* Build the PACK_EXPANSION_* node.  */
3163   result = for_types
3164      ? cxx_make_type (TYPE_PACK_EXPANSION)
3165      : make_node (EXPR_PACK_EXPANSION);
3166   SET_PACK_EXPANSION_PATTERN (result, arg);
3167   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3168     {
3169       /* Propagate type and const-expression information.  */
3170       TREE_TYPE (result) = TREE_TYPE (arg);
3171       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3172     }
3173   else
3174     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3175        they will rarely be compared to anything.  */
3176     SET_TYPE_STRUCTURAL_EQUALITY (result);
3177
3178   /* Determine which parameter packs will be expanded.  */
3179   ppd.parameter_packs = &parameter_packs;
3180   ppd.visited = pointer_set_create ();
3181   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3182   pointer_set_destroy (ppd.visited);
3183
3184   /* Make sure we found some parameter packs.  */
3185   if (parameter_packs == NULL_TREE)
3186     {
3187       if (TYPE_P (arg))
3188         error ("expansion pattern %<%T%> contains no argument packs", arg);
3189       else
3190         error ("expansion pattern %<%E%> contains no argument packs", arg);
3191       return error_mark_node;
3192     }
3193   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3194
3195   return result;
3196 }
3197
3198 /* Checks T for any "bare" parameter packs, which have not yet been
3199    expanded, and issues an error if any are found. This operation can
3200    only be done on full expressions or types (e.g., an expression
3201    statement, "if" condition, etc.), because we could have expressions like:
3202
3203      foo(f(g(h(args)))...)
3204
3205    where "args" is a parameter pack. check_for_bare_parameter_packs
3206    should not be called for the subexpressions args, h(args),
3207    g(h(args)), or f(g(h(args))), because we would produce erroneous
3208    error messages. 
3209
3210    Returns TRUE and emits an error if there were bare parameter packs,
3211    returns FALSE otherwise.  */
3212 bool 
3213 check_for_bare_parameter_packs (tree t)
3214 {
3215   tree parameter_packs = NULL_TREE;
3216   struct find_parameter_pack_data ppd;
3217
3218   if (!processing_template_decl || !t || t == error_mark_node)
3219     return false;
3220
3221   if (TREE_CODE (t) == TYPE_DECL)
3222     t = TREE_TYPE (t);
3223
3224   ppd.parameter_packs = &parameter_packs;
3225   ppd.visited = pointer_set_create ();
3226   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3227   pointer_set_destroy (ppd.visited);
3228
3229   if (parameter_packs) 
3230     {
3231       error ("parameter packs not expanded with %<...%>:");
3232       while (parameter_packs)
3233         {
3234           tree pack = TREE_VALUE (parameter_packs);
3235           tree name = NULL_TREE;
3236
3237           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3238               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3239             name = TYPE_NAME (pack);
3240           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3241             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3242           else
3243             name = DECL_NAME (pack);
3244
3245           if (name)
3246             inform (input_location, "        %qD", name);
3247           else
3248             inform (input_location, "        <anonymous>");
3249
3250           parameter_packs = TREE_CHAIN (parameter_packs);
3251         }
3252
3253       return true;
3254     }
3255
3256   return false;
3257 }
3258
3259 /* Expand any parameter packs that occur in the template arguments in
3260    ARGS.  */
3261 tree
3262 expand_template_argument_pack (tree args)
3263 {
3264   tree result_args = NULL_TREE;
3265   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3266   int num_result_args = -1;
3267   int non_default_args_count = -1;
3268
3269   /* First, determine if we need to expand anything, and the number of
3270      slots we'll need.  */
3271   for (in_arg = 0; in_arg < nargs; ++in_arg)
3272     {
3273       tree arg = TREE_VEC_ELT (args, in_arg);
3274       if (arg == NULL_TREE)
3275         return args;
3276       if (ARGUMENT_PACK_P (arg))
3277         {
3278           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3279           if (num_result_args < 0)
3280             num_result_args = in_arg + num_packed;
3281           else
3282             num_result_args += num_packed;
3283         }
3284       else
3285         {
3286           if (num_result_args >= 0)
3287             num_result_args++;
3288         }
3289     }
3290
3291   /* If no expansion is necessary, we're done.  */
3292   if (num_result_args < 0)
3293     return args;
3294
3295   /* Expand arguments.  */
3296   result_args = make_tree_vec (num_result_args);
3297   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3298     non_default_args_count =
3299       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3300   for (in_arg = 0; in_arg < nargs; ++in_arg)
3301     {
3302       tree arg = TREE_VEC_ELT (args, in_arg);
3303       if (ARGUMENT_PACK_P (arg))
3304         {
3305           tree packed = ARGUMENT_PACK_ARGS (arg);
3306           int i, num_packed = TREE_VEC_LENGTH (packed);
3307           for (i = 0; i < num_packed; ++i, ++out_arg)
3308             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3309           if (non_default_args_count > 0)
3310             non_default_args_count += num_packed;
3311         }
3312       else
3313         {
3314           TREE_VEC_ELT (result_args, out_arg) = arg;
3315           ++out_arg;
3316         }
3317     }
3318   if (non_default_args_count >= 0)
3319     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3320   return result_args;
3321 }
3322
3323 /* Checks if DECL shadows a template parameter.
3324
3325    [temp.local]: A template-parameter shall not be redeclared within its
3326    scope (including nested scopes).
3327
3328    Emits an error and returns TRUE if the DECL shadows a parameter,
3329    returns FALSE otherwise.  */
3330
3331 bool
3332 check_template_shadow (tree decl)
3333 {
3334   tree olddecl;
3335
3336   /* If we're not in a template, we can't possibly shadow a template
3337      parameter.  */
3338   if (!current_template_parms)
3339     return true;
3340
3341   /* Figure out what we're shadowing.  */
3342   if (TREE_CODE (decl) == OVERLOAD)
3343     decl = OVL_CURRENT (decl);
3344   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3345
3346   /* If there's no previous binding for this name, we're not shadowing
3347      anything, let alone a template parameter.  */
3348   if (!olddecl)
3349     return true;
3350
3351   /* If we're not shadowing a template parameter, we're done.  Note
3352      that OLDDECL might be an OVERLOAD (or perhaps even an
3353      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3354      node.  */
3355   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3356     return true;
3357
3358   /* We check for decl != olddecl to avoid bogus errors for using a
3359      name inside a class.  We check TPFI to avoid duplicate errors for
3360      inline member templates.  */
3361   if (decl == olddecl
3362       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3363     return true;
3364
3365   error ("declaration of %q+#D", decl);
3366   error (" shadows template parm %q+#D", olddecl);
3367   return false;
3368 }
3369
3370 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3371    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3372    template parameters.  */
3373
3374 static tree
3375 build_template_parm_index (int index,
3376                            int level,
3377                            int orig_level,
3378                            int num_siblings,
3379                            tree decl,
3380                            tree type)
3381 {
3382   tree t = make_node (TEMPLATE_PARM_INDEX);
3383   TEMPLATE_PARM_IDX (t) = index;
3384   TEMPLATE_PARM_LEVEL (t) = level;
3385   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3386   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3387   TEMPLATE_PARM_DECL (t) = decl;
3388   TREE_TYPE (t) = type;
3389   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3390   TREE_READONLY (t) = TREE_READONLY (decl);
3391
3392   return t;
3393 }
3394
3395 /* Find the canonical type parameter for the given template type
3396    parameter.  Returns the canonical type parameter, which may be TYPE
3397    if no such parameter existed.  */
3398
3399 static tree
3400 canonical_type_parameter (tree type)
3401 {
3402   tree list;
3403   int idx = TEMPLATE_TYPE_IDX (type);
3404   if (!canonical_template_parms)
3405     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3406
3407   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3408     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3409
3410   list = VEC_index (tree, canonical_template_parms, idx);
3411   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3412     list = TREE_CHAIN (list);
3413
3414   if (list)
3415     return TREE_VALUE (list);
3416   else
3417     {
3418       VEC_replace(tree, canonical_template_parms, idx,
3419                   tree_cons (NULL_TREE, type, 
3420                              VEC_index (tree, canonical_template_parms, idx)));
3421       return type;
3422     }
3423 }
3424
3425 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3426    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3427    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3428    new one is created.  */
3429
3430 static tree
3431 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3432                             tsubst_flags_t complain)
3433 {
3434   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3435       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3436           != TEMPLATE_PARM_LEVEL (index) - levels)
3437       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3438     {
3439       tree orig_decl = TEMPLATE_PARM_DECL (index);
3440       tree decl, t;
3441
3442       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3443                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3444       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3445       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3446       DECL_ARTIFICIAL (decl) = 1;
3447       SET_DECL_TEMPLATE_PARM_P (decl);
3448
3449       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3450                                      TEMPLATE_PARM_LEVEL (index) - levels,
3451                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3452                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3453                                      decl, type);
3454       TEMPLATE_PARM_DESCENDANTS (index) = t;
3455       TEMPLATE_PARM_PARAMETER_PACK (t) 
3456         = TEMPLATE_PARM_PARAMETER_PACK (index);
3457
3458         /* Template template parameters need this.  */
3459       if (TREE_CODE (decl) == TEMPLATE_DECL)
3460         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3461           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3462            args, complain);
3463     }
3464
3465   return TEMPLATE_PARM_DESCENDANTS (index);
3466 }
3467
3468 /* Process information from new template parameter PARM and append it
3469    to the LIST being built.  This new parameter is a non-type
3470    parameter iff IS_NON_TYPE is true. This new parameter is a
3471    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3472    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3473    parameter list PARM belongs to. This is used used to create a
3474    proper canonical type for the type of PARM that is to be created,
3475    iff PARM is a type.  If the size is not known, this parameter shall
3476    be set to 0.  */
3477
3478 tree
3479 process_template_parm (tree list, location_t parm_loc, tree parm,
3480                        bool is_non_type, bool is_parameter_pack,
3481                        unsigned num_template_parms)
3482 {
3483   tree decl = 0;
3484   tree defval;
3485   tree err_parm_list;
3486   int idx = 0;
3487
3488   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3489   defval = TREE_PURPOSE (parm);
3490
3491   if (list)
3492     {
3493       tree p = tree_last (list);
3494
3495       if (p && TREE_VALUE (p) != error_mark_node)
3496         {
3497           p = TREE_VALUE (p);
3498           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3499             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3500           else
3501             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3502         }
3503
3504       ++idx;
3505     }
3506   else
3507     idx = 0;
3508
3509   if (is_non_type)
3510     {
3511       parm = TREE_VALUE (parm);
3512
3513       SET_DECL_TEMPLATE_PARM_P (parm);
3514
3515       if (TREE_TYPE (parm) == error_mark_node)
3516         {
3517           err_parm_list = build_tree_list (defval, parm);
3518           TREE_VALUE (err_parm_list) = error_mark_node;
3519            return chainon (list, err_parm_list);
3520         }
3521       else
3522       {
3523         /* [temp.param]
3524
3525            The top-level cv-qualifiers on the template-parameter are
3526            ignored when determining its type.  */
3527         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3528         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3529           {
3530             err_parm_list = build_tree_list (defval, parm);
3531             TREE_VALUE (err_parm_list) = error_mark_node;
3532              return chainon (list, err_parm_list);
3533           }
3534
3535         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3536           {
3537             /* This template parameter is not a parameter pack, but it
3538                should be. Complain about "bare" parameter packs.  */
3539             check_for_bare_parameter_packs (TREE_TYPE (parm));
3540             
3541             /* Recover by calling this a parameter pack.  */
3542             is_parameter_pack = true;
3543           }
3544       }
3545
3546       /* A template parameter is not modifiable.  */
3547       TREE_CONSTANT (parm) = 1;
3548       TREE_READONLY (parm) = 1;
3549       decl = build_decl (parm_loc,
3550                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3551       TREE_CONSTANT (decl) = 1;
3552       TREE_READONLY (decl) = 1;
3553       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3554         = build_template_parm_index (idx, processing_template_decl,
3555                                      processing_template_decl,
3556                                      num_template_parms,
3557                                      decl, TREE_TYPE (parm));
3558
3559       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3560         = is_parameter_pack;
3561     }
3562   else
3563     {
3564       tree t;
3565       parm = TREE_VALUE (TREE_VALUE (parm));
3566
3567       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3568         {
3569           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3570           /* This is for distinguishing between real templates and template
3571              template parameters */
3572           TREE_TYPE (parm) = t;
3573           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3574           decl = parm;
3575         }
3576       else
3577         {
3578           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3579           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3580           decl = build_decl (parm_loc,
3581                              TYPE_DECL, parm, t);
3582         }
3583
3584       TYPE_NAME (t) = decl;
3585       TYPE_STUB_DECL (t) = decl;
3586       parm = decl;
3587       TEMPLATE_TYPE_PARM_INDEX (t)
3588         = build_template_parm_index (idx, processing_template_decl,
3589                                      processing_template_decl,
3590                                      num_template_parms,
3591                                      decl, TREE_TYPE (parm));
3592       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3593       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3594     }
3595   DECL_ARTIFICIAL (decl) = 1;
3596   SET_DECL_TEMPLATE_PARM_P (decl);
3597   pushdecl (decl);
3598   parm = build_tree_list (defval, parm);
3599   return chainon (list, parm);
3600 }
3601
3602 /* The end of a template parameter list has been reached.  Process the
3603    tree list into a parameter vector, converting each parameter into a more
3604    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3605    as PARM_DECLs.  */
3606
3607 tree
3608 end_template_parm_list (tree parms)
3609 {
3610   int nparms;
3611   tree parm, next;
3612   tree saved_parmlist = make_tree_vec (list_length (parms));
3613
3614   current_template_parms
3615     = tree_cons (size_int (processing_template_decl),
3616                  saved_parmlist, current_template_parms);
3617
3618   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3619     {
3620       next = TREE_CHAIN (parm);
3621       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3622       TREE_CHAIN (parm) = NULL_TREE;
3623     }
3624
3625   --processing_template_parmlist;
3626
3627   return saved_parmlist;
3628 }
3629
3630 /* Create a new type almost identical to TYPE but which has the
3631    following differences:
3632
3633      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3634      template sibling parameters of T.
3635
3636      2/ T has a new canonical type that matches the new number
3637      of sibling parms.
3638
3639      3/ From now on, T is going to be what lookups referring to the
3640      name of TYPE will return. No lookup should return TYPE anymore.
3641
3642    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3643
3644    This is a subroutine of fixup_template_parms.  */
3645
3646 static tree
3647 fixup_template_type_parm_type (tree type, int num_parms)
3648 {
3649   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3650   tree t;
3651   /* This is the decl which name is inserted into the symbol table for
3652      the template parm type. So whenever we lookup the type name, this
3653      is the DECL we get.  */
3654   tree decl;
3655
3656   /* Do not fix up the type twice.  */
3657   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3658     return type;
3659
3660   t = copy_type (type);
3661   decl = TYPE_NAME (t);
3662
3663   TYPE_MAIN_VARIANT (t) = t;
3664   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3665   TYPE_POINTER_TO (t) = 0;
3666   TYPE_REFERENCE_TO (t) = 0;
3667
3668   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3669                                    TEMPLATE_PARM_LEVEL (orig_idx),
3670                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3671                                    num_parms,
3672                                    decl, t);
3673   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3674   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3675   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3676
3677   TYPE_STUB_DECL (t) = decl;
3678   TEMPLATE_TYPE_DECL (t) = decl;
3679   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3680     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3681
3682   /* Update the type associated to the type name stored in the symbol
3683      table. Now, whenever the type name is looked up, the resulting
3684      type is properly fixed up.  */
3685   TREE_TYPE (decl) = t;
3686
3687   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3688
3689   return t;
3690 }
3691
3692 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3693    identical to I, but that is fixed up as to:
3694
3695    1/ carry the number of sibling parms (NUM_PARMS) of the template
3696    parm represented by I.
3697
3698    2/ replace all references to template parm types declared before I
3699    (in the same template parm list as I) by references to template
3700    parm types contained in ARGS. ARGS should contain the list of
3701    template parms that have been fixed up so far, in a form suitable
3702    to be passed to tsubst.
3703
3704    This is a subroutine of fixup_template_parms.  */
3705
3706 static tree
3707 fixup_template_parm_index (tree i, tree args, int num_parms)
3708 {
3709   tree index, decl, type;
3710
3711   if (i == NULL_TREE
3712       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3713       /* Do not fix up the index twice.  */
3714       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3715     return i;
3716
3717   decl = TEMPLATE_PARM_DECL (i);
3718   type = TREE_TYPE (decl);
3719
3720   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3721                                      TEMPLATE_PARM_LEVEL (i),
3722                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3723                                      num_parms,
3724                                      decl, type);
3725
3726   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3727   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3728
3729   type = tsubst (type, args, tf_none, NULL_TREE);
3730   
3731   TREE_TYPE (decl) = type;
3732   TREE_TYPE (index) = type;
3733
3734   return index;
3735 }
3736
3737 /* 
3738    This is a subroutine of fixup_template_parms.
3739
3740    It computes the canonical type of the type of the template
3741    parameter PARM_DESC and update all references to that type so that
3742    they use the newly computed canonical type. No access check is
3743    performed during the fixup. PARM_DESC is a TREE_LIST which
3744    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3745    default argument of the template parm if any. IDX is the index of
3746    the template parameter, starting at 0. NUM_PARMS is the number of
3747    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3748    TREE_VEC containing the full set of template parameters in a form
3749    suitable to be passed to substs functions as their ARGS
3750    argument. This is what current_template_args returns for a given
3751    template. The innermost vector of args in ARGLIST is the set of
3752    template parms that have been fixed up so far. This function adds
3753    the fixed up parameter into that vector.  */
3754
3755 static void
3756 fixup_template_parm (tree parm_desc,
3757                      int idx,
3758                      int num_parms,
3759                      tree arglist)
3760 {
3761   tree parm = TREE_VALUE (parm_desc);
3762   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3763
3764   push_deferring_access_checks (dk_no_check);
3765
3766   if (TREE_CODE (parm) == TYPE_DECL)
3767     {
3768       /* PARM is a template type parameter. Fix up its type, add
3769          the fixed-up template parm to the vector of fixed-up
3770          template parms so far, and substitute the fixed-up
3771          template parms into the default argument of this
3772          parameter.  */
3773       tree t =
3774         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3775       TREE_TYPE (parm) = t;
3776
3777       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3778     }
3779   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3780     {
3781       /* PARM is a template template parameter. This is going to
3782          be interesting.  */
3783       tree tparms, targs, innermost_args, t;
3784       int j;
3785
3786       /* First, fix up the parms of the template template parm
3787          because the parms are involved in defining the new canonical
3788          type of the template template parm.  */
3789
3790       /* So we need to substitute the template parm types that have
3791          been fixed up so far into the template parms of this template
3792          template parm. E.g, consider this:
3793
3794          template<class T, template<T u> class TT> class S;
3795
3796          In this case we want to substitute T into the
3797          template parameters of TT.
3798
3799          So let's walk the template parms of PARM here, and
3800          tsubst ARGLIST into into each of the template
3801          parms.   */
3802
3803       /* For this substitution we need to build the full set of
3804          template parameters and use that as arguments for the
3805          tsubsting function.  */
3806       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3807
3808       /* This will contain the innermost parms of PARM into which
3809          we have substituted so far.  */
3810       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3811       targs = add_to_template_args (arglist, innermost_args);
3812       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3813         {
3814           tree parameter;
3815
3816           parameter = TREE_VEC_ELT (tparms, j);
3817
3818           /* INNERMOST_ARGS needs to have at least the same number
3819              of elements as the index PARAMETER, ortherwise
3820              tsubsting into PARAMETER will result in partially
3821              instantiating it, reducing its tempate parm
3822              level. Let's tactically fill INNERMOST_ARGS for that
3823              purpose.  */
3824           TREE_VEC_ELT (innermost_args, j) =
3825             template_parm_to_arg (parameter);
3826
3827           fixup_template_parm (parameter, j,
3828                                TREE_VEC_LENGTH (tparms),
3829                                targs);
3830         }
3831
3832       /* Now fix up the type of the template template parm.  */
3833
3834       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3835       TREE_TYPE (parm) = t;
3836
3837       TREE_VEC_ELT (fixedup_args, idx) =
3838         template_parm_to_arg (parm_desc);
3839     }
3840   else if (TREE_CODE (parm) == PARM_DECL)
3841     {
3842       /* PARM is a non-type template parameter. We need to:
3843
3844        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3845        proper number of sibling parameters.
3846
3847        * Make lookups of the template parameter return a reference
3848        to the fixed-up index. No lookup should return references
3849        to the former index anymore.
3850
3851        * Substitute the template parms that got fixed up so far
3852
3853        * into the type of PARM.  */
3854
3855       tree index = DECL_INITIAL (parm);
3856
3857       /* PUSHED_DECL is the decl added to the symbol table with
3858          the name of the parameter. E,g:
3859              
3860          template<class T, T u> //#0
3861          auto my_function(T t) -> decltype(u); //#1
3862
3863          Here, when looking up u at //#1, we get the decl of u
3864          resulting from the declaration in #0. This is what
3865          PUSHED_DECL is. We need to replace the reference to the
3866          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3867          fixed-up TEMPLATE_PARM_INDEX.  */
3868       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3869
3870       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3871          fixup the type of PUSHED_DECL as well and luckily
3872          fixup_template_parm_index does it for us too.  */
3873       tree fixed_up_index =
3874         fixup_template_parm_index (index, arglist, num_parms);
3875
3876       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3877
3878       /* Add this fixed up PARM to the template parms we've fixed
3879          up so far and use that to substitute the fixed-up
3880          template parms into the type of PARM.  */
3881       TREE_VEC_ELT (fixedup_args, idx) =
3882         template_parm_to_arg (parm_desc);
3883       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3884                                  tf_none, NULL_TREE);
3885     }
3886
3887   TREE_PURPOSE (parm_desc) =
3888     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3889                          arglist, tf_none, parm);
3890
3891   pop_deferring_access_checks ();
3892 }
3893
3894 /* Walk the current template parms and properly compute the canonical
3895    types of the dependent types created during
3896    cp_parser_template_parameter_list.  */
3897
3898 void
3899 fixup_template_parms (void)
3900 {
3901   tree arglist;
3902   tree parameter_vec;
3903   tree fixedup_args;
3904   int i, num_parms;
3905
3906   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3907   if (parameter_vec == NULL_TREE)
3908     return;
3909
3910   num_parms = TREE_VEC_LENGTH (parameter_vec);
3911
3912   /* This vector contains the current innermost template parms that
3913      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3914      to be passed to tsubst* functions as their ARGS argument.  */
3915   fixedup_args = make_tree_vec (num_parms);
3916
3917   /* This vector contains the full set of template parms in a form
3918      suitable to be passed to substs functions as their ARGS
3919      argument.  */
3920   arglist = current_template_args ();
3921   arglist = add_outermost_template_args (arglist, fixedup_args);
3922
3923   /* Let's do the proper fixup now.  */
3924   for (i = 0; i < num_parms; ++i)
3925     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3926                          i, num_parms, arglist);
3927 }
3928
3929 /* end_template_decl is called after a template declaration is seen.  */
3930
3931 void
3932 end_template_decl (void)
3933 {
3934   reset_specialization ();
3935
3936   if (! processing_template_decl)
3937     return;
3938
3939   /* This matches the pushlevel in begin_template_parm_list.  */
3940   finish_scope ();
3941
3942   --processing_template_decl;
3943   current_template_parms = TREE_CHAIN (current_template_parms);
3944 }
3945
3946 /* Takes a TREE_LIST representing a template parameter and convert it
3947    into an argument suitable to be passed to the type substitution
3948    functions.  Note that If the TREE_LIST contains an error_mark
3949    node, the returned argument is error_mark_node.  */
3950
3951 static tree
3952 template_parm_to_arg (tree t)
3953 {
3954
3955   if (t == NULL_TREE
3956       || TREE_CODE (t) != TREE_LIST)
3957     return t;
3958
3959   if (error_operand_p (TREE_VALUE (t)))
3960     return error_mark_node;
3961
3962   t = TREE_VALUE (t);
3963
3964   if (TREE_CODE (t) == TYPE_DECL
3965       || TREE_CODE (t) == TEMPLATE_DECL)
3966     {
3967       t = TREE_TYPE (t);
3968
3969       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3970         {
3971           /* Turn this argument into a TYPE_ARGUMENT_PACK
3972              with a single element, which expands T.  */
3973           tree vec = make_tree_vec (1);
3974 #ifdef ENABLE_CHECKING
3975           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3976             (vec, TREE_VEC_LENGTH (vec));
3977 #endif
3978           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3979
3980           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3981           SET_ARGUMENT_PACK_ARGS (t, vec);
3982         }
3983     }
3984   else
3985     {
3986       t = DECL_INITIAL (t);
3987
3988       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3989         {
3990           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3991              with a single element, which expands T.  */
3992           tree vec = make_tree_vec (1);
3993           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3994 #ifdef ENABLE_CHECKING
3995           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3996             (vec, TREE_VEC_LENGTH (vec));
3997 #endif
3998           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3999
4000           t  = make_node (NONTYPE_ARGUMENT_PACK);
4001           SET_ARGUMENT_PACK_ARGS (t, vec);
4002           TREE_TYPE (t) = type;
4003         }
4004     }
4005   return t;
4006 }
4007
4008 /* Within the declaration of a template, return all levels of template
4009    parameters that apply.  The template parameters are represented as
4010    a TREE_VEC, in the form documented in cp-tree.h for template
4011    arguments.  */
4012
4013 static tree
4014 current_template_args (void)
4015 {
4016   tree header;
4017   tree args = NULL_TREE;
4018   int length = TMPL_PARMS_DEPTH (current_template_parms);
4019   int l = length;
4020
4021   /* If there is only one level of template parameters, we do not
4022      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4023      TREE_VEC containing the arguments.  */
4024   if (length > 1)
4025     args = make_tree_vec (length);
4026
4027   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4028     {
4029       tree a = copy_node (TREE_VALUE (header));
4030       int i;
4031
4032       TREE_TYPE (a) = NULL_TREE;
4033       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4034         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4035
4036 #ifdef ENABLE_CHECKING
4037       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4038 #endif
4039
4040       if (length > 1)
4041         TREE_VEC_ELT (args, --l) = a;
4042       else
4043         args = a;
4044     }
4045
4046     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4047       /* This can happen for template parms of a template template
4048          parameter, e.g:
4049
4050          template<template<class T, class U> class TT> struct S;
4051
4052          Consider the level of the parms of TT; T and U both have
4053          level 2; TT has no template parm of level 1. So in this case
4054          the first element of full_template_args is NULL_TREE. If we
4055          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4056          of 2. This will make tsubst wrongly consider that T and U
4057          have level 1. Instead, let's create a dummy vector as the
4058          first element of full_template_args so that TMPL_ARG_DEPTH
4059          returns the correct depth for args.  */
4060       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4061   return args;
4062 }
4063
4064 /* Update the declared TYPE by doing any lookups which were thought to be
4065    dependent, but are not now that we know the SCOPE of the declarator.  */
4066
4067 tree
4068 maybe_update_decl_type (tree orig_type, tree scope)
4069 {
4070   tree type = orig_type;
4071
4072   if (type == NULL_TREE)
4073     return type;
4074
4075   if (TREE_CODE (orig_type) == TYPE_DECL)
4076     type = TREE_TYPE (type);
4077
4078   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4079       && dependent_type_p (type)
4080       /* Don't bother building up the args in this case.  */
4081       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4082     {
4083       /* tsubst in the args corresponding to the template parameters,
4084          including auto if present.  Most things will be unchanged, but
4085          make_typename_type and tsubst_qualified_id will resolve
4086          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4087       tree args = current_template_args ();
4088       tree auto_node = type_uses_auto (type);
4089       tree pushed;
4090       if (auto_node)
4091         {
4092           tree auto_vec = make_tree_vec (1);
4093           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4094           args = add_to_template_args (args, auto_vec);
4095         }
4096       pushed = push_scope (scope);
4097       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4098       if (pushed)
4099         pop_scope (scope);
4100     }
4101
4102   if (type == error_mark_node)
4103     return orig_type;
4104
4105   if (TREE_CODE (orig_type) == TYPE_DECL)
4106     {
4107       if (same_type_p (type, TREE_TYPE (orig_type)))
4108         type = orig_type;
4109       else
4110         type = TYPE_NAME (type);
4111     }
4112   return type;
4113 }
4114
4115 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4116    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4117    a member template.  Used by push_template_decl below.  */
4118
4119 static tree
4120 build_template_decl (tree decl, tree parms, bool member_template_p)
4121 {
4122   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4123   DECL_TEMPLATE_PARMS (tmpl) = parms;
4124   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4125   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4126   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4127
4128   return tmpl;
4129 }
4130
4131 struct template_parm_data
4132 {
4133   /* The level of the template parameters we are currently
4134      processing.  */
4135   int level;
4136
4137   /* The index of the specialization argument we are currently
4138      processing.  */
4139   int current_arg;
4140
4141   /* An array whose size is the number of template parameters.  The
4142      elements are nonzero if the parameter has been used in any one
4143      of the arguments processed so far.  */
4144   int* parms;
4145
4146   /* An array whose size is the number of template arguments.  The
4147      elements are nonzero if the argument makes use of template
4148      parameters of this level.  */
4149   int* arg_uses_template_parms;
4150 };
4151
4152 /* Subroutine of push_template_decl used to see if each template
4153    parameter in a partial specialization is used in the explicit
4154    argument list.  If T is of the LEVEL given in DATA (which is
4155    treated as a template_parm_data*), then DATA->PARMS is marked
4156    appropriately.  */
4157
4158 static int
4159 mark_template_parm (tree t, void* data)
4160 {
4161   int level;
4162   int idx;
4163   struct template_parm_data* tpd = (struct template_parm_data*) data;
4164
4165   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4166     {
4167       level = TEMPLATE_PARM_LEVEL (t);
4168       idx = TEMPLATE_PARM_IDX (t);
4169     }
4170   else
4171     {
4172       level = TEMPLATE_TYPE_LEVEL (t);
4173       idx = TEMPLATE_TYPE_IDX (t);
4174     }
4175
4176   if (level == tpd->level)
4177     {
4178       tpd->parms[idx] = 1;
4179       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4180     }
4181
4182   /* Return zero so that for_each_template_parm will continue the
4183      traversal of the tree; we want to mark *every* template parm.  */
4184   return 0;
4185 }
4186
4187 /* Process the partial specialization DECL.  */
4188
4189 static tree
4190 process_partial_specialization (tree decl)
4191 {
4192   tree type = TREE_TYPE (decl);
4193   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4194   tree specargs = CLASSTYPE_TI_ARGS (type);
4195   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4196   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4197   tree inner_parms;
4198   tree inst;
4199   int nargs = TREE_VEC_LENGTH (inner_args);
4200   int ntparms;
4201   int  i;
4202   bool did_error_intro = false;
4203   struct template_parm_data tpd;
4204   struct template_parm_data tpd2;
4205
4206   gcc_assert (current_template_parms);
4207
4208   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4209   ntparms = TREE_VEC_LENGTH (inner_parms);
4210
4211   /* We check that each of the template parameters given in the
4212      partial specialization is used in the argument list to the
4213      specialization.  For example:
4214
4215        template <class T> struct S;
4216        template <class T> struct S<T*>;
4217
4218      The second declaration is OK because `T*' uses the template
4219      parameter T, whereas
4220
4221        template <class T> struct S<int>;
4222
4223      is no good.  Even trickier is:
4224
4225        template <class T>
4226        struct S1
4227        {
4228           template <class U>
4229           struct S2;
4230           template <class U>
4231           struct S2<T>;
4232        };
4233
4234      The S2<T> declaration is actually invalid; it is a
4235      full-specialization.  Of course,
4236
4237           template <class U>
4238           struct S2<T (*)(U)>;
4239
4240      or some such would have been OK.  */
4241   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4242   tpd.parms = XALLOCAVEC (int, ntparms);
4243   memset (tpd.parms, 0, sizeof (int) * ntparms);
4244
4245   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4246   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4247   for (i = 0; i < nargs; ++i)
4248     {
4249       tpd.current_arg = i;
4250       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4251                               &mark_template_parm,
4252                               &tpd,
4253                               NULL,
4254                               /*include_nondeduced_p=*/false);
4255     }
4256   for (i = 0; i < ntparms; ++i)
4257     if (tpd.parms[i] == 0)
4258       {
4259         /* One of the template parms was not used in the
4260            specialization.  */
4261         if (!did_error_intro)
4262           {
4263             error ("template parameters not used in partial specialization:");
4264             did_error_intro = true;
4265           }
4266
4267         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4268       }
4269
4270   if (did_error_intro)
4271     return error_mark_node;
4272
4273   /* [temp.class.spec]
4274
4275      The argument list of the specialization shall not be identical to
4276      the implicit argument list of the primary template.  */
4277   if (comp_template_args
4278       (inner_args,
4279        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4280                                                    (maintmpl)))))
4281     error ("partial specialization %qT does not specialize any template arguments", type);
4282
4283   /* [temp.class.spec]
4284
4285      A partially specialized non-type argument expression shall not
4286      involve template parameters of the partial specialization except
4287      when the argument expression is a simple identifier.
4288
4289      The type of a template parameter corresponding to a specialized
4290      non-type argument shall not be dependent on a parameter of the
4291      specialization. 
4292
4293      Also, we verify that pack expansions only occur at the
4294      end of the argument list.  */
4295   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4296   tpd2.parms = 0;
4297   for (i = 0; i < nargs; ++i)
4298     {
4299       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4300       tree arg = TREE_VEC_ELT (inner_args, i);
4301       tree packed_args = NULL_TREE;
4302       int j, len = 1;
4303
4304       if (ARGUMENT_PACK_P (arg))
4305         {
4306           /* Extract the arguments from the argument pack. We'll be
4307              iterating over these in the following loop.  */
4308           packed_args = ARGUMENT_PACK_ARGS (arg);
4309           len = TREE_VEC_LENGTH (packed_args);
4310         }
4311
4312       for (j = 0; j < len; j++)
4313         {
4314           if (packed_args)
4315             /* Get the Jth argument in the parameter pack.  */
4316             arg = TREE_VEC_ELT (packed_args, j);
4317
4318           if (PACK_EXPANSION_P (arg))
4319             {
4320               /* Pack expansions must come at the end of the
4321                  argument list.  */
4322               if ((packed_args && j < len - 1)
4323                   || (!packed_args && i < nargs - 1))
4324                 {
4325                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4326                     error ("parameter pack argument %qE must be at the "
4327                            "end of the template argument list", arg);
4328                   else
4329                     error ("parameter pack argument %qT must be at the "
4330                            "end of the template argument list", arg);
4331                 }
4332             }
4333
4334           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4335             /* We only care about the pattern.  */
4336             arg = PACK_EXPANSION_PATTERN (arg);
4337
4338           if (/* These first two lines are the `non-type' bit.  */
4339               !TYPE_P (arg)
4340               && TREE_CODE (arg) != TEMPLATE_DECL
4341               /* This next line is the `argument expression is not just a
4342                  simple identifier' condition and also the `specialized
4343                  non-type argument' bit.  */
4344               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4345             {
4346               if ((!packed_args && tpd.arg_uses_template_parms[i])
4347                   || (packed_args && uses_template_parms (arg)))
4348                 error ("template argument %qE involves template parameter(s)",
4349                        arg);
4350               else 
4351                 {
4352                   /* Look at the corresponding template parameter,
4353                      marking which template parameters its type depends
4354                      upon.  */
4355                   tree type = TREE_TYPE (parm);
4356
4357                   if (!tpd2.parms)
4358                     {
4359                       /* We haven't yet initialized TPD2.  Do so now.  */
4360                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4361                       /* The number of parameters here is the number in the
4362                          main template, which, as checked in the assertion
4363                          above, is NARGS.  */
4364                       tpd2.parms = XALLOCAVEC (int, nargs);
4365                       tpd2.level = 
4366                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4367                     }
4368
4369                   /* Mark the template parameters.  But this time, we're
4370                      looking for the template parameters of the main
4371                      template, not in the specialization.  */
4372                   tpd2.current_arg = i;
4373                   tpd2.arg_uses_template_parms[i] = 0;
4374                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4375                   for_each_template_parm (type,
4376                                           &mark_template_parm,
4377                                           &tpd2,
4378                                           NULL,
4379                                           /*include_nondeduced_p=*/false);
4380
4381                   if (tpd2.arg_uses_template_parms [i])
4382                     {
4383                       /* The type depended on some template parameters.
4384                          If they are fully specialized in the
4385                          specialization, that's OK.  */
4386                       int j;
4387                       int count = 0;
4388                       for (j = 0; j < nargs; ++j)
4389                         if (tpd2.parms[j] != 0
4390                             && tpd.arg_uses_template_parms [j])
4391                           ++count;
4392                       if (count != 0)
4393                         error_n (input_location, count,
4394                                  "type %qT of template argument %qE depends "
4395                                  "on a template parameter",
4396                                  "type %qT of template argument %qE depends "
4397                                  "on template parameters",
4398                                  type,
4399                                  arg);
4400                     }
4401                 }
4402             }
4403         }
4404     }
4405
4406   /* We should only get here once.  */
4407   gcc_assert (!COMPLETE_TYPE_P (type));
4408
4409   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4410     = tree_cons (specargs, inner_parms,
4411                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4412   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4413
4414   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4415        inst = TREE_CHAIN (inst))
4416     {
4417       tree inst_type = TREE_VALUE (inst);
4418       if (COMPLETE_TYPE_P (inst_type)
4419           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4420         {
4421           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4422           if (spec && TREE_TYPE (spec) == type)
4423             permerror (input_location,
4424                        "partial specialization of %qT after instantiation "
4425                        "of %qT", type, inst_type);
4426         }
4427     }
4428
4429   return decl;
4430 }
4431
4432 /* Check that a template declaration's use of default arguments and
4433    parameter packs is not invalid.  Here, PARMS are the template
4434    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4435    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4436    specialization.
4437    
4438
4439    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4440    declaration (but not a definition); 1 indicates a declaration, 2
4441    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4442    emitted for extraneous default arguments.
4443
4444    Returns TRUE if there were no errors found, FALSE otherwise. */
4445
4446 bool
4447 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4448                          int is_partial, int is_friend_decl)
4449 {
4450   const char *msg;
4451   int last_level_to_check;
4452   tree parm_level;
4453   bool no_errors = true;
4454
4455   /* [temp.param]
4456
4457      A default template-argument shall not be specified in a
4458      function template declaration or a function template definition, nor
4459      in the template-parameter-list of the definition of a member of a
4460      class template.  */
4461
4462   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4463     /* You can't have a function template declaration in a local
4464        scope, nor you can you define a member of a class template in a
4465        local scope.  */
4466     return true;
4467
4468   if (current_class_type
4469       && !TYPE_BEING_DEFINED (current_class_type)
4470       && DECL_LANG_SPECIFIC (decl)
4471       && DECL_DECLARES_FUNCTION_P (decl)
4472       /* If this is either a friend defined in the scope of the class
4473          or a member function.  */
4474       && (DECL_FUNCTION_MEMBER_P (decl)
4475           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4476           : DECL_FRIEND_CONTEXT (decl)
4477           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4478           : false)
4479       /* And, if it was a member function, it really was defined in
4480          the scope of the class.  */
4481       && (!DECL_FUNCTION_MEMBER_P (decl)
4482           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4483     /* We already checked these parameters when the template was
4484        declared, so there's no need to do it again now.  This function
4485        was defined in class scope, but we're processing it's body now
4486        that the class is complete.  */
4487     return true;
4488
4489   /* Core issue 226 (C++0x only): the following only applies to class
4490      templates.  */
4491   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4492     {
4493       /* [temp.param]
4494
4495          If a template-parameter has a default template-argument, all
4496          subsequent template-parameters shall have a default
4497          template-argument supplied.  */
4498       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4499         {
4500           tree inner_parms = TREE_VALUE (parm_level);
4501           int ntparms = TREE_VEC_LENGTH (inner_parms);
4502           int seen_def_arg_p = 0;
4503           int i;
4504
4505           for (i = 0; i < ntparms; ++i)
4506             {
4507               tree parm = TREE_VEC_ELT (inner_parms, i);
4508
4509               if (parm == error_mark_node)
4510                 continue;
4511
4512               if (TREE_PURPOSE (parm))
4513                 seen_def_arg_p = 1;
4514               else if (seen_def_arg_p
4515                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4516                 {
4517                   error ("no default argument for %qD", TREE_VALUE (parm));
4518                   /* For better subsequent error-recovery, we indicate that
4519                      there should have been a default argument.  */
4520                   TREE_PURPOSE (parm) = error_mark_node;
4521                   no_errors = false;
4522                 }
4523               else if (is_primary
4524                        && !is_partial
4525                        && !is_friend_decl
4526                        /* Don't complain about an enclosing partial
4527                           specialization.  */
4528                        && parm_level == parms
4529                        && TREE_CODE (decl) == TYPE_DECL
4530                        && i < ntparms - 1
4531                        && template_parameter_pack_p (TREE_VALUE (parm)))
4532                 {
4533                   /* A primary class template can only have one
4534                      parameter pack, at the end of the template
4535                      parameter list.  */
4536
4537                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4538                     error ("parameter pack %qE must be at the end of the"
4539                            " template parameter list", TREE_VALUE (parm));
4540                   else
4541                     error ("parameter pack %qT must be at the end of the"
4542                            " template parameter list", 
4543                            TREE_TYPE (TREE_VALUE (parm)));
4544
4545                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4546                     = error_mark_node;
4547                   no_errors = false;
4548                 }
4549             }
4550         }
4551     }
4552
4553   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4554       || is_partial 
4555       || !is_primary
4556       || is_friend_decl)
4557     /* For an ordinary class template, default template arguments are
4558        allowed at the innermost level, e.g.:
4559          template <class T = int>
4560          struct S {};
4561        but, in a partial specialization, they're not allowed even
4562        there, as we have in [temp.class.spec]:
4563
4564          The template parameter list of a specialization shall not
4565          contain default template argument values.
4566
4567        So, for a partial specialization, or for a function template
4568        (in C++98/C++03), we look at all of them.  */
4569     ;
4570   else
4571     /* But, for a primary class template that is not a partial
4572        specialization we look at all template parameters except the
4573        innermost ones.  */
4574     parms = TREE_CHAIN (parms);
4575
4576   /* Figure out what error message to issue.  */
4577   if (is_friend_decl == 2)
4578     msg = G_("default template arguments may not be used in function template "
4579              "friend re-declaration");
4580   else if (is_friend_decl)
4581     msg = G_("default template arguments may not be used in function template "
4582              "friend declarations");
4583   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4584     msg = G_("default template arguments may not be used in function templates "
4585              "without -std=c++0x or -std=gnu++0x");
4586   else if (is_partial)
4587     msg = G_("default template arguments may not be used in "
4588              "partial specializations");
4589   else
4590     msg = G_("default argument for template parameter for class enclosing %qD");
4591
4592   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4593     /* If we're inside a class definition, there's no need to
4594        examine the parameters to the class itself.  On the one
4595        hand, they will be checked when the class is defined, and,
4596        on the other, default arguments are valid in things like:
4597          template <class T = double>
4598          struct S { template <class U> void f(U); };
4599        Here the default argument for `S' has no bearing on the
4600        declaration of `f'.  */
4601     last_level_to_check = template_class_depth (current_class_type) + 1;
4602   else
4603     /* Check everything.  */
4604     last_level_to_check = 0;
4605
4606   for (parm_level = parms;
4607        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4608        parm_level = TREE_CHAIN (parm_level))
4609     {
4610       tree inner_parms = TREE_VALUE (parm_level);
4611       int i;
4612       int ntparms;
4613
4614       ntparms = TREE_VEC_LENGTH (inner_parms);
4615       for (i = 0; i < ntparms; ++i)
4616         {
4617           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4618             continue;
4619
4620           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4621             {
4622               if (msg)
4623                 {
4624                   no_errors = false;
4625                   if (is_friend_decl == 2)
4626                     return no_errors;
4627
4628                   error (msg, decl);
4629                   msg = 0;
4630                 }
4631
4632               /* Clear out the default argument so that we are not
4633                  confused later.  */
4634               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4635             }
4636         }
4637
4638       /* At this point, if we're still interested in issuing messages,
4639          they must apply to classes surrounding the object declared.  */
4640       if (msg)
4641         msg = G_("default argument for template parameter for class "
4642                  "enclosing %qD");
4643     }
4644
4645   return no_errors;
4646 }
4647
4648 /* Worker for push_template_decl_real, called via
4649    for_each_template_parm.  DATA is really an int, indicating the
4650    level of the parameters we are interested in.  If T is a template
4651    parameter of that level, return nonzero.  */
4652
4653 static int
4654 template_parm_this_level_p (tree t, void* data)
4655 {
4656   int this_level = *(int *)data;
4657   int level;
4658
4659   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4660     level = TEMPLATE_PARM_LEVEL (t);
4661   else
4662     level = TEMPLATE_TYPE_LEVEL (t);
4663   return level == this_level;
4664 }
4665
4666 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4667    parameters given by current_template_args, or reuses a
4668    previously existing one, if appropriate.  Returns the DECL, or an
4669    equivalent one, if it is replaced via a call to duplicate_decls.
4670
4671    If IS_FRIEND is true, DECL is a friend declaration.  */
4672
4673 tree
4674 push_template_decl_real (tree decl, bool is_friend)
4675 {
4676   tree tmpl;
4677   tree args;
4678   tree info;
4679   tree ctx;
4680   int primary;
4681   int is_partial;
4682   int new_template_p = 0;
4683   /* True if the template is a member template, in the sense of
4684      [temp.mem].  */
4685   bool member_template_p = false;
4686
4687   if (decl == error_mark_node || !current_template_parms)
4688     return error_mark_node;
4689
4690   /* See if this is a partial specialization.  */
4691   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4692                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4693                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4694
4695   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4696     is_friend = true;
4697
4698   if (is_friend)
4699     /* For a friend, we want the context of the friend function, not
4700        the type of which it is a friend.  */
4701     ctx = CP_DECL_CONTEXT (decl);
4702   else if (CP_DECL_CONTEXT (decl)
4703            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4704     /* In the case of a virtual function, we want the class in which
4705        it is defined.  */
4706     ctx = CP_DECL_CONTEXT (decl);
4707   else
4708     /* Otherwise, if we're currently defining some class, the DECL
4709        is assumed to be a member of the class.  */
4710     ctx = current_scope ();
4711
4712   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4713     ctx = NULL_TREE;
4714
4715   if (!DECL_CONTEXT (decl))
4716     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4717
4718   /* See if this is a primary template.  */
4719   if (is_friend && ctx)
4720     /* A friend template that specifies a class context, i.e.
4721          template <typename T> friend void A<T>::f();
4722        is not primary.  */
4723     primary = 0;
4724   else
4725     primary = template_parm_scope_p ();
4726
4727   if (primary)
4728     {
4729       if (DECL_CLASS_SCOPE_P (decl))
4730         member_template_p = true;
4731       if (TREE_CODE (decl) == TYPE_DECL
4732           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4733         {
4734           error ("template class without a name");
4735           return error_mark_node;
4736         }
4737       else if (TREE_CODE (decl) == FUNCTION_DECL)
4738         {
4739           if (DECL_DESTRUCTOR_P (decl))
4740             {
4741               /* [temp.mem]
4742
4743                  A destructor shall not be a member template.  */
4744               error ("destructor %qD declared as member template", decl);
4745               return error_mark_node;
4746             }
4747           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4748               && (!prototype_p (TREE_TYPE (decl))
4749                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4750                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4751                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4752                       == void_list_node)))
4753             {
4754               /* [basic.stc.dynamic.allocation]
4755
4756                  An allocation function can be a function
4757                  template. ... Template allocation functions shall
4758                  have two or more parameters.  */
4759               error ("invalid template declaration of %qD", decl);
4760               return error_mark_node;
4761             }
4762         }
4763       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4764                && CLASS_TYPE_P (TREE_TYPE (decl)))
4765         /* OK */;
4766       else
4767         {
4768           error ("template declaration of %q#D", decl);
4769           return error_mark_node;
4770         }
4771     }
4772
4773   /* Check to see that the rules regarding the use of default
4774      arguments are not being violated.  */
4775   check_default_tmpl_args (decl, current_template_parms,
4776                            primary, is_partial, /*is_friend_decl=*/0);
4777
4778   /* Ensure that there are no parameter packs in the type of this
4779      declaration that have not been expanded.  */
4780   if (TREE_CODE (decl) == FUNCTION_DECL)
4781     {
4782       /* Check each of the arguments individually to see if there are
4783          any bare parameter packs.  */
4784       tree type = TREE_TYPE (decl);
4785       tree arg = DECL_ARGUMENTS (decl);
4786       tree argtype = TYPE_ARG_TYPES (type);
4787
4788       while (arg && argtype)
4789         {
4790           if (!FUNCTION_PARAMETER_PACK_P (arg)
4791               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4792             {
4793             /* This is a PARM_DECL that contains unexpanded parameter
4794                packs. We have already complained about this in the
4795                check_for_bare_parameter_packs call, so just replace
4796                these types with ERROR_MARK_NODE.  */
4797               TREE_TYPE (arg) = error_mark_node;
4798               TREE_VALUE (argtype) = error_mark_node;
4799             }
4800
4801           arg = DECL_CHAIN (arg);
4802           argtype = TREE_CHAIN (argtype);
4803         }
4804
4805       /* Check for bare parameter packs in the return type and the
4806          exception specifiers.  */
4807       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4808         /* Errors were already issued, set return type to int
4809            as the frontend doesn't expect error_mark_node as
4810            the return type.  */
4811         TREE_TYPE (type) = integer_type_node;
4812       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4813         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4814     }
4815   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4816     {
4817       TREE_TYPE (decl) = error_mark_node;
4818       return error_mark_node;
4819     }
4820
4821   if (is_partial)
4822     return process_partial_specialization (decl);
4823
4824   args = current_template_args ();
4825
4826   if (!ctx
4827       || TREE_CODE (ctx) == FUNCTION_DECL
4828       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4829       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4830     {
4831       if (DECL_LANG_SPECIFIC (decl)
4832           && DECL_TEMPLATE_INFO (decl)
4833           && DECL_TI_TEMPLATE (decl))
4834         tmpl = DECL_TI_TEMPLATE (decl);
4835       /* If DECL is a TYPE_DECL for a class-template, then there won't
4836          be DECL_LANG_SPECIFIC.  The information equivalent to
4837          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4838       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4839                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4840                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4841         {
4842           /* Since a template declaration already existed for this
4843              class-type, we must be redeclaring it here.  Make sure
4844              that the redeclaration is valid.  */
4845           redeclare_class_template (TREE_TYPE (decl),
4846                                     current_template_parms);
4847           /* We don't need to create a new TEMPLATE_DECL; just use the
4848              one we already had.  */
4849           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4850         }
4851       else
4852         {
4853           tmpl = build_template_decl (decl, current_template_parms,
4854                                       member_template_p);
4855           new_template_p = 1;
4856
4857           if (DECL_LANG_SPECIFIC (decl)
4858               && DECL_TEMPLATE_SPECIALIZATION (decl))
4859             {
4860               /* A specialization of a member template of a template
4861                  class.  */
4862               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4863               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4864               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4865             }
4866         }
4867     }
4868   else
4869     {
4870       tree a, t, current, parms;
4871       int i;
4872       tree tinfo = get_template_info (decl);
4873
4874       if (!tinfo)
4875         {
4876           error ("template definition of non-template %q#D", decl);
4877           return error_mark_node;
4878         }
4879
4880       tmpl = TI_TEMPLATE (tinfo);
4881
4882       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4883           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4884           && DECL_TEMPLATE_SPECIALIZATION (decl)
4885           && DECL_MEMBER_TEMPLATE_P (tmpl))
4886         {
4887           tree new_tmpl;
4888
4889           /* The declaration is a specialization of a member
4890              template, declared outside the class.  Therefore, the
4891              innermost template arguments will be NULL, so we
4892              replace them with the arguments determined by the
4893              earlier call to check_explicit_specialization.  */
4894           args = DECL_TI_ARGS (decl);
4895
4896           new_tmpl
4897             = build_template_decl (decl, current_template_parms,
4898                                    member_template_p);
4899           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4900           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4901           DECL_TI_TEMPLATE (decl) = new_tmpl;
4902           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4903           DECL_TEMPLATE_INFO (new_tmpl)
4904             = build_template_info (tmpl, args);
4905
4906           register_specialization (new_tmpl,
4907                                    most_general_template (tmpl),
4908                                    args,
4909                                    is_friend, 0);
4910           return decl;
4911         }
4912
4913       /* Make sure the template headers we got make sense.  */
4914
4915       parms = DECL_TEMPLATE_PARMS (tmpl);
4916       i = TMPL_PARMS_DEPTH (parms);
4917       if (TMPL_ARGS_DEPTH (args) != i)
4918         {
4919           error ("expected %d levels of template parms for %q#D, got %d",
4920                  i, decl, TMPL_ARGS_DEPTH (args));
4921         }
4922       else
4923         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4924           {
4925             a = TMPL_ARGS_LEVEL (args, i);
4926             t = INNERMOST_TEMPLATE_PARMS (parms);
4927
4928             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4929               {
4930                 if (current == decl)
4931                   error ("got %d template parameters for %q#D",
4932                          TREE_VEC_LENGTH (a), decl);
4933                 else
4934                   error ("got %d template parameters for %q#T",
4935                          TREE_VEC_LENGTH (a), current);
4936                 error ("  but %d required", TREE_VEC_LENGTH (t));
4937                 return error_mark_node;
4938               }
4939
4940             if (current == decl)
4941               current = ctx;
4942             else if (current == NULL_TREE)
4943               /* Can happen in erroneous input.  */
4944               break;
4945             else
4946               current = (TYPE_P (current)
4947                          ? TYPE_CONTEXT (current)
4948                          : DECL_CONTEXT (current));
4949           }
4950
4951       /* Check that the parms are used in the appropriate qualifying scopes
4952          in the declarator.  */
4953       if (!comp_template_args
4954           (TI_ARGS (tinfo),
4955            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4956         {
4957           error ("\
4958 template arguments to %qD do not match original template %qD",
4959                  decl, DECL_TEMPLATE_RESULT (tmpl));
4960           if (!uses_template_parms (TI_ARGS (tinfo)))
4961             inform (input_location, "use template<> for an explicit specialization");
4962           /* Avoid crash in import_export_decl.  */
4963           DECL_INTERFACE_KNOWN (decl) = 1;
4964           return error_mark_node;
4965         }
4966     }
4967
4968   DECL_TEMPLATE_RESULT (tmpl) = decl;
4969   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4970
4971   /* Push template declarations for global functions and types.  Note
4972      that we do not try to push a global template friend declared in a
4973      template class; such a thing may well depend on the template
4974      parameters of the class.  */
4975   if (new_template_p && !ctx
4976       && !(is_friend && template_class_depth (current_class_type) > 0))
4977     {
4978       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4979       if (tmpl == error_mark_node)
4980         return error_mark_node;
4981
4982       /* Hide template friend classes that haven't been declared yet.  */
4983       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4984         {
4985           DECL_ANTICIPATED (tmpl) = 1;
4986           DECL_FRIEND_P (tmpl) = 1;
4987         }
4988     }
4989
4990   if (primary)
4991     {
4992       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4993       int i;
4994
4995       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4996       if (DECL_CONV_FN_P (tmpl))
4997         {
4998           int depth = TMPL_PARMS_DEPTH (parms);
4999
5000           /* It is a conversion operator. See if the type converted to
5001              depends on innermost template operands.  */
5002
5003           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5004                                          depth))
5005             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5006         }
5007
5008       /* Give template template parms a DECL_CONTEXT of the template
5009          for which they are a parameter.  */
5010       parms = INNERMOST_TEMPLATE_PARMS (parms);
5011       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5012         {
5013           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5014           if (TREE_CODE (parm) == TEMPLATE_DECL)
5015             DECL_CONTEXT (parm) = tmpl;
5016         }
5017     }
5018
5019   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5020      back to its most general template.  If TMPL is a specialization,
5021      ARGS may only have the innermost set of arguments.  Add the missing
5022      argument levels if necessary.  */
5023   if (DECL_TEMPLATE_INFO (tmpl))
5024     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5025
5026   info = build_template_info (tmpl, args);
5027
5028   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5029     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5030   else if (DECL_LANG_SPECIFIC (decl))
5031     DECL_TEMPLATE_INFO (decl) = info;
5032
5033   return DECL_TEMPLATE_RESULT (tmpl);
5034 }
5035
5036 tree
5037 push_template_decl (tree decl)
5038 {
5039   return push_template_decl_real (decl, false);
5040 }
5041
5042 /* Called when a class template TYPE is redeclared with the indicated
5043    template PARMS, e.g.:
5044
5045      template <class T> struct S;
5046      template <class T> struct S {};  */
5047
5048 bool
5049 redeclare_class_template (tree type, tree parms)
5050 {
5051   tree tmpl;
5052   tree tmpl_parms;
5053   int i;
5054
5055   if (!TYPE_TEMPLATE_INFO (type))
5056     {
5057       error ("%qT is not a template type", type);
5058       return false;
5059     }
5060
5061   tmpl = TYPE_TI_TEMPLATE (type);
5062   if (!PRIMARY_TEMPLATE_P (tmpl))
5063     /* The type is nested in some template class.  Nothing to worry
5064        about here; there are no new template parameters for the nested
5065        type.  */
5066     return true;
5067
5068   if (!parms)
5069     {
5070       error ("template specifiers not specified in declaration of %qD",
5071              tmpl);
5072       return false;
5073     }
5074
5075   parms = INNERMOST_TEMPLATE_PARMS (parms);
5076   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5077
5078   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5079     {
5080       error_n (input_location, TREE_VEC_LENGTH (parms),
5081                "redeclared with %d template parameter",
5082                "redeclared with %d template parameters",
5083                TREE_VEC_LENGTH (parms));
5084       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5085                 "previous declaration %q+D used %d template parameter",
5086                 "previous declaration %q+D used %d template parameters",
5087                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5088       return false;
5089     }
5090
5091   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5092     {
5093       tree tmpl_parm;
5094       tree parm;
5095       tree tmpl_default;
5096       tree parm_default;
5097
5098       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5099           || TREE_VEC_ELT (parms, i) == error_mark_node)
5100         continue;
5101
5102       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5103       if (tmpl_parm == error_mark_node)
5104         return false;
5105
5106       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5107       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5108       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5109
5110       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5111          TEMPLATE_DECL.  */
5112       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5113           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5114               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5115           || (TREE_CODE (tmpl_parm) != PARM_DECL
5116               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5117                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5118           || (TREE_CODE (tmpl_parm) == PARM_DECL
5119               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5120                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5121         {
5122           error ("template parameter %q+#D", tmpl_parm);
5123           error ("redeclared here as %q#D", parm);
5124           return false;
5125         }
5126
5127       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5128         {
5129           /* We have in [temp.param]:
5130
5131              A template-parameter may not be given default arguments
5132              by two different declarations in the same scope.  */
5133           error_at (input_location, "redefinition of default argument for %q#D", parm);
5134           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5135                   "original definition appeared here");
5136           return false;
5137         }
5138
5139       if (parm_default != NULL_TREE)
5140         /* Update the previous template parameters (which are the ones
5141            that will really count) with the new default value.  */
5142         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5143       else if (tmpl_default != NULL_TREE)
5144         /* Update the new parameters, too; they'll be used as the
5145            parameters for any members.  */
5146         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5147     }
5148
5149     return true;
5150 }
5151
5152 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5153    (possibly simplified) expression.  */
5154
5155 static tree
5156 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5157 {
5158   if (expr == NULL_TREE)
5159     return NULL_TREE;
5160
5161   /* If we're in a template, but EXPR isn't value dependent, simplify
5162      it.  We're supposed to treat:
5163
5164        template <typename T> void f(T[1 + 1]);
5165        template <typename T> void f(T[2]);
5166
5167      as two declarations of the same function, for example.  */
5168   if (processing_template_decl
5169       && !type_dependent_expression_p (expr)
5170       && potential_constant_expression (expr)
5171       && !value_dependent_expression_p (expr))
5172     {
5173       HOST_WIDE_INT saved_processing_template_decl;
5174
5175       saved_processing_template_decl = processing_template_decl;
5176       processing_template_decl = 0;
5177       expr = tsubst_copy_and_build (expr,
5178                                     /*args=*/NULL_TREE,
5179                                     complain,
5180                                     /*in_decl=*/NULL_TREE,
5181                                     /*function_p=*/false,
5182                                     /*integral_constant_expression_p=*/true);
5183       processing_template_decl = saved_processing_template_decl;
5184     }
5185   return expr;
5186 }
5187
5188 tree
5189 fold_non_dependent_expr (tree expr)
5190 {
5191   return fold_non_dependent_expr_sfinae (expr, tf_error);
5192 }
5193
5194 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5195    must be a function or a pointer-to-function type, as specified
5196    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5197    and check that the resulting function has external linkage.  */
5198
5199 static tree
5200 convert_nontype_argument_function (tree type, tree expr)
5201 {
5202   tree fns = expr;
5203   tree fn, fn_no_ptr;
5204
5205   fn = instantiate_type (type, fns, tf_none);
5206   if (fn == error_mark_node)
5207     return error_mark_node;
5208
5209   fn_no_ptr = fn;
5210   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5211     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5212   if (TREE_CODE (fn_no_ptr) == BASELINK)
5213     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5214  
5215   /* [temp.arg.nontype]/1
5216
5217      A template-argument for a non-type, non-template template-parameter
5218      shall be one of:
5219      [...]
5220      -- the address of an object or function with external linkage.  */
5221   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5222     {
5223       error ("%qE is not a valid template argument for type %qT "
5224              "because function %qD has not external linkage",
5225              expr, type, fn_no_ptr);
5226       return NULL_TREE;
5227     }
5228
5229   return fn;
5230 }
5231
5232 /* Subroutine of convert_nontype_argument.
5233    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5234    Emit an error otherwise.  */
5235
5236 static bool
5237 check_valid_ptrmem_cst_expr (tree type, tree expr,
5238                              tsubst_flags_t complain)
5239 {
5240   STRIP_NOPS (expr);
5241   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5242     return true;
5243   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5244     return true;
5245   if (complain & tf_error)
5246     {
5247       error ("%qE is not a valid template argument for type %qT",
5248              expr, type);
5249       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5250     }
5251   return false;
5252 }
5253
5254 /* Returns TRUE iff the address of OP is value-dependent.
5255
5256    14.6.2.4 [temp.dep.temp]:
5257    A non-integral non-type template-argument is dependent if its type is
5258    dependent or it has either of the following forms
5259      qualified-id
5260      & qualified-id
5261    and contains a nested-name-specifier which specifies a class-name that
5262    names a dependent type.
5263
5264    We generalize this to just say that the address of a member of a
5265    dependent class is value-dependent; the above doesn't cover the
5266    address of a static data member named with an unqualified-id.  */
5267
5268 static bool
5269 has_value_dependent_address (tree op)
5270 {
5271   /* We could use get_inner_reference here, but there's no need;
5272      this is only relevant for template non-type arguments, which
5273      can only be expressed as &id-expression.  */
5274   if (DECL_P (op))
5275     {
5276       tree ctx = CP_DECL_CONTEXT (op);
5277       if (TYPE_P (ctx) && dependent_type_p (ctx))
5278         return true;
5279     }
5280
5281   return false;
5282 }
5283
5284 /* The next set of functions are used for providing helpful explanatory
5285    diagnostics for failed overload resolution.  Their messages should be
5286    indented by two spaces for consistency with the messages in
5287    call.c  */
5288
5289 static int
5290 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5291 {
5292   return 0;
5293 }
5294
5295 static int
5296 unify_parameter_deduction_failure (bool explain_p, tree parm)
5297 {
5298   if (explain_p)
5299     inform (input_location,
5300             "  couldn't deduce template parameter %qD", parm);
5301   return 1;
5302 }
5303
5304 static int
5305 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5306 {
5307   return 1;
5308 }
5309
5310 static int
5311 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5312 {
5313   if (explain_p)
5314     inform (input_location,
5315             "  types %qT and %qT have incompatible cv-qualifiers",
5316             parm, arg);
5317   return 1;
5318 }
5319
5320 static int
5321 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5322 {
5323   if (explain_p)
5324     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5325   return 1;
5326 }
5327
5328 static int
5329 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5330 {
5331   if (explain_p)
5332     inform (input_location,
5333             "  template parameter %qD is not a parameter pack, but "
5334             "argument %qD is",
5335             parm, arg);
5336   return 1;
5337 }
5338
5339 static int
5340 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5341 {
5342   if (explain_p)
5343     inform (input_location,
5344             "  template argument %qE does not match "
5345             "pointer-to-member constant %qE",
5346             arg, parm);
5347   return 1;
5348 }
5349
5350 static int
5351 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5352 {
5353   if (explain_p)
5354     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5355   return 1;
5356 }
5357
5358 static int
5359 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5360 {
5361   if (explain_p)
5362     inform (input_location,
5363             "  inconsistent parameter pack deduction with %qT and %qT",
5364             old_arg, new_arg);
5365   return 1;
5366 }
5367
5368 static int
5369 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5370 {
5371   if (explain_p)
5372     inform (input_location,
5373             "  deduced conflicting types for parameter %qT (%qT and %qT)",
5374             parm, first, second);
5375   return 1;
5376 }
5377
5378 static int
5379 unify_vla_arg (bool explain_p, tree arg)
5380 {
5381   if (explain_p)
5382     inform (input_location,
5383             "  variable-sized array type %qT is not "
5384             "a valid template argument",
5385             arg);
5386   return 1;
5387 }
5388
5389 static int
5390 unify_method_type_error (bool explain_p, tree arg)
5391 {
5392   if (explain_p)
5393     inform (input_location,
5394             "  member function type %qT is not a valid template argument",
5395             arg);
5396   return 1;
5397 }
5398
5399 static int
5400 unify_arity (bool explain_p, int have, int wanted)
5401 {
5402   if (explain_p)
5403     inform_n (input_location, wanted,
5404               "  candidate expects %d argument, %d provided",
5405               "  candidate expects %d arguments, %d provided",
5406               wanted, have);
5407   return 1;
5408 }
5409
5410 static int
5411 unify_too_many_arguments (bool explain_p, int have, int wanted)
5412 {
5413   return unify_arity (explain_p, have, wanted);
5414 }
5415
5416 static int
5417 unify_too_few_arguments (bool explain_p, int have, int wanted)
5418 {
5419   return unify_arity (explain_p, have, wanted);
5420 }
5421
5422 static int
5423 unify_arg_conversion (bool explain_p, tree to_type,
5424                       tree from_type, tree arg)
5425 {
5426   if (explain_p)
5427     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5428             arg, from_type, to_type);
5429   return 1;
5430 }
5431
5432 static int
5433 unify_no_common_base (bool explain_p, enum template_base_result r,
5434                       tree parm, tree arg)
5435 {
5436   if (explain_p)
5437     switch (r)
5438       {
5439       case tbr_ambiguous_baseclass:
5440         inform (input_location, "  %qT is an ambiguous base class of %qT",
5441                 arg, parm);
5442         break;
5443       default:
5444         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5445         break;
5446       }
5447   return 1;
5448 }
5449
5450 static int
5451 unify_inconsistent_template_template_parameters (bool explain_p)
5452 {
5453   if (explain_p)
5454     inform (input_location,
5455             "  template parameters of a template template argument are "
5456             "inconsistent with other deduced template arguments");
5457   return 1;
5458 }
5459
5460 static int
5461 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5462 {
5463   if (explain_p)
5464     inform (input_location,
5465             "  can't deduce a template for %qT from non-template type %qT",
5466             parm, arg);
5467   return 1;
5468 }
5469
5470 static int
5471 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5472 {
5473   if (explain_p)
5474     inform (input_location,
5475             "  template argument %qE does not match %qD", arg, parm);
5476   return 1;
5477 }
5478
5479 static int
5480 unify_overload_resolution_failure (bool explain_p, tree arg)
5481 {
5482   if (explain_p)
5483     inform (input_location,
5484             "  could not resolve address from overloaded function %qE",
5485             arg);
5486   return 1;
5487 }
5488
5489 /* Attempt to convert the non-type template parameter EXPR to the
5490    indicated TYPE.  If the conversion is successful, return the
5491    converted value.  If the conversion is unsuccessful, return
5492    NULL_TREE if we issued an error message, or error_mark_node if we
5493    did not.  We issue error messages for out-and-out bad template
5494    parameters, but not simply because the conversion failed, since we
5495    might be just trying to do argument deduction.  Both TYPE and EXPR
5496    must be non-dependent.
5497
5498    The conversion follows the special rules described in
5499    [temp.arg.nontype], and it is much more strict than an implicit
5500    conversion.
5501
5502    This function is called twice for each template argument (see
5503    lookup_template_class for a more accurate description of this
5504    problem). This means that we need to handle expressions which
5505    are not valid in a C++ source, but can be created from the
5506    first call (for instance, casts to perform conversions). These
5507    hacks can go away after we fix the double coercion problem.  */
5508
5509 static tree
5510 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5511 {
5512   tree expr_type;
5513
5514   /* Detect immediately string literals as invalid non-type argument.
5515      This special-case is not needed for correctness (we would easily
5516      catch this later), but only to provide better diagnostic for this
5517      common user mistake. As suggested by DR 100, we do not mention
5518      linkage issues in the diagnostic as this is not the point.  */
5519   /* FIXME we're making this OK.  */
5520   if (TREE_CODE (expr) == STRING_CST)
5521     {
5522       if (complain & tf_error)
5523         error ("%qE is not a valid template argument for type %qT "
5524                "because string literals can never be used in this context",
5525                expr, type);
5526       return NULL_TREE;
5527     }
5528
5529   /* Add the ADDR_EXPR now for the benefit of
5530      value_dependent_expression_p.  */
5531   if (TYPE_PTROBV_P (type)
5532       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5533     expr = decay_conversion (expr);
5534
5535   /* If we are in a template, EXPR may be non-dependent, but still
5536      have a syntactic, rather than semantic, form.  For example, EXPR
5537      might be a SCOPE_REF, rather than the VAR_DECL to which the
5538      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5539      so that access checking can be performed when the template is
5540      instantiated -- but here we need the resolved form so that we can
5541      convert the argument.  */
5542   if (TYPE_REF_OBJ_P (type)
5543       && has_value_dependent_address (expr))
5544     /* If we want the address and it's value-dependent, don't fold.  */;
5545   else if (!type_unknown_p (expr))
5546     expr = fold_non_dependent_expr_sfinae (expr, complain);
5547   if (error_operand_p (expr))
5548     return error_mark_node;
5549   expr_type = TREE_TYPE (expr);
5550   if (TREE_CODE (type) == REFERENCE_TYPE)
5551     expr = mark_lvalue_use (expr);
5552   else
5553     expr = mark_rvalue_use (expr);
5554
5555   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5556      to a non-type argument of "nullptr".  */
5557   if (expr == nullptr_node
5558       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5559     expr = convert (type, expr);
5560
5561   /* In C++11, non-type template arguments can be arbitrary constant
5562      expressions.  But don't fold a PTRMEM_CST to a CONSTRUCTOR yet.  */
5563   if (cxx_dialect >= cxx0x && TREE_CODE (expr) != PTRMEM_CST)
5564     expr = maybe_constant_value (expr);
5565
5566   /* HACK: Due to double coercion, we can get a
5567      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5568      which is the tree that we built on the first call (see
5569      below when coercing to reference to object or to reference to
5570      function). We just strip everything and get to the arg.
5571      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5572      for examples.  */
5573   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5574     {
5575       tree probe_type, probe = expr;
5576       if (REFERENCE_REF_P (probe))
5577         probe = TREE_OPERAND (probe, 0);
5578       probe_type = TREE_TYPE (probe);
5579       if (TREE_CODE (probe) == NOP_EXPR)
5580         {
5581           /* ??? Maybe we could use convert_from_reference here, but we
5582              would need to relax its constraints because the NOP_EXPR
5583              could actually change the type to something more cv-qualified,
5584              and this is not folded by convert_from_reference.  */
5585           tree addr = TREE_OPERAND (probe, 0);
5586           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5587           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5588           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5589           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5590                       (TREE_TYPE (probe_type),
5591                        TREE_TYPE (TREE_TYPE (addr))));
5592
5593           expr = TREE_OPERAND (addr, 0);
5594           expr_type = TREE_TYPE (expr);
5595         }
5596     }
5597
5598   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5599      parameter is a pointer to object, through decay and
5600      qualification conversion. Let's strip everything.  */
5601   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5602     {
5603       STRIP_NOPS (expr);
5604       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5605       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5606       /* Skip the ADDR_EXPR only if it is part of the decay for
5607          an array. Otherwise, it is part of the original argument
5608          in the source code.  */
5609       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5610         expr = TREE_OPERAND (expr, 0);
5611       expr_type = TREE_TYPE (expr);
5612     }
5613
5614   /* [temp.arg.nontype]/5, bullet 1
5615
5616      For a non-type template-parameter of integral or enumeration type,
5617      integral promotions (_conv.prom_) and integral conversions
5618      (_conv.integral_) are applied.  */
5619   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5620     {
5621       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5622       t = maybe_constant_value (t);
5623       if (t != error_mark_node)
5624         expr = t;
5625
5626       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5627         return error_mark_node;
5628
5629       /* Notice that there are constant expressions like '4 % 0' which
5630          do not fold into integer constants.  */
5631       if (TREE_CODE (expr) != INTEGER_CST)
5632         {
5633           if (complain & tf_error)
5634             {
5635               int errs = errorcount, warns = warningcount;
5636               expr = cxx_constant_value (expr);
5637               if (errorcount > errs || warningcount > warns)
5638                 inform (EXPR_LOC_OR_HERE (expr),
5639                         "in template argument for type %qT ", type);
5640               if (expr == error_mark_node)
5641                 return NULL_TREE;
5642               /* else cxx_constant_value complained but gave us
5643                  a real constant, so go ahead.  */
5644               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5645             }
5646           else
5647             return NULL_TREE;
5648         }
5649     }
5650   /* [temp.arg.nontype]/5, bullet 2
5651
5652      For a non-type template-parameter of type pointer to object,
5653      qualification conversions (_conv.qual_) and the array-to-pointer
5654      conversion (_conv.array_) are applied.  */
5655   else if (TYPE_PTROBV_P (type))
5656     {
5657       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5658
5659          A template-argument for a non-type, non-template template-parameter
5660          shall be one of: [...]
5661
5662          -- the name of a non-type template-parameter;
5663          -- the address of an object or function with external linkage, [...]
5664             expressed as "& id-expression" where the & is optional if the name
5665             refers to a function or array, or if the corresponding
5666             template-parameter is a reference.
5667
5668         Here, we do not care about functions, as they are invalid anyway
5669         for a parameter of type pointer-to-object.  */
5670
5671       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5672         /* Non-type template parameters are OK.  */
5673         ;
5674       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5675         /* Null pointer values are OK in C++11.  */;
5676       else if (TREE_CODE (expr) != ADDR_EXPR
5677                && TREE_CODE (expr_type) != ARRAY_TYPE)
5678         {
5679           if (TREE_CODE (expr) == VAR_DECL)
5680             {
5681               error ("%qD is not a valid template argument "
5682                      "because %qD is a variable, not the address of "
5683                      "a variable",
5684                      expr, expr);
5685               return NULL_TREE;
5686             }
5687           /* Other values, like integer constants, might be valid
5688              non-type arguments of some other type.  */
5689           return error_mark_node;
5690         }
5691       else
5692         {
5693           tree decl;
5694
5695           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5696                   ? TREE_OPERAND (expr, 0) : expr);
5697           if (TREE_CODE (decl) != VAR_DECL)
5698             {
5699               error ("%qE is not a valid template argument of type %qT "
5700                      "because %qE is not a variable",
5701                      expr, type, decl);
5702               return NULL_TREE;
5703             }
5704           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5705             {
5706               error ("%qE is not a valid template argument of type %qT "
5707                      "because %qD does not have external linkage",
5708                      expr, type, decl);
5709               return NULL_TREE;
5710             }
5711         }
5712
5713       expr = decay_conversion (expr);
5714       if (expr == error_mark_node)
5715         return error_mark_node;
5716
5717       expr = perform_qualification_conversions (type, expr);
5718       if (expr == error_mark_node)
5719         return error_mark_node;
5720     }
5721   /* [temp.arg.nontype]/5, bullet 3
5722
5723      For a non-type template-parameter of type reference to object, no
5724      conversions apply. The type referred to by the reference may be more
5725      cv-qualified than the (otherwise identical) type of the
5726      template-argument. The template-parameter is bound directly to the
5727      template-argument, which must be an lvalue.  */
5728   else if (TYPE_REF_OBJ_P (type))
5729     {
5730       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5731                                                       expr_type))
5732         return error_mark_node;
5733
5734       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5735         {
5736           error ("%qE is not a valid template argument for type %qT "
5737                  "because of conflicts in cv-qualification", expr, type);
5738           return NULL_TREE;
5739         }
5740
5741       if (!real_lvalue_p (expr))
5742         {
5743           error ("%qE is not a valid template argument for type %qT "
5744                  "because it is not an lvalue", expr, type);
5745           return NULL_TREE;
5746         }
5747
5748       /* [temp.arg.nontype]/1
5749
5750          A template-argument for a non-type, non-template template-parameter
5751          shall be one of: [...]
5752
5753          -- the address of an object or function with external linkage.  */
5754       if (TREE_CODE (expr) == INDIRECT_REF
5755           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5756         {
5757           expr = TREE_OPERAND (expr, 0);
5758           if (DECL_P (expr))
5759             {
5760               error ("%q#D is not a valid template argument for type %qT "
5761                      "because a reference variable does not have a constant "
5762                      "address", expr, type);
5763               return NULL_TREE;
5764             }
5765         }
5766
5767       if (!DECL_P (expr))
5768         {
5769           error ("%qE is not a valid template argument for type %qT "
5770                  "because it is not an object with external linkage",
5771                  expr, type);
5772           return NULL_TREE;
5773         }
5774
5775       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5776         {
5777           error ("%qE is not a valid template argument for type %qT "
5778                  "because object %qD has not external linkage",
5779                  expr, type, expr);
5780           return NULL_TREE;
5781         }
5782
5783       expr = build_nop (type, build_address (expr));
5784     }
5785   /* [temp.arg.nontype]/5, bullet 4
5786
5787      For a non-type template-parameter of type pointer to function, only
5788      the function-to-pointer conversion (_conv.func_) is applied. If the
5789      template-argument represents a set of overloaded functions (or a
5790      pointer to such), the matching function is selected from the set
5791      (_over.over_).  */
5792   else if (TYPE_PTRFN_P (type))
5793     {
5794       /* If the argument is a template-id, we might not have enough
5795          context information to decay the pointer.  */
5796       if (!type_unknown_p (expr_type))
5797         {
5798           expr = decay_conversion (expr);
5799           if (expr == error_mark_node)
5800             return error_mark_node;
5801         }
5802
5803       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5804         /* Null pointer values are OK in C++11.  */
5805         return perform_qualification_conversions (type, expr);
5806
5807       expr = convert_nontype_argument_function (type, expr);
5808       if (!expr || expr == error_mark_node)
5809         return expr;
5810
5811       if (TREE_CODE (expr) != ADDR_EXPR)
5812         {
5813           error ("%qE is not a valid template argument for type %qT", expr, type);
5814           error ("it must be the address of a function with external linkage");
5815           return NULL_TREE;
5816         }
5817     }
5818   /* [temp.arg.nontype]/5, bullet 5
5819
5820      For a non-type template-parameter of type reference to function, no
5821      conversions apply. If the template-argument represents a set of
5822      overloaded functions, the matching function is selected from the set
5823      (_over.over_).  */
5824   else if (TYPE_REFFN_P (type))
5825     {
5826       if (TREE_CODE (expr) == ADDR_EXPR)
5827         {
5828           error ("%qE is not a valid template argument for type %qT "
5829                  "because it is a pointer", expr, type);
5830           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5831           return NULL_TREE;
5832         }
5833
5834       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5835       if (!expr || expr == error_mark_node)
5836         return expr;
5837
5838       expr = build_nop (type, build_address (expr));
5839     }
5840   /* [temp.arg.nontype]/5, bullet 6
5841
5842      For a non-type template-parameter of type pointer to member function,
5843      no conversions apply. If the template-argument represents a set of
5844      overloaded member functions, the matching member function is selected
5845      from the set (_over.over_).  */
5846   else if (TYPE_PTRMEMFUNC_P (type))
5847     {
5848       expr = instantiate_type (type, expr, tf_none);
5849       if (expr == error_mark_node)
5850         return error_mark_node;
5851
5852       /* [temp.arg.nontype] bullet 1 says the pointer to member
5853          expression must be a pointer-to-member constant.  */
5854       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5855         return error_mark_node;
5856
5857       /* There is no way to disable standard conversions in
5858          resolve_address_of_overloaded_function (called by
5859          instantiate_type). It is possible that the call succeeded by
5860          converting &B::I to &D::I (where B is a base of D), so we need
5861          to reject this conversion here.
5862
5863          Actually, even if there was a way to disable standard conversions,
5864          it would still be better to reject them here so that we can
5865          provide a superior diagnostic.  */
5866       if (!same_type_p (TREE_TYPE (expr), type))
5867         {
5868           error ("%qE is not a valid template argument for type %qT "
5869                  "because it is of type %qT", expr, type,
5870                  TREE_TYPE (expr));
5871           /* If we are just one standard conversion off, explain.  */
5872           if (can_convert (type, TREE_TYPE (expr)))
5873             inform (input_location,
5874                     "standard conversions are not allowed in this context");
5875           return NULL_TREE;
5876         }
5877     }
5878   /* [temp.arg.nontype]/5, bullet 7
5879
5880      For a non-type template-parameter of type pointer to data member,
5881      qualification conversions (_conv.qual_) are applied.  */
5882   else if (TYPE_PTRMEM_P (type))
5883     {
5884       /* [temp.arg.nontype] bullet 1 says the pointer to member
5885          expression must be a pointer-to-member constant.  */
5886       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5887         return error_mark_node;
5888
5889       expr = perform_qualification_conversions (type, expr);
5890       if (expr == error_mark_node)
5891         return expr;
5892     }
5893   /* A template non-type parameter must be one of the above.  */
5894   else
5895     gcc_unreachable ();
5896
5897   /* Sanity check: did we actually convert the argument to the
5898      right type?  */
5899   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5900               (type, TREE_TYPE (expr)));
5901   return expr;
5902 }
5903
5904 /* Subroutine of coerce_template_template_parms, which returns 1 if
5905    PARM_PARM and ARG_PARM match using the rule for the template
5906    parameters of template template parameters. Both PARM and ARG are
5907    template parameters; the rest of the arguments are the same as for
5908    coerce_template_template_parms.
5909  */
5910 static int
5911 coerce_template_template_parm (tree parm,
5912                               tree arg,
5913                               tsubst_flags_t complain,
5914                               tree in_decl,
5915                               tree outer_args)
5916 {
5917   if (arg == NULL_TREE || arg == error_mark_node
5918       || parm == NULL_TREE || parm == error_mark_node)
5919     return 0;
5920   
5921   if (TREE_CODE (arg) != TREE_CODE (parm))
5922     return 0;
5923   
5924   switch (TREE_CODE (parm))
5925     {
5926     case TEMPLATE_DECL:
5927       /* We encounter instantiations of templates like
5928          template <template <template <class> class> class TT>
5929          class C;  */
5930       {
5931         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5932         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5933         
5934         if (!coerce_template_template_parms
5935             (parmparm, argparm, complain, in_decl, outer_args))
5936           return 0;
5937       }
5938       /* Fall through.  */
5939       
5940     case TYPE_DECL:
5941       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5942           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5943         /* Argument is a parameter pack but parameter is not.  */
5944         return 0;
5945       break;
5946       
5947     case PARM_DECL:
5948       /* The tsubst call is used to handle cases such as
5949          
5950            template <int> class C {};
5951            template <class T, template <T> class TT> class D {};
5952            D<int, C> d;
5953
5954          i.e. the parameter list of TT depends on earlier parameters.  */
5955       if (!uses_template_parms (TREE_TYPE (arg))
5956           && !same_type_p
5957                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5958                  TREE_TYPE (arg)))
5959         return 0;
5960       
5961       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5962           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5963         /* Argument is a parameter pack but parameter is not.  */
5964         return 0;
5965       
5966       break;
5967
5968     default:
5969       gcc_unreachable ();
5970     }
5971
5972   return 1;
5973 }
5974
5975
5976 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5977    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5978    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5979    or PARM_DECL.
5980
5981    Consider the example:
5982      template <class T> class A;
5983      template<template <class U> class TT> class B;
5984
5985    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5986    the parameters to A, and OUTER_ARGS contains A.  */
5987
5988 static int
5989 coerce_template_template_parms (tree parm_parms,
5990                                 tree arg_parms,
5991                                 tsubst_flags_t complain,
5992                                 tree in_decl,
5993                                 tree outer_args)
5994 {
5995   int nparms, nargs, i;
5996   tree parm, arg;
5997   int variadic_p = 0;
5998
5999   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6000   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6001
6002   nparms = TREE_VEC_LENGTH (parm_parms);
6003   nargs = TREE_VEC_LENGTH (arg_parms);
6004
6005   /* Determine whether we have a parameter pack at the end of the
6006      template template parameter's template parameter list.  */
6007   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6008     {
6009       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6010       
6011       if (parm == error_mark_node)
6012         return 0;
6013
6014       switch (TREE_CODE (parm))
6015         {
6016         case TEMPLATE_DECL:
6017         case TYPE_DECL:
6018           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6019             variadic_p = 1;
6020           break;
6021           
6022         case PARM_DECL:
6023           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6024             variadic_p = 1;
6025           break;
6026           
6027         default:
6028           gcc_unreachable ();
6029         }
6030     }
6031  
6032   if (nargs != nparms
6033       && !(variadic_p && nargs >= nparms - 1))
6034     return 0;
6035
6036   /* Check all of the template parameters except the parameter pack at
6037      the end (if any).  */
6038   for (i = 0; i < nparms - variadic_p; ++i)
6039     {
6040       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6041           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6042         continue;
6043
6044       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6045       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6046
6047       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6048                                           outer_args))
6049         return 0;
6050
6051     }
6052
6053   if (variadic_p)
6054     {
6055       /* Check each of the template parameters in the template
6056          argument against the template parameter pack at the end of
6057          the template template parameter.  */
6058       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6059         return 0;
6060
6061       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6062
6063       for (; i < nargs; ++i)
6064         {
6065           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6066             continue;
6067  
6068           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6069  
6070           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6071                                               outer_args))
6072             return 0;
6073         }
6074     }
6075
6076   return 1;
6077 }
6078
6079 /* Verifies that the deduced template arguments (in TARGS) for the
6080    template template parameters (in TPARMS) represent valid bindings,
6081    by comparing the template parameter list of each template argument
6082    to the template parameter list of its corresponding template
6083    template parameter, in accordance with DR150. This
6084    routine can only be called after all template arguments have been
6085    deduced. It will return TRUE if all of the template template
6086    parameter bindings are okay, FALSE otherwise.  */
6087 bool 
6088 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6089 {
6090   int i, ntparms = TREE_VEC_LENGTH (tparms);
6091   bool ret = true;
6092
6093   /* We're dealing with template parms in this process.  */
6094   ++processing_template_decl;
6095
6096   targs = INNERMOST_TEMPLATE_ARGS (targs);
6097
6098   for (i = 0; i < ntparms; ++i)
6099     {
6100       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6101       tree targ = TREE_VEC_ELT (targs, i);
6102
6103       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6104         {
6105           tree packed_args = NULL_TREE;
6106           int idx, len = 1;
6107
6108           if (ARGUMENT_PACK_P (targ))
6109             {
6110               /* Look inside the argument pack.  */
6111               packed_args = ARGUMENT_PACK_ARGS (targ);
6112               len = TREE_VEC_LENGTH (packed_args);
6113             }
6114
6115           for (idx = 0; idx < len; ++idx)
6116             {
6117               tree targ_parms = NULL_TREE;
6118
6119               if (packed_args)
6120                 /* Extract the next argument from the argument
6121                    pack.  */
6122                 targ = TREE_VEC_ELT (packed_args, idx);
6123
6124               if (PACK_EXPANSION_P (targ))
6125                 /* Look at the pattern of the pack expansion.  */
6126                 targ = PACK_EXPANSION_PATTERN (targ);
6127
6128               /* Extract the template parameters from the template
6129                  argument.  */
6130               if (TREE_CODE (targ) == TEMPLATE_DECL)
6131                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6132               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6133                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6134
6135               /* Verify that we can coerce the template template
6136                  parameters from the template argument to the template
6137                  parameter.  This requires an exact match.  */
6138               if (targ_parms
6139                   && !coerce_template_template_parms
6140                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6141                         targ_parms,
6142                         tf_none,
6143                         tparm,
6144                         targs))
6145                 {
6146                   ret = false;
6147                   goto out;
6148                 }
6149             }
6150         }
6151     }
6152
6153  out:
6154
6155   --processing_template_decl;
6156   return ret;
6157 }
6158
6159 /* Since type attributes aren't mangled, we need to strip them from
6160    template type arguments.  */
6161
6162 static tree
6163 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6164 {
6165   tree mv;
6166   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6167     return arg;
6168   mv = TYPE_MAIN_VARIANT (arg);
6169   arg = strip_typedefs (arg);
6170   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6171       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6172     {
6173       if (complain & tf_warning)
6174         warning (0, "ignoring attributes on template argument %qT", arg);
6175       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6176       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6177     }
6178   return arg;
6179 }
6180
6181 /* Convert the indicated template ARG as necessary to match the
6182    indicated template PARM.  Returns the converted ARG, or
6183    error_mark_node if the conversion was unsuccessful.  Error and
6184    warning messages are issued under control of COMPLAIN.  This
6185    conversion is for the Ith parameter in the parameter list.  ARGS is
6186    the full set of template arguments deduced so far.  */
6187
6188 static tree
6189 convert_template_argument (tree parm,
6190                            tree arg,
6191                            tree args,
6192                            tsubst_flags_t complain,
6193                            int i,
6194                            tree in_decl)
6195 {
6196   tree orig_arg;
6197   tree val;
6198   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6199
6200   if (TREE_CODE (arg) == TREE_LIST
6201       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6202     {
6203       /* The template argument was the name of some
6204          member function.  That's usually
6205          invalid, but static members are OK.  In any
6206          case, grab the underlying fields/functions
6207          and issue an error later if required.  */
6208       orig_arg = TREE_VALUE (arg);
6209       TREE_TYPE (arg) = unknown_type_node;
6210     }
6211
6212   orig_arg = arg;
6213
6214   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6215   requires_type = (TREE_CODE (parm) == TYPE_DECL
6216                    || requires_tmpl_type);
6217
6218   /* When determining whether an argument pack expansion is a template,
6219      look at the pattern.  */
6220   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6221     arg = PACK_EXPANSION_PATTERN (arg);
6222
6223   /* Deal with an injected-class-name used as a template template arg.  */
6224   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6225     {
6226       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6227       if (TREE_CODE (t) == TEMPLATE_DECL)
6228         {
6229           if (cxx_dialect >= cxx0x)
6230             /* OK under DR 1004.  */;
6231           else if (complain & tf_warning_or_error)
6232             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6233                      " used as template template argument", TYPE_NAME (arg));
6234           else if (flag_pedantic_errors)
6235             t = arg;
6236
6237           arg = t;
6238         }
6239     }
6240
6241   is_tmpl_type = 
6242     ((TREE_CODE (arg) == TEMPLATE_DECL
6243       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6244      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6245      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6246
6247   if (is_tmpl_type
6248       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6249           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6250     arg = TYPE_STUB_DECL (arg);
6251
6252   is_type = TYPE_P (arg) || is_tmpl_type;
6253
6254   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6255       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6256     {
6257       permerror (input_location, "to refer to a type member of a template parameter, "
6258                  "use %<typename %E%>", orig_arg);
6259
6260       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6261                                      TREE_OPERAND (arg, 1),
6262                                      typename_type,
6263                                      complain & tf_error);
6264       arg = orig_arg;
6265       is_type = 1;
6266     }
6267   if (is_type != requires_type)
6268     {
6269       if (in_decl)
6270         {
6271           if (complain & tf_error)
6272             {
6273               error ("type/value mismatch at argument %d in template "
6274                      "parameter list for %qD",
6275                      i + 1, in_decl);
6276               if (is_type)
6277                 error ("  expected a constant of type %qT, got %qT",
6278                        TREE_TYPE (parm),
6279                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6280               else if (requires_tmpl_type)
6281                 error ("  expected a class template, got %qE", orig_arg);
6282               else
6283                 error ("  expected a type, got %qE", orig_arg);
6284             }
6285         }
6286       return error_mark_node;
6287     }
6288   if (is_tmpl_type ^ requires_tmpl_type)
6289     {
6290       if (in_decl && (complain & tf_error))
6291         {
6292           error ("type/value mismatch at argument %d in template "
6293                  "parameter list for %qD",
6294                  i + 1, in_decl);
6295           if (is_tmpl_type)
6296             error ("  expected a type, got %qT", DECL_NAME (arg));
6297           else
6298             error ("  expected a class template, got %qT", orig_arg);
6299         }
6300       return error_mark_node;
6301     }
6302
6303   if (is_type)
6304     {
6305       if (requires_tmpl_type)
6306         {
6307           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6308             /* The number of argument required is not known yet.
6309                Just accept it for now.  */
6310             val = TREE_TYPE (arg);
6311           else
6312             {
6313               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6314               tree argparm;
6315
6316               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6317
6318               if (coerce_template_template_parms (parmparm, argparm,
6319                                                   complain, in_decl,
6320                                                   args))
6321                 {
6322                   val = arg;
6323
6324                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6325                      TEMPLATE_DECL.  */
6326                   if (val != error_mark_node)
6327                     {
6328                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6329                         val = TREE_TYPE (val);
6330                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6331                         val = make_pack_expansion (val);
6332                     }
6333                 }
6334               else
6335                 {
6336                   if (in_decl && (complain & tf_error))
6337                     {
6338                       error ("type/value mismatch at argument %d in "
6339                              "template parameter list for %qD",
6340                              i + 1, in_decl);
6341                       error ("  expected a template of type %qD, got %qT",
6342                              parm, orig_arg);
6343                     }
6344
6345                   val = error_mark_node;
6346                 }
6347             }
6348         }
6349       else
6350         val = orig_arg;
6351       /* We only form one instance of each template specialization.
6352          Therefore, if we use a non-canonical variant (i.e., a
6353          typedef), any future messages referring to the type will use
6354          the typedef, which is confusing if those future uses do not
6355          themselves also use the typedef.  */
6356       if (TYPE_P (val))
6357         val = canonicalize_type_argument (val, complain);
6358     }
6359   else
6360     {
6361       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6362
6363       if (invalid_nontype_parm_type_p (t, complain))
6364         return error_mark_node;
6365
6366       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6367         {
6368           if (same_type_p (t, TREE_TYPE (orig_arg)))
6369             val = orig_arg;
6370           else
6371             {
6372               /* Not sure if this is reachable, but it doesn't hurt
6373                  to be robust.  */
6374               error ("type mismatch in nontype parameter pack");
6375               val = error_mark_node;
6376             }
6377         }
6378       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6379         /* We used to call digest_init here.  However, digest_init
6380            will report errors, which we don't want when complain
6381            is zero.  More importantly, digest_init will try too
6382            hard to convert things: for example, `0' should not be
6383            converted to pointer type at this point according to
6384            the standard.  Accepting this is not merely an
6385            extension, since deciding whether or not these
6386            conversions can occur is part of determining which
6387            function template to call, or whether a given explicit
6388            argument specification is valid.  */
6389         val = convert_nontype_argument (t, orig_arg, complain);
6390       else
6391         val = orig_arg;
6392
6393       if (val == NULL_TREE)
6394         val = error_mark_node;
6395       else if (val == error_mark_node && (complain & tf_error))
6396         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6397
6398       if (TREE_CODE (val) == SCOPE_REF)
6399         {
6400           /* Strip typedefs from the SCOPE_REF.  */
6401           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6402           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6403                                                    complain);
6404           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6405                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6406         }
6407     }
6408
6409   return val;
6410 }
6411
6412 /* Coerces the remaining template arguments in INNER_ARGS (from
6413    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6414    Returns the coerced argument pack. PARM_IDX is the position of this
6415    parameter in the template parameter list. ARGS is the original
6416    template argument list.  */
6417 static tree
6418 coerce_template_parameter_pack (tree parms,
6419                                 int parm_idx,
6420                                 tree args,
6421                                 tree inner_args,
6422                                 int arg_idx,
6423                                 tree new_args,
6424                                 int* lost,
6425                                 tree in_decl,
6426                                 tsubst_flags_t complain)
6427 {
6428   tree parm = TREE_VEC_ELT (parms, parm_idx);
6429   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6430   tree packed_args;
6431   tree argument_pack;
6432   tree packed_types = NULL_TREE;
6433
6434   if (arg_idx > nargs)
6435     arg_idx = nargs;
6436
6437   packed_args = make_tree_vec (nargs - arg_idx);
6438
6439   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6440       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6441     {
6442       /* When the template parameter is a non-type template
6443          parameter pack whose type uses parameter packs, we need
6444          to look at each of the template arguments
6445          separately. Build a vector of the types for these
6446          non-type template parameters in PACKED_TYPES.  */
6447       tree expansion 
6448         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6449       packed_types = tsubst_pack_expansion (expansion, args,
6450                                             complain, in_decl);
6451
6452       if (packed_types == error_mark_node)
6453         return error_mark_node;
6454
6455       /* Check that we have the right number of arguments.  */
6456       if (arg_idx < nargs
6457           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6458           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6459         {
6460           int needed_parms 
6461             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6462           error ("wrong number of template arguments (%d, should be %d)",
6463                  nargs, needed_parms);
6464           return error_mark_node;
6465         }
6466
6467       /* If we aren't able to check the actual arguments now
6468          (because they haven't been expanded yet), we can at least
6469          verify that all of the types used for the non-type
6470          template parameter pack are, in fact, valid for non-type
6471          template parameters.  */
6472       if (arg_idx < nargs 
6473           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6474         {
6475           int j, len = TREE_VEC_LENGTH (packed_types);
6476           for (j = 0; j < len; ++j)
6477             {
6478               tree t = TREE_VEC_ELT (packed_types, j);
6479               if (invalid_nontype_parm_type_p (t, complain))
6480                 return error_mark_node;
6481             }
6482         }
6483     }
6484
6485   /* Convert the remaining arguments, which will be a part of the
6486      parameter pack "parm".  */
6487   for (; arg_idx < nargs; ++arg_idx)
6488     {
6489       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6490       tree actual_parm = TREE_VALUE (parm);
6491
6492       if (packed_types && !PACK_EXPANSION_P (arg))
6493         {
6494           /* When we have a vector of types (corresponding to the
6495              non-type template parameter pack that uses parameter
6496              packs in its type, as mention above), and the
6497              argument is not an expansion (which expands to a
6498              currently unknown number of arguments), clone the
6499              parm and give it the next type in PACKED_TYPES.  */
6500           actual_parm = copy_node (actual_parm);
6501           TREE_TYPE (actual_parm) = 
6502             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6503         }
6504
6505       if (arg != error_mark_node)
6506         arg = convert_template_argument (actual_parm, 
6507                                          arg, new_args, complain, parm_idx,
6508                                          in_decl);
6509       if (arg == error_mark_node)
6510         (*lost)++;
6511       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6512     }
6513
6514   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6515       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6516     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6517   else
6518     {
6519       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6520       TREE_TYPE (argument_pack) 
6521         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6522       TREE_CONSTANT (argument_pack) = 1;
6523     }
6524
6525   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6526 #ifdef ENABLE_CHECKING
6527   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6528                                        TREE_VEC_LENGTH (packed_args));
6529 #endif
6530   return argument_pack;
6531 }
6532
6533 /* Convert all template arguments to their appropriate types, and
6534    return a vector containing the innermost resulting template
6535    arguments.  If any error occurs, return error_mark_node. Error and
6536    warning messages are issued under control of COMPLAIN.
6537
6538    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6539    for arguments not specified in ARGS.  Otherwise, if
6540    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6541    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6542    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6543    ARGS.  */
6544
6545 static tree
6546 coerce_template_parms (tree parms,
6547                        tree args,
6548                        tree in_decl,
6549                        tsubst_flags_t complain,
6550                        bool require_all_args,
6551                        bool use_default_args)
6552 {
6553   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6554   tree inner_args;
6555   tree new_args;
6556   tree new_inner_args;
6557   int saved_unevaluated_operand;
6558   int saved_inhibit_evaluation_warnings;
6559
6560   /* When used as a boolean value, indicates whether this is a
6561      variadic template parameter list. Since it's an int, we can also
6562      subtract it from nparms to get the number of non-variadic
6563      parameters.  */
6564   int variadic_p = 0;
6565   int post_variadic_parms = 0;
6566
6567   if (args == error_mark_node)
6568     return error_mark_node;
6569
6570   nparms = TREE_VEC_LENGTH (parms);
6571
6572   /* Determine if there are any parameter packs.  */
6573   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6574     {
6575       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6576       if (variadic_p)
6577         ++post_variadic_parms;
6578       if (template_parameter_pack_p (tparm))
6579         ++variadic_p;
6580     }
6581
6582   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6583   /* If there are no parameters that follow a parameter pack, we need to
6584      expand any argument packs so that we can deduce a parameter pack from
6585      some non-packed args followed by an argument pack, as in variadic85.C.
6586      If there are such parameters, we need to leave argument packs intact
6587      so the arguments are assigned properly.  This can happen when dealing
6588      with a nested class inside a partial specialization of a class
6589      template, as in variadic92.C, or when deducing a template parameter pack
6590      from a sub-declarator, as in variadic114.C.  */
6591   if (!post_variadic_parms)
6592     inner_args = expand_template_argument_pack (inner_args);
6593
6594   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6595   if ((nargs > nparms && !variadic_p)
6596       || (nargs < nparms - variadic_p
6597           && require_all_args
6598           && (!use_default_args
6599               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6600                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6601     {
6602       if (complain & tf_error)
6603         {
6604           if (variadic_p)
6605             {
6606               nparms -= variadic_p;
6607               error ("wrong number of template arguments "
6608                      "(%d, should be %d or more)", nargs, nparms);
6609             }
6610           else
6611              error ("wrong number of template arguments "
6612                     "(%d, should be %d)", nargs, nparms);
6613
6614           if (in_decl)
6615             error ("provided for %q+D", in_decl);
6616         }
6617
6618       return error_mark_node;
6619     }
6620
6621   /* We need to evaluate the template arguments, even though this
6622      template-id may be nested within a "sizeof".  */
6623   saved_unevaluated_operand = cp_unevaluated_operand;
6624   cp_unevaluated_operand = 0;
6625   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6626   c_inhibit_evaluation_warnings = 0;
6627   new_inner_args = make_tree_vec (nparms);
6628   new_args = add_outermost_template_args (args, new_inner_args);
6629   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6630     {
6631       tree arg;
6632       tree parm;
6633
6634       /* Get the Ith template parameter.  */
6635       parm = TREE_VEC_ELT (parms, parm_idx);
6636  
6637       if (parm == error_mark_node)
6638       {
6639         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6640         continue;
6641       }
6642
6643       /* Calculate the next argument.  */
6644       if (arg_idx < nargs)
6645         arg = TREE_VEC_ELT (inner_args, arg_idx);
6646       else
6647         arg = NULL_TREE;
6648
6649       if (template_parameter_pack_p (TREE_VALUE (parm))
6650           && !(arg && ARGUMENT_PACK_P (arg)))
6651         {
6652           /* All remaining arguments will be placed in the
6653              template parameter pack PARM.  */
6654           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6655                                                 inner_args, arg_idx,
6656                                                 new_args, &lost,
6657                                                 in_decl, complain);
6658
6659           /* Store this argument.  */
6660           if (arg == error_mark_node)
6661             lost++;
6662           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6663
6664           /* We are done with all of the arguments.  */
6665           arg_idx = nargs;
6666           
6667           continue;
6668         }
6669       else if (arg)
6670         {
6671           if (PACK_EXPANSION_P (arg))
6672             {
6673               if (complain & tf_error)
6674                 {
6675                   /* FIXME this restriction was removed by N2555; see
6676                      bug 35722.  */
6677                   /* If ARG is a pack expansion, but PARM is not a
6678                      template parameter pack (if it were, we would have
6679                      handled it above), we're trying to expand into a
6680                      fixed-length argument list.  */
6681                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6682                     sorry ("cannot expand %<%E%> into a fixed-length "
6683                            "argument list", arg);
6684                   else
6685                     sorry ("cannot expand %<%T%> into a fixed-length "
6686                            "argument list", arg);
6687                 }
6688               ++lost;
6689             }
6690         }
6691       else if (require_all_args)
6692         {
6693           /* There must be a default arg in this case.  */
6694           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6695                                      complain, in_decl);
6696           /* The position of the first default template argument,
6697              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6698              Record that.  */
6699           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6700             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6701         }
6702       else
6703         break;
6704
6705       if (arg == error_mark_node)
6706         {
6707           if (complain & tf_error)
6708             error ("template argument %d is invalid", arg_idx + 1);
6709         }
6710       else if (!arg)
6711         /* This only occurs if there was an error in the template
6712            parameter list itself (which we would already have
6713            reported) that we are trying to recover from, e.g., a class
6714            template with a parameter list such as
6715            template<typename..., typename>.  */
6716         ++lost;
6717       else
6718         arg = convert_template_argument (TREE_VALUE (parm),
6719                                          arg, new_args, complain, 
6720                                          parm_idx, in_decl);
6721
6722       if (arg == error_mark_node)
6723         lost++;
6724       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6725     }
6726   cp_unevaluated_operand = saved_unevaluated_operand;
6727   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6728
6729   if (lost)
6730     return error_mark_node;
6731
6732 #ifdef ENABLE_CHECKING
6733   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6734     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6735                                          TREE_VEC_LENGTH (new_inner_args));
6736 #endif
6737
6738   return new_inner_args;
6739 }
6740
6741 /* Returns 1 if template args OT and NT are equivalent.  */
6742
6743 static int
6744 template_args_equal (tree ot, tree nt)
6745 {
6746   if (nt == ot)
6747     return 1;
6748   if (nt == NULL_TREE || ot == NULL_TREE)
6749     return false;
6750
6751   if (TREE_CODE (nt) == TREE_VEC)
6752     /* For member templates */
6753     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6754   else if (PACK_EXPANSION_P (ot))
6755     return PACK_EXPANSION_P (nt) 
6756       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6757                               PACK_EXPANSION_PATTERN (nt));
6758   else if (ARGUMENT_PACK_P (ot))
6759     {
6760       int i, len;
6761       tree opack, npack;
6762
6763       if (!ARGUMENT_PACK_P (nt))
6764         return 0;
6765
6766       opack = ARGUMENT_PACK_ARGS (ot);
6767       npack = ARGUMENT_PACK_ARGS (nt);
6768       len = TREE_VEC_LENGTH (opack);
6769       if (TREE_VEC_LENGTH (npack) != len)
6770         return 0;
6771       for (i = 0; i < len; ++i)
6772         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6773                                   TREE_VEC_ELT (npack, i)))
6774           return 0;
6775       return 1;
6776     }
6777   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6778     {
6779       /* We get here probably because we are in the middle of substituting
6780          into the pattern of a pack expansion. In that case the
6781          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6782          interested in. So we want to use the initial pack argument for
6783          the comparison.  */
6784       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6785       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6786         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6787       return template_args_equal (ot, nt);
6788     }
6789   else if (TYPE_P (nt))
6790     return TYPE_P (ot) && same_type_p (ot, nt);
6791   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6792     return 0;
6793   else
6794     return cp_tree_equal (ot, nt);
6795 }
6796
6797 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6798    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6799    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6800
6801 static int
6802 comp_template_args_with_info (tree oldargs, tree newargs,
6803                               tree *oldarg_ptr, tree *newarg_ptr)
6804 {
6805   int i;
6806
6807   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6808     return 0;
6809
6810   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6811     {
6812       tree nt = TREE_VEC_ELT (newargs, i);
6813       tree ot = TREE_VEC_ELT (oldargs, i);
6814
6815       if (! template_args_equal (ot, nt))
6816         {
6817           if (oldarg_ptr != NULL)
6818             *oldarg_ptr = ot;
6819           if (newarg_ptr != NULL)
6820             *newarg_ptr = nt;
6821           return 0;
6822         }
6823     }
6824   return 1;
6825 }
6826
6827 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6828    of template arguments.  Returns 0 otherwise.  */
6829
6830 int
6831 comp_template_args (tree oldargs, tree newargs)
6832 {
6833   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6834 }
6835
6836 static void
6837 add_pending_template (tree d)
6838 {
6839   tree ti = (TYPE_P (d)
6840              ? CLASSTYPE_TEMPLATE_INFO (d)
6841              : DECL_TEMPLATE_INFO (d));
6842   struct pending_template *pt;
6843   int level;
6844
6845   if (TI_PENDING_TEMPLATE_FLAG (ti))
6846     return;
6847
6848   /* We are called both from instantiate_decl, where we've already had a
6849      tinst_level pushed, and instantiate_template, where we haven't.
6850      Compensate.  */
6851   level = !current_tinst_level || current_tinst_level->decl != d;
6852
6853   if (level)
6854     push_tinst_level (d);
6855
6856   pt = ggc_alloc_pending_template ();
6857   pt->next = NULL;
6858   pt->tinst = current_tinst_level;
6859   if (last_pending_template)
6860     last_pending_template->next = pt;
6861   else
6862     pending_templates = pt;
6863
6864   last_pending_template = pt;
6865
6866   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6867
6868   if (level)
6869     pop_tinst_level ();
6870 }
6871
6872
6873 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6874    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6875    documentation for TEMPLATE_ID_EXPR.  */
6876
6877 tree
6878 lookup_template_function (tree fns, tree arglist)
6879 {
6880   tree type;
6881
6882   if (fns == error_mark_node || arglist == error_mark_node)
6883     return error_mark_node;
6884
6885   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6886
6887   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6888     {
6889       error ("%q#D is not a function template", fns);
6890       return error_mark_node;
6891     }
6892
6893   if (BASELINK_P (fns))
6894     {
6895       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6896                                          unknown_type_node,
6897                                          BASELINK_FUNCTIONS (fns),
6898                                          arglist);
6899       return fns;
6900     }
6901
6902   type = TREE_TYPE (fns);
6903   if (TREE_CODE (fns) == OVERLOAD || !type)
6904     type = unknown_type_node;
6905
6906   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6907 }
6908
6909 /* Within the scope of a template class S<T>, the name S gets bound
6910    (in build_self_reference) to a TYPE_DECL for the class, not a
6911    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6912    or one of its enclosing classes, and that type is a template,
6913    return the associated TEMPLATE_DECL.  Otherwise, the original
6914    DECL is returned.
6915
6916    Also handle the case when DECL is a TREE_LIST of ambiguous
6917    injected-class-names from different bases.  */
6918
6919 tree
6920 maybe_get_template_decl_from_type_decl (tree decl)
6921 {
6922   if (decl == NULL_TREE)
6923     return decl;
6924
6925   /* DR 176: A lookup that finds an injected-class-name (10.2
6926      [class.member.lookup]) can result in an ambiguity in certain cases
6927      (for example, if it is found in more than one base class). If all of
6928      the injected-class-names that are found refer to specializations of
6929      the same class template, and if the name is followed by a
6930      template-argument-list, the reference refers to the class template
6931      itself and not a specialization thereof, and is not ambiguous.  */
6932   if (TREE_CODE (decl) == TREE_LIST)
6933     {
6934       tree t, tmpl = NULL_TREE;
6935       for (t = decl; t; t = TREE_CHAIN (t))
6936         {
6937           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6938           if (!tmpl)
6939             tmpl = elt;
6940           else if (tmpl != elt)
6941             break;
6942         }
6943       if (tmpl && t == NULL_TREE)
6944         return tmpl;
6945       else
6946         return decl;
6947     }
6948
6949   return (decl != NULL_TREE
6950           && DECL_SELF_REFERENCE_P (decl)
6951           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6952     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6953 }
6954
6955 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6956    parameters, find the desired type.
6957
6958    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6959
6960    IN_DECL, if non-NULL, is the template declaration we are trying to
6961    instantiate.
6962
6963    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6964    the class we are looking up.
6965
6966    Issue error and warning messages under control of COMPLAIN.
6967
6968    If the template class is really a local class in a template
6969    function, then the FUNCTION_CONTEXT is the function in which it is
6970    being instantiated.
6971
6972    ??? Note that this function is currently called *twice* for each
6973    template-id: the first time from the parser, while creating the
6974    incomplete type (finish_template_type), and the second type during the
6975    real instantiation (instantiate_template_class). This is surely something
6976    that we want to avoid. It also causes some problems with argument
6977    coercion (see convert_nontype_argument for more information on this).  */
6978
6979 static tree
6980 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6981                          int entering_scope, tsubst_flags_t complain)
6982 {
6983   tree templ = NULL_TREE, parmlist;
6984   tree t;
6985   spec_entry **slot;
6986   spec_entry *entry;
6987   spec_entry elt;
6988   hashval_t hash;
6989
6990   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6991     {
6992       tree value = innermost_non_namespace_value (d1);
6993       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6994         templ = value;
6995       else
6996         {
6997           if (context)
6998             push_decl_namespace (context);
6999           templ = lookup_name (d1);
7000           templ = maybe_get_template_decl_from_type_decl (templ);
7001           if (context)
7002             pop_decl_namespace ();
7003         }
7004       if (templ)
7005         context = DECL_CONTEXT (templ);
7006     }
7007   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7008     {
7009       tree type = TREE_TYPE (d1);
7010
7011       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7012          an implicit typename for the second A.  Deal with it.  */
7013       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7014         type = TREE_TYPE (type);
7015
7016       if (CLASSTYPE_TEMPLATE_INFO (type))
7017         {
7018           templ = CLASSTYPE_TI_TEMPLATE (type);
7019           d1 = DECL_NAME (templ);
7020         }
7021     }
7022   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7023            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7024     {
7025       templ = TYPE_TI_TEMPLATE (d1);
7026       d1 = DECL_NAME (templ);
7027     }
7028   else if (TREE_CODE (d1) == TEMPLATE_DECL
7029            && DECL_TEMPLATE_RESULT (d1)
7030            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7031     {
7032       templ = d1;
7033       d1 = DECL_NAME (templ);
7034       context = DECL_CONTEXT (templ);
7035     }
7036
7037   /* Issue an error message if we didn't find a template.  */
7038   if (! templ)
7039     {
7040       if (complain & tf_error)
7041         error ("%qT is not a template", d1);
7042       return error_mark_node;
7043     }
7044
7045   if (TREE_CODE (templ) != TEMPLATE_DECL
7046          /* Make sure it's a user visible template, if it was named by
7047             the user.  */
7048       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7049           && !PRIMARY_TEMPLATE_P (templ)))
7050     {
7051       if (complain & tf_error)
7052         {
7053           error ("non-template type %qT used as a template", d1);
7054           if (in_decl)
7055             error ("for template declaration %q+D", in_decl);
7056         }
7057       return error_mark_node;
7058     }
7059
7060   complain &= ~tf_user;
7061
7062   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7063     {
7064       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7065          template arguments */
7066
7067       tree parm;
7068       tree arglist2;
7069       tree outer;
7070
7071       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7072
7073       /* Consider an example where a template template parameter declared as
7074
7075            template <class T, class U = std::allocator<T> > class TT
7076
7077          The template parameter level of T and U are one level larger than
7078          of TT.  To proper process the default argument of U, say when an
7079          instantiation `TT<int>' is seen, we need to build the full
7080          arguments containing {int} as the innermost level.  Outer levels,
7081          available when not appearing as default template argument, can be
7082          obtained from the arguments of the enclosing template.
7083
7084          Suppose that TT is later substituted with std::vector.  The above
7085          instantiation is `TT<int, std::allocator<T> >' with TT at
7086          level 1, and T at level 2, while the template arguments at level 1
7087          becomes {std::vector} and the inner level 2 is {int}.  */
7088
7089       outer = DECL_CONTEXT (templ);
7090       if (outer)
7091         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7092       else if (current_template_parms)
7093         /* This is an argument of the current template, so we haven't set
7094            DECL_CONTEXT yet.  */
7095         outer = current_template_args ();
7096
7097       if (outer)
7098         arglist = add_to_template_args (outer, arglist);
7099
7100       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7101                                         complain,
7102                                         /*require_all_args=*/true,
7103                                         /*use_default_args=*/true);
7104       if (arglist2 == error_mark_node
7105           || (!uses_template_parms (arglist2)
7106               && check_instantiated_args (templ, arglist2, complain)))
7107         return error_mark_node;
7108
7109       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7110       return parm;
7111     }
7112   else
7113     {
7114       tree template_type = TREE_TYPE (templ);
7115       tree gen_tmpl;
7116       tree type_decl;
7117       tree found = NULL_TREE;
7118       int arg_depth;
7119       int parm_depth;
7120       int is_dependent_type;
7121       int use_partial_inst_tmpl = false;
7122
7123       gen_tmpl = most_general_template (templ);
7124       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7125       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7126       arg_depth = TMPL_ARGS_DEPTH (arglist);
7127
7128       if (arg_depth == 1 && parm_depth > 1)
7129         {
7130           /* We've been given an incomplete set of template arguments.
7131              For example, given:
7132
7133                template <class T> struct S1 {
7134                  template <class U> struct S2 {};
7135                  template <class U> struct S2<U*> {};
7136                 };
7137
7138              we will be called with an ARGLIST of `U*', but the
7139              TEMPLATE will be `template <class T> template
7140              <class U> struct S1<T>::S2'.  We must fill in the missing
7141              arguments.  */
7142           arglist
7143             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7144                                            arglist);
7145           arg_depth = TMPL_ARGS_DEPTH (arglist);
7146         }
7147
7148       /* Now we should have enough arguments.  */
7149       gcc_assert (parm_depth == arg_depth);
7150
7151       /* From here on, we're only interested in the most general
7152          template.  */
7153
7154       /* Calculate the BOUND_ARGS.  These will be the args that are
7155          actually tsubst'd into the definition to create the
7156          instantiation.  */
7157       if (parm_depth > 1)
7158         {
7159           /* We have multiple levels of arguments to coerce, at once.  */
7160           int i;
7161           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7162
7163           tree bound_args = make_tree_vec (parm_depth);
7164
7165           for (i = saved_depth,
7166                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7167                i > 0 && t != NULL_TREE;
7168                --i, t = TREE_CHAIN (t))
7169             {
7170               tree a;
7171               if (i == saved_depth)
7172                 a = coerce_template_parms (TREE_VALUE (t),
7173                                            arglist, gen_tmpl,
7174                                            complain,
7175                                            /*require_all_args=*/true,
7176                                            /*use_default_args=*/true);
7177               else
7178                 /* Outer levels should have already been coerced.  */
7179                 a = TMPL_ARGS_LEVEL (arglist, i);
7180
7181               /* Don't process further if one of the levels fails.  */
7182               if (a == error_mark_node)
7183                 {
7184                   /* Restore the ARGLIST to its full size.  */
7185                   TREE_VEC_LENGTH (arglist) = saved_depth;
7186                   return error_mark_node;
7187                 }
7188
7189               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7190
7191               /* We temporarily reduce the length of the ARGLIST so
7192                  that coerce_template_parms will see only the arguments
7193                  corresponding to the template parameters it is
7194                  examining.  */
7195               TREE_VEC_LENGTH (arglist)--;
7196             }
7197
7198           /* Restore the ARGLIST to its full size.  */
7199           TREE_VEC_LENGTH (arglist) = saved_depth;
7200
7201           arglist = bound_args;
7202         }
7203       else
7204         arglist
7205           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7206                                    INNERMOST_TEMPLATE_ARGS (arglist),
7207                                    gen_tmpl,
7208                                    complain,
7209                                    /*require_all_args=*/true,
7210                                    /*use_default_args=*/true);
7211
7212       if (arglist == error_mark_node)
7213         /* We were unable to bind the arguments.  */
7214         return error_mark_node;
7215
7216       /* In the scope of a template class, explicit references to the
7217          template class refer to the type of the template, not any
7218          instantiation of it.  For example, in:
7219
7220            template <class T> class C { void f(C<T>); }
7221
7222          the `C<T>' is just the same as `C'.  Outside of the
7223          class, however, such a reference is an instantiation.  */
7224       if ((entering_scope
7225            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7226            || currently_open_class (template_type))
7227           /* comp_template_args is expensive, check it last.  */
7228           && comp_template_args (TYPE_TI_ARGS (template_type),
7229                                  arglist))
7230         return template_type;
7231
7232       /* If we already have this specialization, return it.  */
7233       elt.tmpl = gen_tmpl;
7234       elt.args = arglist;
7235       hash = hash_specialization (&elt);
7236       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7237                                                   &elt, hash);
7238
7239       if (entry)
7240         return entry->spec;
7241
7242       is_dependent_type = uses_template_parms (arglist);
7243
7244       /* If the deduced arguments are invalid, then the binding
7245          failed.  */
7246       if (!is_dependent_type
7247           && check_instantiated_args (gen_tmpl,
7248                                       INNERMOST_TEMPLATE_ARGS (arglist),
7249                                       complain))
7250         return error_mark_node;
7251
7252       if (!is_dependent_type
7253           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7254           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7255           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7256         {
7257           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7258                                       DECL_NAME (gen_tmpl),
7259                                       /*tag_scope=*/ts_global);
7260           return found;
7261         }
7262
7263       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7264                         complain, in_decl);
7265       if (!context)
7266         context = global_namespace;
7267
7268       /* Create the type.  */
7269       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7270         {
7271           if (!is_dependent_type)
7272             {
7273               set_current_access_from_decl (TYPE_NAME (template_type));
7274               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7275                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7276                                       arglist, complain, in_decl),
7277                               SCOPED_ENUM_P (template_type), NULL);
7278             }
7279           else
7280             {
7281               /* We don't want to call start_enum for this type, since
7282                  the values for the enumeration constants may involve
7283                  template parameters.  And, no one should be interested
7284                  in the enumeration constants for such a type.  */
7285               t = cxx_make_type (ENUMERAL_TYPE);
7286               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7287             }
7288           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7289           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7290             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7291         }
7292       else
7293         {
7294           t = make_class_type (TREE_CODE (template_type));
7295           CLASSTYPE_DECLARED_CLASS (t)
7296             = CLASSTYPE_DECLARED_CLASS (template_type);
7297           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7298           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7299
7300           /* A local class.  Make sure the decl gets registered properly.  */
7301           if (context == current_function_decl)
7302             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7303
7304           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7305             /* This instantiation is another name for the primary
7306                template type. Set the TYPE_CANONICAL field
7307                appropriately. */
7308             TYPE_CANONICAL (t) = template_type;
7309           else if (any_template_arguments_need_structural_equality_p (arglist))
7310             /* Some of the template arguments require structural
7311                equality testing, so this template class requires
7312                structural equality testing. */
7313             SET_TYPE_STRUCTURAL_EQUALITY (t);
7314         }
7315
7316       /* If we called start_enum or pushtag above, this information
7317          will already be set up.  */
7318       if (!TYPE_NAME (t))
7319         {
7320           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7321
7322           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7323           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7324           DECL_SOURCE_LOCATION (type_decl)
7325             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7326         }
7327       else
7328         type_decl = TYPE_NAME (t);
7329
7330       TREE_PRIVATE (type_decl)
7331         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7332       TREE_PROTECTED (type_decl)
7333         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7334       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7335         {
7336           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7337           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7338         }
7339
7340       /* Let's consider the explicit specialization of a member
7341          of a class template specialization that is implicitely instantiated,
7342          e.g.:
7343              template<class T>
7344              struct S
7345              {
7346                template<class U> struct M {}; //#0
7347              };
7348
7349              template<>
7350              template<>
7351              struct S<int>::M<char> //#1
7352              {
7353                int i;
7354              };
7355         [temp.expl.spec]/4 says this is valid.
7356
7357         In this case, when we write:
7358         S<int>::M<char> m;
7359
7360         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7361         the one of #0.
7362
7363         When we encounter #1, we want to store the partial instantiation
7364         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7365
7366         For all cases other than this "explicit specialization of member of a
7367         class template", we just want to store the most general template into
7368         the CLASSTYPE_TI_TEMPLATE of M.
7369
7370         This case of "explicit specialization of member of a class template"
7371         only happens when:
7372         1/ the enclosing class is an instantiation of, and therefore not
7373         the same as, the context of the most general template, and
7374         2/ we aren't looking at the partial instantiation itself, i.e.
7375         the innermost arguments are not the same as the innermost parms of
7376         the most general template.
7377
7378         So it's only when 1/ and 2/ happens that we want to use the partial
7379         instantiation of the member template in lieu of its most general
7380         template.  */
7381
7382       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7383           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7384           /* the enclosing class must be an instantiation...  */
7385           && CLASS_TYPE_P (context)
7386           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7387         {
7388           tree partial_inst_args;
7389           TREE_VEC_LENGTH (arglist)--;
7390           ++processing_template_decl;
7391           partial_inst_args =
7392             tsubst (INNERMOST_TEMPLATE_ARGS
7393                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7394                     arglist, complain, NULL_TREE);
7395           --processing_template_decl;
7396           TREE_VEC_LENGTH (arglist)++;
7397           use_partial_inst_tmpl =
7398             /*...and we must not be looking at the partial instantiation
7399              itself. */
7400             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7401                                  partial_inst_args);
7402         }
7403
7404       if (!use_partial_inst_tmpl)
7405         /* This case is easy; there are no member templates involved.  */
7406         found = gen_tmpl;
7407       else
7408         {
7409           /* This is a full instantiation of a member template.  Find
7410              the partial instantiation of which this is an instance.  */
7411
7412           /* Temporarily reduce by one the number of levels in the ARGLIST
7413              so as to avoid comparing the last set of arguments.  */
7414           TREE_VEC_LENGTH (arglist)--;
7415           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7416           TREE_VEC_LENGTH (arglist)++;
7417           found = CLASSTYPE_TI_TEMPLATE (found);
7418         }
7419
7420       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7421
7422       elt.spec = t;
7423       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7424                                                        &elt, hash, INSERT);
7425       *slot = ggc_alloc_spec_entry ();
7426       **slot = elt;
7427
7428       /* Note this use of the partial instantiation so we can check it
7429          later in maybe_process_partial_specialization.  */
7430       DECL_TEMPLATE_INSTANTIATIONS (templ)
7431         = tree_cons (arglist, t,
7432                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7433
7434       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7435         /* Now that the type has been registered on the instantiations
7436            list, we set up the enumerators.  Because the enumeration
7437            constants may involve the enumeration type itself, we make
7438            sure to register the type first, and then create the
7439            constants.  That way, doing tsubst_expr for the enumeration
7440            constants won't result in recursive calls here; we'll find
7441            the instantiation and exit above.  */
7442         tsubst_enum (template_type, t, arglist);
7443
7444       if (is_dependent_type)
7445         /* If the type makes use of template parameters, the
7446            code that generates debugging information will crash.  */
7447         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7448
7449       /* Possibly limit visibility based on template args.  */
7450       TREE_PUBLIC (type_decl) = 1;
7451       determine_visibility (type_decl);
7452
7453       return t;
7454     }
7455 }
7456
7457 /* Wrapper for lookup_template_class_1.  */
7458
7459 tree
7460 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7461                        int entering_scope, tsubst_flags_t complain)
7462 {
7463   tree ret;
7464   timevar_push (TV_TEMPLATE_INST);
7465   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7466                                  entering_scope, complain);
7467   timevar_pop (TV_TEMPLATE_INST);
7468   return ret;
7469 }
7470 \f
7471 struct pair_fn_data
7472 {
7473   tree_fn_t fn;
7474   void *data;
7475   /* True when we should also visit template parameters that occur in
7476      non-deduced contexts.  */
7477   bool include_nondeduced_p;
7478   struct pointer_set_t *visited;
7479 };
7480
7481 /* Called from for_each_template_parm via walk_tree.  */
7482
7483 static tree
7484 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7485 {
7486   tree t = *tp;
7487   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7488   tree_fn_t fn = pfd->fn;
7489   void *data = pfd->data;
7490
7491   if (TYPE_P (t)
7492       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7493       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7494                                  pfd->include_nondeduced_p))
7495     return error_mark_node;
7496
7497   switch (TREE_CODE (t))
7498     {
7499     case RECORD_TYPE:
7500       if (TYPE_PTRMEMFUNC_P (t))
7501         break;
7502       /* Fall through.  */
7503
7504     case UNION_TYPE:
7505     case ENUMERAL_TYPE:
7506       if (!TYPE_TEMPLATE_INFO (t))
7507         *walk_subtrees = 0;
7508       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7509                                        fn, data, pfd->visited, 
7510                                        pfd->include_nondeduced_p))
7511         return error_mark_node;
7512       break;
7513
7514     case INTEGER_TYPE:
7515       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7516                                   fn, data, pfd->visited, 
7517                                   pfd->include_nondeduced_p)
7518           || for_each_template_parm (TYPE_MAX_VALUE (t),
7519                                      fn, data, pfd->visited,
7520                                      pfd->include_nondeduced_p))
7521         return error_mark_node;
7522       break;
7523
7524     case METHOD_TYPE:
7525       /* Since we're not going to walk subtrees, we have to do this
7526          explicitly here.  */
7527       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7528                                   pfd->visited, pfd->include_nondeduced_p))
7529         return error_mark_node;
7530       /* Fall through.  */
7531
7532     case FUNCTION_TYPE:
7533       /* Check the return type.  */
7534       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7535                                   pfd->include_nondeduced_p))
7536         return error_mark_node;
7537
7538       /* Check the parameter types.  Since default arguments are not
7539          instantiated until they are needed, the TYPE_ARG_TYPES may
7540          contain expressions that involve template parameters.  But,
7541          no-one should be looking at them yet.  And, once they're
7542          instantiated, they don't contain template parameters, so
7543          there's no point in looking at them then, either.  */
7544       {
7545         tree parm;
7546
7547         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7548           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7549                                       pfd->visited, pfd->include_nondeduced_p))
7550             return error_mark_node;
7551
7552         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7553            want walk_tree walking into them itself.  */
7554         *walk_subtrees = 0;
7555       }
7556       break;
7557
7558     case TYPEOF_TYPE:
7559     case UNDERLYING_TYPE:
7560       if (pfd->include_nondeduced_p
7561           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7562                                      pfd->visited, 
7563                                      pfd->include_nondeduced_p))
7564         return error_mark_node;
7565       break;
7566
7567     case FUNCTION_DECL:
7568     case VAR_DECL:
7569       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7570           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7571                                      pfd->visited, pfd->include_nondeduced_p))
7572         return error_mark_node;
7573       /* Fall through.  */
7574
7575     case PARM_DECL:
7576     case CONST_DECL:
7577       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7578           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7579                                      pfd->visited, pfd->include_nondeduced_p))
7580         return error_mark_node;
7581       if (DECL_CONTEXT (t)
7582           && pfd->include_nondeduced_p
7583           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7584                                      pfd->visited, pfd->include_nondeduced_p))
7585         return error_mark_node;
7586       break;
7587
7588     case BOUND_TEMPLATE_TEMPLATE_PARM:
7589       /* Record template parameters such as `T' inside `TT<T>'.  */
7590       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7591                                   pfd->include_nondeduced_p))
7592         return error_mark_node;
7593       /* Fall through.  */
7594
7595     case TEMPLATE_TEMPLATE_PARM:
7596     case TEMPLATE_TYPE_PARM:
7597     case TEMPLATE_PARM_INDEX:
7598       if (fn && (*fn)(t, data))
7599         return error_mark_node;
7600       else if (!fn)
7601         return error_mark_node;
7602       break;
7603
7604     case TEMPLATE_DECL:
7605       /* A template template parameter is encountered.  */
7606       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7607           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7608                                      pfd->include_nondeduced_p))
7609         return error_mark_node;
7610
7611       /* Already substituted template template parameter */
7612       *walk_subtrees = 0;
7613       break;
7614
7615     case TYPENAME_TYPE:
7616       if (!fn
7617           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7618                                      data, pfd->visited, 
7619                                      pfd->include_nondeduced_p))
7620         return error_mark_node;
7621       break;
7622
7623     case CONSTRUCTOR:
7624       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7625           && pfd->include_nondeduced_p
7626           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7627                                      (TREE_TYPE (t)), fn, data,
7628                                      pfd->visited, pfd->include_nondeduced_p))
7629         return error_mark_node;
7630       break;
7631
7632     case INDIRECT_REF:
7633     case COMPONENT_REF:
7634       /* If there's no type, then this thing must be some expression
7635          involving template parameters.  */
7636       if (!fn && !TREE_TYPE (t))
7637         return error_mark_node;
7638       break;
7639
7640     case MODOP_EXPR:
7641     case CAST_EXPR:
7642     case REINTERPRET_CAST_EXPR:
7643     case CONST_CAST_EXPR:
7644     case STATIC_CAST_EXPR:
7645     case DYNAMIC_CAST_EXPR:
7646     case ARROW_EXPR:
7647     case DOTSTAR_EXPR:
7648     case TYPEID_EXPR:
7649     case PSEUDO_DTOR_EXPR:
7650       if (!fn)
7651         return error_mark_node;
7652       break;
7653
7654     default:
7655       break;
7656     }
7657
7658   /* We didn't find any template parameters we liked.  */
7659   return NULL_TREE;
7660 }
7661
7662 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7663    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7664    call FN with the parameter and the DATA.
7665    If FN returns nonzero, the iteration is terminated, and
7666    for_each_template_parm returns 1.  Otherwise, the iteration
7667    continues.  If FN never returns a nonzero value, the value
7668    returned by for_each_template_parm is 0.  If FN is NULL, it is
7669    considered to be the function which always returns 1.
7670
7671    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7672    parameters that occur in non-deduced contexts.  When false, only
7673    visits those template parameters that can be deduced.  */
7674
7675 static int
7676 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7677                         struct pointer_set_t *visited,
7678                         bool include_nondeduced_p)
7679 {
7680   struct pair_fn_data pfd;
7681   int result;
7682
7683   /* Set up.  */
7684   pfd.fn = fn;
7685   pfd.data = data;
7686   pfd.include_nondeduced_p = include_nondeduced_p;
7687
7688   /* Walk the tree.  (Conceptually, we would like to walk without
7689      duplicates, but for_each_template_parm_r recursively calls
7690      for_each_template_parm, so we would need to reorganize a fair
7691      bit to use walk_tree_without_duplicates, so we keep our own
7692      visited list.)  */
7693   if (visited)
7694     pfd.visited = visited;
7695   else
7696     pfd.visited = pointer_set_create ();
7697   result = cp_walk_tree (&t,
7698                          for_each_template_parm_r,
7699                          &pfd,
7700                          pfd.visited) != NULL_TREE;
7701
7702   /* Clean up.  */
7703   if (!visited)
7704     {
7705       pointer_set_destroy (pfd.visited);
7706       pfd.visited = 0;
7707     }
7708
7709   return result;
7710 }
7711
7712 /* Returns true if T depends on any template parameter.  */
7713
7714 int
7715 uses_template_parms (tree t)
7716 {
7717   bool dependent_p;
7718   int saved_processing_template_decl;
7719
7720   saved_processing_template_decl = processing_template_decl;
7721   if (!saved_processing_template_decl)
7722     processing_template_decl = 1;
7723   if (TYPE_P (t))
7724     dependent_p = dependent_type_p (t);
7725   else if (TREE_CODE (t) == TREE_VEC)
7726     dependent_p = any_dependent_template_arguments_p (t);
7727   else if (TREE_CODE (t) == TREE_LIST)
7728     dependent_p = (uses_template_parms (TREE_VALUE (t))
7729                    || uses_template_parms (TREE_CHAIN (t)));
7730   else if (TREE_CODE (t) == TYPE_DECL)
7731     dependent_p = dependent_type_p (TREE_TYPE (t));
7732   else if (DECL_P (t)
7733            || EXPR_P (t)
7734            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7735            || TREE_CODE (t) == OVERLOAD
7736            || TREE_CODE (t) == BASELINK
7737            || TREE_CODE (t) == IDENTIFIER_NODE
7738            || TREE_CODE (t) == TRAIT_EXPR
7739            || TREE_CODE (t) == CONSTRUCTOR
7740            || CONSTANT_CLASS_P (t))
7741     dependent_p = (type_dependent_expression_p (t)
7742                    || value_dependent_expression_p (t));
7743   else
7744     {
7745       gcc_assert (t == error_mark_node);
7746       dependent_p = false;
7747     }
7748
7749   processing_template_decl = saved_processing_template_decl;
7750
7751   return dependent_p;
7752 }
7753
7754 /* Returns true if T depends on any template parameter with level LEVEL.  */
7755
7756 int
7757 uses_template_parms_level (tree t, int level)
7758 {
7759   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7760                                  /*include_nondeduced_p=*/true);
7761 }
7762
7763 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7764    ill-formed translation unit, i.e. a variable or function that isn't
7765    usable in a constant expression.  */
7766
7767 static inline bool
7768 neglectable_inst_p (tree d)
7769 {
7770   return (DECL_P (d)
7771           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7772                : decl_maybe_constant_var_p (d)));
7773 }
7774
7775 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7776    neglectable and instantiated from within an erroneous instantiation.  */
7777
7778 static bool
7779 limit_bad_template_recursion (tree decl)
7780 {
7781   struct tinst_level *lev = current_tinst_level;
7782   int errs = errorcount + sorrycount;
7783   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7784     return false;
7785
7786   for (; lev; lev = lev->next)
7787     if (neglectable_inst_p (lev->decl))
7788       break;
7789
7790   return (lev && errs > lev->errors);
7791 }
7792
7793 static int tinst_depth;
7794 extern int max_tinst_depth;
7795 #ifdef GATHER_STATISTICS
7796 int depth_reached;
7797 #endif
7798 static GTY(()) struct tinst_level *last_error_tinst_level;
7799
7800 /* We're starting to instantiate D; record the template instantiation context
7801    for diagnostics and to restore it later.  */
7802
7803 int
7804 push_tinst_level (tree d)
7805 {
7806   struct tinst_level *new_level;
7807
7808   if (tinst_depth >= max_tinst_depth)
7809     {
7810       last_error_tinst_level = current_tinst_level;
7811       if (TREE_CODE (d) == TREE_LIST)
7812         error ("template instantiation depth exceeds maximum of %d (use "
7813                "-ftemplate-depth= to increase the maximum) substituting %qS",
7814                max_tinst_depth, d);
7815       else
7816         error ("template instantiation depth exceeds maximum of %d (use "
7817                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7818                max_tinst_depth, d);
7819
7820       print_instantiation_context ();
7821
7822       return 0;
7823     }
7824
7825   /* If the current instantiation caused problems, don't let it instantiate
7826      anything else.  Do allow deduction substitution and decls usable in
7827      constant expressions.  */
7828   if (limit_bad_template_recursion (d))
7829     return 0;
7830
7831   new_level = ggc_alloc_tinst_level ();
7832   new_level->decl = d;
7833   new_level->locus = input_location;
7834   new_level->errors = errorcount+sorrycount;
7835   new_level->in_system_header_p = in_system_header;
7836   new_level->next = current_tinst_level;
7837   current_tinst_level = new_level;
7838
7839   ++tinst_depth;
7840 #ifdef GATHER_STATISTICS
7841   if (tinst_depth > depth_reached)
7842     depth_reached = tinst_depth;
7843 #endif
7844
7845   return 1;
7846 }
7847
7848 /* We're done instantiating this template; return to the instantiation
7849    context.  */
7850
7851 void
7852 pop_tinst_level (void)
7853 {
7854   /* Restore the filename and line number stashed away when we started
7855      this instantiation.  */
7856   input_location = current_tinst_level->locus;
7857   current_tinst_level = current_tinst_level->next;
7858   --tinst_depth;
7859 }
7860
7861 /* We're instantiating a deferred template; restore the template
7862    instantiation context in which the instantiation was requested, which
7863    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7864
7865 static tree
7866 reopen_tinst_level (struct tinst_level *level)
7867 {
7868   struct tinst_level *t;
7869
7870   tinst_depth = 0;
7871   for (t = level; t; t = t->next)
7872     ++tinst_depth;
7873
7874   current_tinst_level = level;
7875   pop_tinst_level ();
7876   if (current_tinst_level)
7877     current_tinst_level->errors = errorcount+sorrycount;
7878   return level->decl;
7879 }
7880
7881 /* Returns the TINST_LEVEL which gives the original instantiation
7882    context.  */
7883
7884 struct tinst_level *
7885 outermost_tinst_level (void)
7886 {
7887   struct tinst_level *level = current_tinst_level;
7888   if (level)
7889     while (level->next)
7890       level = level->next;
7891   return level;
7892 }
7893
7894 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7895
7896 bool
7897 parameter_of_template_p (tree parm, tree templ)
7898 {
7899   tree parms;
7900   int i;
7901
7902   if (!parm || !templ)
7903     return false;
7904
7905   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7906   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7907
7908   parms = DECL_TEMPLATE_PARMS (templ);
7909   parms = INNERMOST_TEMPLATE_PARMS (parms);
7910
7911   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7912     {
7913       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7914       if (parm == p
7915           || (DECL_INITIAL (parm)
7916               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7917         return true;
7918     }
7919
7920   return false;
7921 }
7922
7923 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7924    vector of template arguments, as for tsubst.
7925
7926    Returns an appropriate tsubst'd friend declaration.  */
7927
7928 static tree
7929 tsubst_friend_function (tree decl, tree args)
7930 {
7931   tree new_friend;
7932
7933   if (TREE_CODE (decl) == FUNCTION_DECL
7934       && DECL_TEMPLATE_INSTANTIATION (decl)
7935       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7936     /* This was a friend declared with an explicit template
7937        argument list, e.g.:
7938
7939        friend void f<>(T);
7940
7941        to indicate that f was a template instantiation, not a new
7942        function declaration.  Now, we have to figure out what
7943        instantiation of what template.  */
7944     {
7945       tree template_id, arglist, fns;
7946       tree new_args;
7947       tree tmpl;
7948       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7949
7950       /* Friend functions are looked up in the containing namespace scope.
7951          We must enter that scope, to avoid finding member functions of the
7952          current class with same name.  */
7953       push_nested_namespace (ns);
7954       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7955                          tf_warning_or_error, NULL_TREE,
7956                          /*integral_constant_expression_p=*/false);
7957       pop_nested_namespace (ns);
7958       arglist = tsubst (DECL_TI_ARGS (decl), args,
7959                         tf_warning_or_error, NULL_TREE);
7960       template_id = lookup_template_function (fns, arglist);
7961
7962       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7963       tmpl = determine_specialization (template_id, new_friend,
7964                                        &new_args,
7965                                        /*need_member_template=*/0,
7966                                        TREE_VEC_LENGTH (args),
7967                                        tsk_none);
7968       return instantiate_template (tmpl, new_args, tf_error);
7969     }
7970
7971   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7972
7973   /* The NEW_FRIEND will look like an instantiation, to the
7974      compiler, but is not an instantiation from the point of view of
7975      the language.  For example, we might have had:
7976
7977      template <class T> struct S {
7978        template <class U> friend void f(T, U);
7979      };
7980
7981      Then, in S<int>, template <class U> void f(int, U) is not an
7982      instantiation of anything.  */
7983   if (new_friend == error_mark_node)
7984     return error_mark_node;
7985
7986   DECL_USE_TEMPLATE (new_friend) = 0;
7987   if (TREE_CODE (decl) == TEMPLATE_DECL)
7988     {
7989       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7990       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7991         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7992     }
7993
7994   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7995      is not a template instantiation and should not be mangled like
7996      one.  Therefore, we forget the mangling here; we'll recompute it
7997      later if we need it.  */
7998   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7999     {
8000       SET_DECL_RTL (new_friend, NULL);
8001       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8002     }
8003
8004   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8005     {
8006       tree old_decl;
8007       tree new_friend_template_info;
8008       tree new_friend_result_template_info;
8009       tree ns;
8010       int  new_friend_is_defn;
8011
8012       /* We must save some information from NEW_FRIEND before calling
8013          duplicate decls since that function will free NEW_FRIEND if
8014          possible.  */
8015       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8016       new_friend_is_defn =
8017             (DECL_INITIAL (DECL_TEMPLATE_RESULT
8018                            (template_for_substitution (new_friend)))
8019              != NULL_TREE);
8020       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8021         {
8022           /* This declaration is a `primary' template.  */
8023           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8024
8025           new_friend_result_template_info
8026             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8027         }
8028       else
8029         new_friend_result_template_info = NULL_TREE;
8030
8031       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8032       if (new_friend_is_defn)
8033         DECL_INITIAL (new_friend) = error_mark_node;
8034
8035       /* Inside pushdecl_namespace_level, we will push into the
8036          current namespace. However, the friend function should go
8037          into the namespace of the template.  */
8038       ns = decl_namespace_context (new_friend);
8039       push_nested_namespace (ns);
8040       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8041       pop_nested_namespace (ns);
8042
8043       if (old_decl == error_mark_node)
8044         return error_mark_node;
8045
8046       if (old_decl != new_friend)
8047         {
8048           /* This new friend declaration matched an existing
8049              declaration.  For example, given:
8050
8051                template <class T> void f(T);
8052                template <class U> class C {
8053                  template <class T> friend void f(T) {}
8054                };
8055
8056              the friend declaration actually provides the definition
8057              of `f', once C has been instantiated for some type.  So,
8058              old_decl will be the out-of-class template declaration,
8059              while new_friend is the in-class definition.
8060
8061              But, if `f' was called before this point, the
8062              instantiation of `f' will have DECL_TI_ARGS corresponding
8063              to `T' but not to `U', references to which might appear
8064              in the definition of `f'.  Previously, the most general
8065              template for an instantiation of `f' was the out-of-class
8066              version; now it is the in-class version.  Therefore, we
8067              run through all specialization of `f', adding to their
8068              DECL_TI_ARGS appropriately.  In particular, they need a
8069              new set of outer arguments, corresponding to the
8070              arguments for this class instantiation.
8071
8072              The same situation can arise with something like this:
8073
8074                friend void f(int);
8075                template <class T> class C {
8076                  friend void f(T) {}
8077                };
8078
8079              when `C<int>' is instantiated.  Now, `f(int)' is defined
8080              in the class.  */
8081
8082           if (!new_friend_is_defn)
8083             /* On the other hand, if the in-class declaration does
8084                *not* provide a definition, then we don't want to alter
8085                existing definitions.  We can just leave everything
8086                alone.  */
8087             ;
8088           else
8089             {
8090               tree new_template = TI_TEMPLATE (new_friend_template_info);
8091               tree new_args = TI_ARGS (new_friend_template_info);
8092
8093               /* Overwrite whatever template info was there before, if
8094                  any, with the new template information pertaining to
8095                  the declaration.  */
8096               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8097
8098               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8099                 {
8100                   /* We should have called reregister_specialization in
8101                      duplicate_decls.  */
8102                   gcc_assert (retrieve_specialization (new_template,
8103                                                        new_args, 0)
8104                               == old_decl);
8105
8106                   /* Instantiate it if the global has already been used.  */
8107                   if (DECL_ODR_USED (old_decl))
8108                     instantiate_decl (old_decl, /*defer_ok=*/true,
8109                                       /*expl_inst_class_mem_p=*/false);
8110                 }
8111               else
8112                 {
8113                   tree t;
8114
8115                   /* Indicate that the old function template is a partial
8116                      instantiation.  */
8117                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8118                     = new_friend_result_template_info;
8119
8120                   gcc_assert (new_template
8121                               == most_general_template (new_template));
8122                   gcc_assert (new_template != old_decl);
8123
8124                   /* Reassign any specializations already in the hash table
8125                      to the new more general template, and add the
8126                      additional template args.  */
8127                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8128                        t != NULL_TREE;
8129                        t = TREE_CHAIN (t))
8130                     {
8131                       tree spec = TREE_VALUE (t);
8132                       spec_entry elt;
8133
8134                       elt.tmpl = old_decl;
8135                       elt.args = DECL_TI_ARGS (spec);
8136                       elt.spec = NULL_TREE;
8137
8138                       htab_remove_elt (decl_specializations, &elt);
8139
8140                       DECL_TI_ARGS (spec)
8141                         = add_outermost_template_args (new_args,
8142                                                        DECL_TI_ARGS (spec));
8143
8144                       register_specialization
8145                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8146
8147                     }
8148                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8149                 }
8150             }
8151
8152           /* The information from NEW_FRIEND has been merged into OLD_DECL
8153              by duplicate_decls.  */
8154           new_friend = old_decl;
8155         }
8156     }
8157   else
8158     {
8159       tree context = DECL_CONTEXT (new_friend);
8160       bool dependent_p;
8161
8162       /* In the code
8163            template <class T> class C {
8164              template <class U> friend void C1<U>::f (); // case 1
8165              friend void C2<T>::f ();                    // case 2
8166            };
8167          we only need to make sure CONTEXT is a complete type for
8168          case 2.  To distinguish between the two cases, we note that
8169          CONTEXT of case 1 remains dependent type after tsubst while
8170          this isn't true for case 2.  */
8171       ++processing_template_decl;
8172       dependent_p = dependent_type_p (context);
8173       --processing_template_decl;
8174
8175       if (!dependent_p
8176           && !complete_type_or_else (context, NULL_TREE))
8177         return error_mark_node;
8178
8179       if (COMPLETE_TYPE_P (context))
8180         {
8181           /* Check to see that the declaration is really present, and,
8182              possibly obtain an improved declaration.  */
8183           tree fn = check_classfn (context,
8184                                    new_friend, NULL_TREE);
8185
8186           if (fn)
8187             new_friend = fn;
8188         }
8189     }
8190
8191   return new_friend;
8192 }
8193
8194 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8195    template arguments, as for tsubst.
8196
8197    Returns an appropriate tsubst'd friend type or error_mark_node on
8198    failure.  */
8199
8200 static tree
8201 tsubst_friend_class (tree friend_tmpl, tree args)
8202 {
8203   tree friend_type;
8204   tree tmpl;
8205   tree context;
8206
8207   context = CP_DECL_CONTEXT (friend_tmpl);
8208
8209   if (context != global_namespace)
8210     {
8211       if (TREE_CODE (context) == NAMESPACE_DECL)
8212         push_nested_namespace (context);
8213       else
8214         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8215     }
8216
8217   /* Look for a class template declaration.  We look for hidden names
8218      because two friend declarations of the same template are the
8219      same.  For example, in:
8220
8221        struct A { 
8222          template <typename> friend class F;
8223        };
8224        template <typename> struct B { 
8225          template <typename> friend class F;
8226        };
8227
8228      both F templates are the same.  */
8229   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8230                            /*block_p=*/true, 0, 
8231                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8232
8233   /* But, if we don't find one, it might be because we're in a
8234      situation like this:
8235
8236        template <class T>
8237        struct S {
8238          template <class U>
8239          friend struct S;
8240        };
8241
8242      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8243      for `S<int>', not the TEMPLATE_DECL.  */
8244   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8245     {
8246       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8247       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8248     }
8249
8250   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8251     {
8252       /* The friend template has already been declared.  Just
8253          check to see that the declarations match, and install any new
8254          default parameters.  We must tsubst the default parameters,
8255          of course.  We only need the innermost template parameters
8256          because that is all that redeclare_class_template will look
8257          at.  */
8258       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8259           > TMPL_ARGS_DEPTH (args))
8260         {
8261           tree parms;
8262           location_t saved_input_location;
8263           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8264                                          args, tf_warning_or_error);
8265
8266           saved_input_location = input_location;
8267           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8268           redeclare_class_template (TREE_TYPE (tmpl), parms);
8269           input_location = saved_input_location;
8270           
8271         }
8272
8273       friend_type = TREE_TYPE (tmpl);
8274     }
8275   else
8276     {
8277       /* The friend template has not already been declared.  In this
8278          case, the instantiation of the template class will cause the
8279          injection of this template into the global scope.  */
8280       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8281       if (tmpl == error_mark_node)
8282         return error_mark_node;
8283
8284       /* The new TMPL is not an instantiation of anything, so we
8285          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8286          the new type because that is supposed to be the corresponding
8287          template decl, i.e., TMPL.  */
8288       DECL_USE_TEMPLATE (tmpl) = 0;
8289       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8290       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8291       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8292         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8293
8294       /* Inject this template into the global scope.  */
8295       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8296     }
8297
8298   if (context != global_namespace)
8299     {
8300       if (TREE_CODE (context) == NAMESPACE_DECL)
8301         pop_nested_namespace (context);
8302       else
8303         pop_nested_class ();
8304     }
8305
8306   return friend_type;
8307 }
8308
8309 /* Returns zero if TYPE cannot be completed later due to circularity.
8310    Otherwise returns one.  */
8311
8312 static int
8313 can_complete_type_without_circularity (tree type)
8314 {
8315   if (type == NULL_TREE || type == error_mark_node)
8316     return 0;
8317   else if (COMPLETE_TYPE_P (type))
8318     return 1;
8319   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8320     return can_complete_type_without_circularity (TREE_TYPE (type));
8321   else if (CLASS_TYPE_P (type)
8322            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8323     return 0;
8324   else
8325     return 1;
8326 }
8327
8328 /* Apply any attributes which had to be deferred until instantiation
8329    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8330    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8331
8332 static void
8333 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8334                                 tree args, tsubst_flags_t complain, tree in_decl)
8335 {
8336   tree last_dep = NULL_TREE;
8337   tree t;
8338   tree *p;
8339
8340   for (t = attributes; t; t = TREE_CHAIN (t))
8341     if (ATTR_IS_DEPENDENT (t))
8342       {
8343         last_dep = t;
8344         attributes = copy_list (attributes);
8345         break;
8346       }
8347
8348   if (DECL_P (*decl_p))
8349     {
8350       if (TREE_TYPE (*decl_p) == error_mark_node)
8351         return;
8352       p = &DECL_ATTRIBUTES (*decl_p);
8353     }
8354   else
8355     p = &TYPE_ATTRIBUTES (*decl_p);
8356
8357   if (last_dep)
8358     {
8359       tree late_attrs = NULL_TREE;
8360       tree *q = &late_attrs;
8361
8362       for (*p = attributes; *p; )
8363         {
8364           t = *p;
8365           if (ATTR_IS_DEPENDENT (t))
8366             {
8367               *p = TREE_CHAIN (t);
8368               TREE_CHAIN (t) = NULL_TREE;
8369               /* If the first attribute argument is an identifier, don't
8370                  pass it through tsubst.  Attributes like mode, format,
8371                  cleanup and several target specific attributes expect it
8372                  unmodified.  */
8373               if (TREE_VALUE (t)
8374                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8375                   && TREE_VALUE (TREE_VALUE (t))
8376                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8377                       == IDENTIFIER_NODE))
8378                 {
8379                   tree chain
8380                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8381                                    in_decl,
8382                                    /*integral_constant_expression_p=*/false);
8383                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8384                     TREE_VALUE (t)
8385                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8386                                    chain);
8387                 }
8388               else
8389                 TREE_VALUE (t)
8390                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8391                                  /*integral_constant_expression_p=*/false);
8392               *q = t;
8393               q = &TREE_CHAIN (t);
8394             }
8395           else
8396             p = &TREE_CHAIN (t);
8397         }
8398
8399       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8400     }
8401 }
8402
8403 /* Perform (or defer) access check for typedefs that were referenced
8404    from within the template TMPL code.
8405    This is a subroutine of instantiate_template and instantiate_class_template.
8406    TMPL is the template to consider and TARGS is the list of arguments of
8407    that template.  */
8408
8409 static void
8410 perform_typedefs_access_check (tree tmpl, tree targs)
8411 {
8412   location_t saved_location;
8413   int i;
8414   qualified_typedef_usage_t *iter;
8415
8416   if (!tmpl
8417       || (!CLASS_TYPE_P (tmpl)
8418           && TREE_CODE (tmpl) != FUNCTION_DECL))
8419     return;
8420
8421   saved_location = input_location;
8422   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8423                     get_types_needing_access_check (tmpl),
8424                     i, iter)
8425     {
8426       tree type_decl = iter->typedef_decl;
8427       tree type_scope = iter->context;
8428
8429       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8430         continue;
8431
8432       if (uses_template_parms (type_decl))
8433         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8434       if (uses_template_parms (type_scope))
8435         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8436
8437       /* Make access check error messages point to the location
8438          of the use of the typedef.  */
8439       input_location = iter->locus;
8440       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8441                                      type_decl, type_decl);
8442     }
8443     input_location = saved_location;
8444 }
8445
8446 static tree
8447 instantiate_class_template_1 (tree type)
8448 {
8449   tree templ, args, pattern, t, member;
8450   tree typedecl;
8451   tree pbinfo;
8452   tree base_list;
8453   unsigned int saved_maximum_field_alignment;
8454
8455   if (type == error_mark_node)
8456     return error_mark_node;
8457
8458   if (COMPLETE_OR_OPEN_TYPE_P (type)
8459       || uses_template_parms (type))
8460     return type;
8461
8462   /* Figure out which template is being instantiated.  */
8463   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8464   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8465
8466   /* Determine what specialization of the original template to
8467      instantiate.  */
8468   t = most_specialized_class (type, templ, tf_warning_or_error);
8469   if (t == error_mark_node)
8470     {
8471       TYPE_BEING_DEFINED (type) = 1;
8472       return error_mark_node;
8473     }
8474   else if (t)
8475     {
8476       /* This TYPE is actually an instantiation of a partial
8477          specialization.  We replace the innermost set of ARGS with
8478          the arguments appropriate for substitution.  For example,
8479          given:
8480
8481            template <class T> struct S {};
8482            template <class T> struct S<T*> {};
8483
8484          and supposing that we are instantiating S<int*>, ARGS will
8485          presently be {int*} -- but we need {int}.  */
8486       pattern = TREE_TYPE (t);
8487       args = TREE_PURPOSE (t);
8488     }
8489   else
8490     {
8491       pattern = TREE_TYPE (templ);
8492       args = CLASSTYPE_TI_ARGS (type);
8493     }
8494
8495   /* If the template we're instantiating is incomplete, then clearly
8496      there's nothing we can do.  */
8497   if (!COMPLETE_TYPE_P (pattern))
8498     return type;
8499
8500   /* If we've recursively instantiated too many templates, stop.  */
8501   if (! push_tinst_level (type))
8502     return type;
8503
8504   /* Now we're really doing the instantiation.  Mark the type as in
8505      the process of being defined.  */
8506   TYPE_BEING_DEFINED (type) = 1;
8507
8508   /* We may be in the middle of deferred access check.  Disable
8509      it now.  */
8510   push_deferring_access_checks (dk_no_deferred);
8511
8512   push_to_top_level ();
8513   /* Use #pragma pack from the template context.  */
8514   saved_maximum_field_alignment = maximum_field_alignment;
8515   maximum_field_alignment = TYPE_PRECISION (pattern);
8516
8517   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8518
8519   /* Set the input location to the most specialized template definition.
8520      This is needed if tsubsting causes an error.  */
8521   typedecl = TYPE_MAIN_DECL (pattern);
8522   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8523     DECL_SOURCE_LOCATION (typedecl);
8524
8525   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8526   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8527   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8528   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8529   if (ANON_AGGR_TYPE_P (pattern))
8530     SET_ANON_AGGR_TYPE_P (type);
8531   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8532     {
8533       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8534       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8535     }
8536   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8537
8538   pbinfo = TYPE_BINFO (pattern);
8539
8540   /* We should never instantiate a nested class before its enclosing
8541      class; we need to look up the nested class by name before we can
8542      instantiate it, and that lookup should instantiate the enclosing
8543      class.  */
8544   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8545               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8546
8547   base_list = NULL_TREE;
8548   if (BINFO_N_BASE_BINFOS (pbinfo))
8549     {
8550       tree pbase_binfo;
8551       tree pushed_scope;
8552       int i;
8553
8554       /* We must enter the scope containing the type, as that is where
8555          the accessibility of types named in dependent bases are
8556          looked up from.  */
8557       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8558
8559       /* Substitute into each of the bases to determine the actual
8560          basetypes.  */
8561       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8562         {
8563           tree base;
8564           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8565           tree expanded_bases = NULL_TREE;
8566           int idx, len = 1;
8567
8568           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8569             {
8570               expanded_bases = 
8571                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8572                                        args, tf_error, NULL_TREE);
8573               if (expanded_bases == error_mark_node)
8574                 continue;
8575
8576               len = TREE_VEC_LENGTH (expanded_bases);
8577             }
8578
8579           for (idx = 0; idx < len; idx++)
8580             {
8581               if (expanded_bases)
8582                 /* Extract the already-expanded base class.  */
8583                 base = TREE_VEC_ELT (expanded_bases, idx);
8584               else
8585                 /* Substitute to figure out the base class.  */
8586                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8587                                NULL_TREE);
8588
8589               if (base == error_mark_node)
8590                 continue;
8591
8592               base_list = tree_cons (access, base, base_list);
8593               if (BINFO_VIRTUAL_P (pbase_binfo))
8594                 TREE_TYPE (base_list) = integer_type_node;
8595             }
8596         }
8597
8598       /* The list is now in reverse order; correct that.  */
8599       base_list = nreverse (base_list);
8600
8601       if (pushed_scope)
8602         pop_scope (pushed_scope);
8603     }
8604   /* Now call xref_basetypes to set up all the base-class
8605      information.  */
8606   xref_basetypes (type, base_list);
8607
8608   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8609                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8610                                   args, tf_error, NULL_TREE);
8611   fixup_attribute_variants (type);
8612
8613   /* Now that our base classes are set up, enter the scope of the
8614      class, so that name lookups into base classes, etc. will work
8615      correctly.  This is precisely analogous to what we do in
8616      begin_class_definition when defining an ordinary non-template
8617      class, except we also need to push the enclosing classes.  */
8618   push_nested_class (type);
8619
8620   /* Now members are processed in the order of declaration.  */
8621   for (member = CLASSTYPE_DECL_LIST (pattern);
8622        member; member = TREE_CHAIN (member))
8623     {
8624       tree t = TREE_VALUE (member);
8625
8626       if (TREE_PURPOSE (member))
8627         {
8628           if (TYPE_P (t))
8629             {
8630               /* Build new CLASSTYPE_NESTED_UTDS.  */
8631
8632               tree newtag;
8633               bool class_template_p;
8634
8635               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8636                                   && TYPE_LANG_SPECIFIC (t)
8637                                   && CLASSTYPE_IS_TEMPLATE (t));
8638               /* If the member is a class template, then -- even after
8639                  substitution -- there may be dependent types in the
8640                  template argument list for the class.  We increment
8641                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8642                  that function will assume that no types are dependent
8643                  when outside of a template.  */
8644               if (class_template_p)
8645                 ++processing_template_decl;
8646               newtag = tsubst (t, args, tf_error, NULL_TREE);
8647               if (class_template_p)
8648                 --processing_template_decl;
8649               if (newtag == error_mark_node)
8650                 continue;
8651
8652               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8653                 {
8654                   tree name = TYPE_IDENTIFIER (t);
8655
8656                   if (class_template_p)
8657                     /* Unfortunately, lookup_template_class sets
8658                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8659                        instantiation (i.e., for the type of a member
8660                        template class nested within a template class.)
8661                        This behavior is required for
8662                        maybe_process_partial_specialization to work
8663                        correctly, but is not accurate in this case;
8664                        the TAG is not an instantiation of anything.
8665                        (The corresponding TEMPLATE_DECL is an
8666                        instantiation, but the TYPE is not.) */
8667                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8668
8669                   /* Now, we call pushtag to put this NEWTAG into the scope of
8670                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8671                      pushtag calling push_template_decl.  We don't have to do
8672                      this for enums because it will already have been done in
8673                      tsubst_enum.  */
8674                   if (name)
8675                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8676                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8677                 }
8678             }
8679           else if (TREE_CODE (t) == FUNCTION_DECL
8680                    || DECL_FUNCTION_TEMPLATE_P (t))
8681             {
8682               /* Build new TYPE_METHODS.  */
8683               tree r;
8684
8685               if (TREE_CODE (t) == TEMPLATE_DECL)
8686                 ++processing_template_decl;
8687               r = tsubst (t, args, tf_error, NULL_TREE);
8688               if (TREE_CODE (t) == TEMPLATE_DECL)
8689                 --processing_template_decl;
8690               set_current_access_from_decl (r);
8691               finish_member_declaration (r);
8692               /* Instantiate members marked with attribute used.  */
8693               if (r != error_mark_node && DECL_PRESERVE_P (r))
8694                 mark_used (r);
8695             }
8696           else
8697             {
8698               /* Build new TYPE_FIELDS.  */
8699               if (TREE_CODE (t) == STATIC_ASSERT)
8700                 {
8701                   tree condition = 
8702                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8703                                  tf_warning_or_error, NULL_TREE,
8704                                  /*integral_constant_expression_p=*/true);
8705                   finish_static_assert (condition,
8706                                         STATIC_ASSERT_MESSAGE (t), 
8707                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8708                                         /*member_p=*/true);
8709                 }
8710               else if (TREE_CODE (t) != CONST_DECL)
8711                 {
8712                   tree r;
8713
8714                   /* The file and line for this declaration, to
8715                      assist in error message reporting.  Since we
8716                      called push_tinst_level above, we don't need to
8717                      restore these.  */
8718                   input_location = DECL_SOURCE_LOCATION (t);
8719
8720                   if (TREE_CODE (t) == TEMPLATE_DECL)
8721                     ++processing_template_decl;
8722                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8723                   if (TREE_CODE (t) == TEMPLATE_DECL)
8724                     --processing_template_decl;
8725                   if (TREE_CODE (r) == VAR_DECL)
8726                     {
8727                       /* In [temp.inst]:
8728
8729                            [t]he initialization (and any associated
8730                            side-effects) of a static data member does
8731                            not occur unless the static data member is
8732                            itself used in a way that requires the
8733                            definition of the static data member to
8734                            exist.
8735
8736                          Therefore, we do not substitute into the
8737                          initialized for the static data member here.  */
8738                       finish_static_data_member_decl
8739                         (r,
8740                          /*init=*/NULL_TREE,
8741                          /*init_const_expr_p=*/false,
8742                          /*asmspec_tree=*/NULL_TREE,
8743                          /*flags=*/0);
8744                       /* Instantiate members marked with attribute used.  */
8745                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8746                         mark_used (r);
8747                     }
8748                   else if (TREE_CODE (r) == FIELD_DECL)
8749                     {
8750                       /* Determine whether R has a valid type and can be
8751                          completed later.  If R is invalid, then it is
8752                          replaced by error_mark_node so that it will not be
8753                          added to TYPE_FIELDS.  */
8754                       tree rtype = TREE_TYPE (r);
8755                       if (can_complete_type_without_circularity (rtype))
8756                         complete_type (rtype);
8757
8758                       if (!COMPLETE_TYPE_P (rtype))
8759                         {
8760                           cxx_incomplete_type_error (r, rtype);
8761                           r = error_mark_node;
8762                         }
8763                     }
8764
8765                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8766                      such a thing will already have been added to the field
8767                      list by tsubst_enum in finish_member_declaration in the
8768                      CLASSTYPE_NESTED_UTDS case above.  */
8769                   if (!(TREE_CODE (r) == TYPE_DECL
8770                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8771                         && DECL_ARTIFICIAL (r)))
8772                     {
8773                       set_current_access_from_decl (r);
8774                       finish_member_declaration (r);
8775                     }
8776                 }
8777             }
8778         }
8779       else
8780         {
8781           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8782             {
8783               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8784
8785               tree friend_type = t;
8786               bool adjust_processing_template_decl = false;
8787
8788               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8789                 {
8790                   /* template <class T> friend class C;  */
8791                   friend_type = tsubst_friend_class (friend_type, args);
8792                   adjust_processing_template_decl = true;
8793                 }
8794               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8795                 {
8796                   /* template <class T> friend class C::D;  */
8797                   friend_type = tsubst (friend_type, args,
8798                                         tf_warning_or_error, NULL_TREE);
8799                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8800                     friend_type = TREE_TYPE (friend_type);
8801                   adjust_processing_template_decl = true;
8802                 }
8803               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8804                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8805                 {
8806                   /* This could be either
8807
8808                        friend class T::C;
8809
8810                      when dependent_type_p is false or
8811
8812                        template <class U> friend class T::C;
8813
8814                      otherwise.  */
8815                   friend_type = tsubst (friend_type, args,
8816                                         tf_warning_or_error, NULL_TREE);
8817                   /* Bump processing_template_decl for correct
8818                      dependent_type_p calculation.  */
8819                   ++processing_template_decl;
8820                   if (dependent_type_p (friend_type))
8821                     adjust_processing_template_decl = true;
8822                   --processing_template_decl;
8823                 }
8824               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8825                        && hidden_name_p (TYPE_NAME (friend_type)))
8826                 {
8827                   /* friend class C;
8828
8829                      where C hasn't been declared yet.  Let's lookup name
8830                      from namespace scope directly, bypassing any name that
8831                      come from dependent base class.  */
8832                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8833
8834                   /* The call to xref_tag_from_type does injection for friend
8835                      classes.  */
8836                   push_nested_namespace (ns);
8837                   friend_type =
8838                     xref_tag_from_type (friend_type, NULL_TREE,
8839                                         /*tag_scope=*/ts_current);
8840                   pop_nested_namespace (ns);
8841                 }
8842               else if (uses_template_parms (friend_type))
8843                 /* friend class C<T>;  */
8844                 friend_type = tsubst (friend_type, args,
8845                                       tf_warning_or_error, NULL_TREE);
8846               /* Otherwise it's
8847
8848                    friend class C;
8849
8850                  where C is already declared or
8851
8852                    friend class C<int>;
8853
8854                  We don't have to do anything in these cases.  */
8855
8856               if (adjust_processing_template_decl)
8857                 /* Trick make_friend_class into realizing that the friend
8858                    we're adding is a template, not an ordinary class.  It's
8859                    important that we use make_friend_class since it will
8860                    perform some error-checking and output cross-reference
8861                    information.  */
8862                 ++processing_template_decl;
8863
8864               if (friend_type != error_mark_node)
8865                 make_friend_class (type, friend_type, /*complain=*/false);
8866
8867               if (adjust_processing_template_decl)
8868                 --processing_template_decl;
8869             }
8870           else
8871             {
8872               /* Build new DECL_FRIENDLIST.  */
8873               tree r;
8874
8875               /* The file and line for this declaration, to
8876                  assist in error message reporting.  Since we
8877                  called push_tinst_level above, we don't need to
8878                  restore these.  */
8879               input_location = DECL_SOURCE_LOCATION (t);
8880
8881               if (TREE_CODE (t) == TEMPLATE_DECL)
8882                 {
8883                   ++processing_template_decl;
8884                   push_deferring_access_checks (dk_no_check);
8885                 }
8886
8887               r = tsubst_friend_function (t, args);
8888               add_friend (type, r, /*complain=*/false);
8889               if (TREE_CODE (t) == TEMPLATE_DECL)
8890                 {
8891                   pop_deferring_access_checks ();
8892                   --processing_template_decl;
8893                 }
8894             }
8895         }
8896     }
8897
8898   if (CLASSTYPE_LAMBDA_EXPR (type))
8899     {
8900       tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8901       if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8902         {
8903           apply_lambda_return_type (lambda, void_type_node);
8904           LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8905         }
8906       instantiate_decl (lambda_function (type), false, false);
8907       maybe_add_lambda_conv_op (type);
8908     }
8909
8910   /* Set the file and line number information to whatever is given for
8911      the class itself.  This puts error messages involving generated
8912      implicit functions at a predictable point, and the same point
8913      that would be used for non-template classes.  */
8914   input_location = DECL_SOURCE_LOCATION (typedecl);
8915
8916   unreverse_member_declarations (type);
8917   finish_struct_1 (type);
8918   TYPE_BEING_DEFINED (type) = 0;
8919
8920   /* We don't instantiate default arguments for member functions.  14.7.1:
8921
8922      The implicit instantiation of a class template specialization causes
8923      the implicit instantiation of the declarations, but not of the
8924      definitions or default arguments, of the class member functions,
8925      member classes, static data members and member templates....  */
8926
8927   /* Some typedefs referenced from within the template code need to be access
8928      checked at template instantiation time, i.e now. These types were
8929      added to the template at parsing time. Let's get those and perform
8930      the access checks then.  */
8931   perform_typedefs_access_check (pattern, args);
8932   perform_deferred_access_checks ();
8933   pop_nested_class ();
8934   maximum_field_alignment = saved_maximum_field_alignment;
8935   pop_from_top_level ();
8936   pop_deferring_access_checks ();
8937   pop_tinst_level ();
8938
8939   /* The vtable for a template class can be emitted in any translation
8940      unit in which the class is instantiated.  When there is no key
8941      method, however, finish_struct_1 will already have added TYPE to
8942      the keyed_classes list.  */
8943   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8944     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8945
8946   return type;
8947 }
8948
8949 /* Wrapper for instantiate_class_template_1.  */
8950
8951 tree
8952 instantiate_class_template (tree type)
8953 {
8954   tree ret;
8955   timevar_push (TV_TEMPLATE_INST);
8956   ret = instantiate_class_template_1 (type);
8957   timevar_pop (TV_TEMPLATE_INST);
8958   return ret;
8959 }
8960
8961 static tree
8962 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8963 {
8964   tree r;
8965
8966   if (!t)
8967     r = t;
8968   else if (TYPE_P (t))
8969     r = tsubst (t, args, complain, in_decl);
8970   else
8971     {
8972       if (!(complain & tf_warning))
8973         ++c_inhibit_evaluation_warnings;
8974       r = tsubst_expr (t, args, complain, in_decl,
8975                        /*integral_constant_expression_p=*/true);
8976       if (!(complain & tf_warning))
8977         --c_inhibit_evaluation_warnings;
8978       /* Preserve the raw-reference nature of T.  */
8979       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
8980           && REFERENCE_REF_P (r))
8981         r = TREE_OPERAND (r, 0);
8982     }
8983   return r;
8984 }
8985
8986 /* Given a function parameter pack TMPL_PARM and some function parameters
8987    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
8988    and set *SPEC_P to point at the next point in the list.  */
8989
8990 static tree
8991 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
8992 {
8993   /* Collect all of the extra "packed" parameters into an
8994      argument pack.  */
8995   tree parmvec;
8996   tree parmtypevec;
8997   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8998   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8999   tree spec_parm = *spec_p;
9000   int i, len;
9001
9002   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9003     if (tmpl_parm
9004         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9005       break;
9006
9007   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9008   parmvec = make_tree_vec (len);
9009   parmtypevec = make_tree_vec (len);
9010   spec_parm = *spec_p;
9011   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9012     {
9013       TREE_VEC_ELT (parmvec, i) = spec_parm;
9014       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9015     }
9016
9017   /* Build the argument packs.  */
9018   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9019   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9020   TREE_TYPE (argpack) = argtypepack;
9021   *spec_p = spec_parm;
9022
9023   return argpack;
9024 }
9025
9026 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9027    NONTYPE_ARGUMENT_PACK.  */
9028
9029 static tree
9030 make_fnparm_pack (tree spec_parm)
9031 {
9032   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9033 }
9034
9035 /* Substitute ARGS into T, which is an pack expansion
9036    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9037    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9038    (if only a partial substitution could be performed) or
9039    ERROR_MARK_NODE if there was an error.  */
9040 tree
9041 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9042                        tree in_decl)
9043 {
9044   tree pattern;
9045   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
9046   int i, len = -1;
9047   tree result;
9048   int incomplete = 0;
9049   htab_t saved_local_specializations = NULL;
9050
9051   gcc_assert (PACK_EXPANSION_P (t));
9052   pattern = PACK_EXPANSION_PATTERN (t);
9053
9054   /* Determine the argument packs that will instantiate the parameter
9055      packs used in the expansion expression. While we're at it,
9056      compute the number of arguments to be expanded and make sure it
9057      is consistent.  */
9058   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9059        pack = TREE_CHAIN (pack))
9060     {
9061       tree parm_pack = TREE_VALUE (pack);
9062       tree arg_pack = NULL_TREE;
9063       tree orig_arg = NULL_TREE;
9064
9065       if (TREE_CODE (parm_pack) == PARM_DECL)
9066         {
9067           if (!cp_unevaluated_operand)
9068             arg_pack = retrieve_local_specialization (parm_pack);
9069           else
9070             {
9071               /* We can't rely on local_specializations for a parameter
9072                  name used later in a function declaration (such as in a
9073                  late-specified return type).  Even if it exists, it might
9074                  have the wrong value for a recursive call.  Just make a
9075                  dummy decl, since it's only used for its type.  */
9076               arg_pack = tsubst_decl (parm_pack, args, complain);
9077               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9078                 /* Partial instantiation of the parm_pack, we can't build
9079                    up an argument pack yet.  */
9080                 arg_pack = NULL_TREE;
9081               else
9082                 arg_pack = make_fnparm_pack (arg_pack);
9083             }
9084         }
9085       else
9086         {
9087           int level, idx, levels;
9088           template_parm_level_and_index (parm_pack, &level, &idx);
9089
9090           levels = TMPL_ARGS_DEPTH (args);
9091           if (level <= levels)
9092             arg_pack = TMPL_ARG (args, level, idx);
9093         }
9094
9095       orig_arg = arg_pack;
9096       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9097         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9098       
9099       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9100         /* This can only happen if we forget to expand an argument
9101            pack somewhere else. Just return an error, silently.  */
9102         {
9103           result = make_tree_vec (1);
9104           TREE_VEC_ELT (result, 0) = error_mark_node;
9105           return result;
9106         }
9107
9108       /* For clarity in the comments below let's use the
9109          representation 'argument_pack<elements>' to denote an
9110          argument pack and its elements.
9111
9112          In the 'if' block below, we want to detect cases where
9113          ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
9114          check if ARG_PACK is an argument pack which sole element is
9115          the expansion of PARM_PACK.  That argument pack is typically
9116          created by template_parm_to_arg when passed a parameter
9117          pack.  */
9118       if (arg_pack
9119           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
9120           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
9121         {
9122           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
9123           tree pattern = PACK_EXPANSION_PATTERN (expansion);
9124           /* So we have an argument_pack<P...>.  We want to test if P
9125              is actually PARM_PACK.  We will not use cp_tree_equal to
9126              test P and PARM_PACK because during type fixup (by
9127              fixup_template_parm) P can be a pre-fixup version of a
9128              type and PARM_PACK be its post-fixup version.
9129              cp_tree_equal would consider them as different even
9130              though we would want to consider them compatible for our
9131              precise purpose here.
9132
9133              Thus we are going to consider that P and PARM_PACK are
9134              compatible if they have the same DECL.  */
9135           if ((/* If ARG_PACK is a type parameter pack named by the
9136                   same DECL as parm_pack ...  */
9137                (TYPE_P (pattern)
9138                 && TYPE_P (parm_pack)
9139                 && TYPE_NAME (pattern) == TYPE_NAME (parm_pack))
9140                /* ... or if ARG_PACK is a non-type parameter
9141                   named by the same DECL as parm_pack ...  */
9142                || (TREE_CODE (pattern) == TEMPLATE_PARM_INDEX
9143                    && TREE_CODE (parm_pack) == PARM_DECL
9144                    && TEMPLATE_PARM_DECL (pattern)
9145                    == TEMPLATE_PARM_DECL (DECL_INITIAL (parm_pack))))
9146               && template_parameter_pack_p (pattern))
9147             /* ... then the argument pack that the parameter maps to
9148                is just an expansion of the parameter itself, such as
9149                one would find in the implicit typedef of a class
9150                inside the class itself.  Consider this parameter
9151                "unsubstituted", so that we will maintain the outer
9152                pack expansion.  */
9153             arg_pack = NULL_TREE;
9154         }
9155           
9156       if (arg_pack)
9157         {
9158           int my_len = 
9159             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9160
9161           /* It's all-or-nothing with incomplete argument packs.  */
9162           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9163             return error_mark_node;
9164           
9165           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9166             incomplete = 1;
9167
9168           if (len < 0)
9169             len = my_len;
9170           else if (len != my_len)
9171             {
9172               if (incomplete)
9173                 /* We got explicit args for some packs but not others;
9174                    do nothing now and try again after deduction.  */
9175                 return t;
9176               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9177                 error ("mismatched argument pack lengths while expanding "
9178                        "%<%T%>",
9179                        pattern);
9180               else
9181                 error ("mismatched argument pack lengths while expanding "
9182                        "%<%E%>",
9183                        pattern);
9184               return error_mark_node;
9185             }
9186
9187           /* Keep track of the parameter packs and their corresponding
9188              argument packs.  */
9189           packs = tree_cons (parm_pack, arg_pack, packs);
9190           TREE_TYPE (packs) = orig_arg;
9191         }
9192       else
9193         /* We can't substitute for this parameter pack.  */
9194         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
9195                                          TREE_VALUE (pack),
9196                                          unsubstituted_packs);
9197     }
9198
9199   /* We cannot expand this expansion expression, because we don't have
9200      all of the argument packs we need. Substitute into the pattern
9201      and return a PACK_EXPANSION_*. The caller will need to deal with
9202      that.  */
9203   if (unsubstituted_packs)
9204     {
9205       tree new_pat;
9206       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9207         new_pat = tsubst_expr (pattern, args, complain, in_decl,
9208                                /*integral_constant_expression_p=*/false);
9209       else
9210         new_pat = tsubst (pattern, args, complain, in_decl);
9211       return make_pack_expansion (new_pat);
9212     }
9213
9214   /* We could not find any argument packs that work.  */
9215   if (len < 0)
9216     return error_mark_node;
9217
9218   if (cp_unevaluated_operand)
9219     {
9220       /* We're in a late-specified return type, so create our own local
9221          specializations table; the current table is either NULL or (in the
9222          case of recursive unification) might have bindings that we don't
9223          want to use or alter.  */
9224       saved_local_specializations = local_specializations;
9225       local_specializations = htab_create (37,
9226                                            hash_local_specialization,
9227                                            eq_local_specializations,
9228                                            NULL);
9229     }
9230
9231   /* For each argument in each argument pack, substitute into the
9232      pattern.  */
9233   result = make_tree_vec (len + incomplete);
9234   for (i = 0; i < len + incomplete; ++i)
9235     {
9236       /* For parameter pack, change the substitution of the parameter
9237          pack to the ith argument in its argument pack, then expand
9238          the pattern.  */
9239       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9240         {
9241           tree parm = TREE_PURPOSE (pack);
9242
9243           if (TREE_CODE (parm) == PARM_DECL)
9244             {
9245               /* Select the Ith argument from the pack.  */
9246               tree arg = make_node (ARGUMENT_PACK_SELECT);
9247               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9248               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9249               mark_used (parm);
9250               register_local_specialization (arg, parm);
9251             }
9252           else
9253             {
9254               tree value = parm;
9255               int idx, level;
9256               template_parm_level_and_index (parm, &level, &idx);
9257               
9258               if (i < len) 
9259                 {
9260                   /* Select the Ith argument from the pack. */
9261                   value = make_node (ARGUMENT_PACK_SELECT);
9262                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
9263                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
9264                 }
9265
9266               /* Update the corresponding argument.  */
9267               TMPL_ARG (args, level, idx) = value;
9268             }
9269         }
9270
9271       /* Substitute into the PATTERN with the altered arguments.  */
9272       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9273         TREE_VEC_ELT (result, i) = 
9274           tsubst_expr (pattern, args, complain, in_decl,
9275                        /*integral_constant_expression_p=*/false);
9276       else
9277         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9278
9279       if (i == len)
9280         /* When we have incomplete argument packs, the last "expanded"
9281            result is itself a pack expansion, which allows us
9282            to deduce more arguments.  */
9283         TREE_VEC_ELT (result, i) = 
9284           make_pack_expansion (TREE_VEC_ELT (result, i));
9285
9286       if (TREE_VEC_ELT (result, i) == error_mark_node)
9287         {
9288           result = error_mark_node;
9289           break;
9290         }
9291     }
9292
9293   /* Update ARGS to restore the substitution from parameter packs to
9294      their argument packs.  */
9295   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9296     {
9297       tree parm = TREE_PURPOSE (pack);
9298
9299       if (TREE_CODE (parm) == PARM_DECL)
9300         register_local_specialization (TREE_TYPE (pack), parm);
9301       else
9302         {
9303           int idx, level;
9304           template_parm_level_and_index (parm, &level, &idx);
9305           
9306           /* Update the corresponding argument.  */
9307           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9308             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9309               TREE_TYPE (pack);
9310           else
9311             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9312         }
9313     }
9314
9315   if (saved_local_specializations)
9316     {
9317       htab_delete (local_specializations);
9318       local_specializations = saved_local_specializations;
9319     }
9320   
9321   return result;
9322 }
9323
9324 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9325    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9326    parameter packs; all parms generated from a function parameter pack will
9327    have the same DECL_PARM_INDEX.  */
9328
9329 tree
9330 get_pattern_parm (tree parm, tree tmpl)
9331 {
9332   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9333   tree patparm;
9334
9335   if (DECL_ARTIFICIAL (parm))
9336     {
9337       for (patparm = DECL_ARGUMENTS (pattern);
9338            patparm; patparm = DECL_CHAIN (patparm))
9339         if (DECL_ARTIFICIAL (patparm)
9340             && DECL_NAME (parm) == DECL_NAME (patparm))
9341           break;
9342     }
9343   else
9344     {
9345       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9346       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9347       gcc_assert (DECL_PARM_INDEX (patparm)
9348                   == DECL_PARM_INDEX (parm));
9349     }
9350
9351   return patparm;
9352 }
9353
9354 /* Substitute ARGS into the vector or list of template arguments T.  */
9355
9356 static tree
9357 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9358 {
9359   tree orig_t = t;
9360   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9361   tree *elts;
9362
9363   if (t == error_mark_node)
9364     return error_mark_node;
9365
9366   len = TREE_VEC_LENGTH (t);
9367   elts = XALLOCAVEC (tree, len);
9368
9369   for (i = 0; i < len; i++)
9370     {
9371       tree orig_arg = TREE_VEC_ELT (t, i);
9372       tree new_arg;
9373
9374       if (TREE_CODE (orig_arg) == TREE_VEC)
9375         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9376       else if (PACK_EXPANSION_P (orig_arg))
9377         {
9378           /* Substitute into an expansion expression.  */
9379           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9380
9381           if (TREE_CODE (new_arg) == TREE_VEC)
9382             /* Add to the expanded length adjustment the number of
9383                expanded arguments. We subtract one from this
9384                measurement, because the argument pack expression
9385                itself is already counted as 1 in
9386                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9387                the argument pack is empty.  */
9388             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9389         }
9390       else if (ARGUMENT_PACK_P (orig_arg))
9391         {
9392           /* Substitute into each of the arguments.  */
9393           new_arg = TYPE_P (orig_arg)
9394             ? cxx_make_type (TREE_CODE (orig_arg))
9395             : make_node (TREE_CODE (orig_arg));
9396           
9397           SET_ARGUMENT_PACK_ARGS (
9398             new_arg,
9399             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9400                                   args, complain, in_decl));
9401
9402           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9403             new_arg = error_mark_node;
9404
9405           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9406             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9407                                           complain, in_decl);
9408             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9409
9410             if (TREE_TYPE (new_arg) == error_mark_node)
9411               new_arg = error_mark_node;
9412           }
9413         }
9414       else
9415         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9416
9417       if (new_arg == error_mark_node)
9418         return error_mark_node;
9419
9420       elts[i] = new_arg;
9421       if (new_arg != orig_arg)
9422         need_new = 1;
9423     }
9424
9425   if (!need_new)
9426     return t;
9427
9428   /* Make space for the expanded arguments coming from template
9429      argument packs.  */
9430   t = make_tree_vec (len + expanded_len_adjust);
9431   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9432      arguments for a member template.
9433      In that case each TREE_VEC in ORIG_T represents a level of template
9434      arguments, and ORIG_T won't carry any non defaulted argument count.
9435      It will rather be the nested TREE_VECs that will carry one.
9436      In other words, ORIG_T carries a non defaulted argument count only
9437      if it doesn't contain any nested TREE_VEC.  */
9438   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9439     {
9440       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9441       count += expanded_len_adjust;
9442       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9443     }
9444   for (i = 0, out = 0; i < len; i++)
9445     {
9446       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9447            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9448           && TREE_CODE (elts[i]) == TREE_VEC)
9449         {
9450           int idx;
9451
9452           /* Now expand the template argument pack "in place".  */
9453           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9454             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9455         }
9456       else
9457         {
9458           TREE_VEC_ELT (t, out) = elts[i];
9459           out++;
9460         }
9461     }
9462
9463   return t;
9464 }
9465
9466 /* Return the result of substituting ARGS into the template parameters
9467    given by PARMS.  If there are m levels of ARGS and m + n levels of
9468    PARMS, then the result will contain n levels of PARMS.  For
9469    example, if PARMS is `template <class T> template <class U>
9470    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9471    result will be `template <int*, double, class V>'.  */
9472
9473 static tree
9474 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9475 {
9476   tree r = NULL_TREE;
9477   tree* new_parms;
9478
9479   /* When substituting into a template, we must set
9480      PROCESSING_TEMPLATE_DECL as the template parameters may be
9481      dependent if they are based on one-another, and the dependency
9482      predicates are short-circuit outside of templates.  */
9483   ++processing_template_decl;
9484
9485   for (new_parms = &r;
9486        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9487        new_parms = &(TREE_CHAIN (*new_parms)),
9488          parms = TREE_CHAIN (parms))
9489     {
9490       tree new_vec =
9491         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9492       int i;
9493
9494       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9495         {
9496           tree tuple;
9497
9498           if (parms == error_mark_node)
9499             continue;
9500
9501           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9502
9503           if (tuple == error_mark_node)
9504             continue;
9505
9506           TREE_VEC_ELT (new_vec, i) =
9507             tsubst_template_parm (tuple, args, complain);
9508         }
9509
9510       *new_parms =
9511         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9512                              - TMPL_ARGS_DEPTH (args)),
9513                    new_vec, NULL_TREE);
9514     }
9515
9516   --processing_template_decl;
9517
9518   return r;
9519 }
9520
9521 /* Return the result of substituting ARGS into one template parameter
9522    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9523    parameter and which TREE_PURPOSE is the default argument of the
9524    template parameter.  */
9525
9526 static tree
9527 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9528 {
9529   tree default_value, parm_decl;
9530
9531   if (args == NULL_TREE
9532       || t == NULL_TREE
9533       || t == error_mark_node)
9534     return t;
9535
9536   gcc_assert (TREE_CODE (t) == TREE_LIST);
9537
9538   default_value = TREE_PURPOSE (t);
9539   parm_decl = TREE_VALUE (t);
9540
9541   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9542   if (TREE_CODE (parm_decl) == PARM_DECL
9543       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9544     parm_decl = error_mark_node;
9545   default_value = tsubst_template_arg (default_value, args,
9546                                        complain, NULL_TREE);
9547
9548   return build_tree_list (default_value, parm_decl);
9549 }
9550
9551 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9552    type T.  If T is not an aggregate or enumeration type, it is
9553    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9554    ENTERING_SCOPE is nonzero, T is the context for a template which
9555    we are presently tsubst'ing.  Return the substituted value.  */
9556
9557 static tree
9558 tsubst_aggr_type (tree t,
9559                   tree args,
9560                   tsubst_flags_t complain,
9561                   tree in_decl,
9562                   int entering_scope)
9563 {
9564   if (t == NULL_TREE)
9565     return NULL_TREE;
9566
9567   switch (TREE_CODE (t))
9568     {
9569     case RECORD_TYPE:
9570       if (TYPE_PTRMEMFUNC_P (t))
9571         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9572
9573       /* Else fall through.  */
9574     case ENUMERAL_TYPE:
9575     case UNION_TYPE:
9576       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9577         {
9578           tree argvec;
9579           tree context;
9580           tree r;
9581           int saved_unevaluated_operand;
9582           int saved_inhibit_evaluation_warnings;
9583
9584           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9585           saved_unevaluated_operand = cp_unevaluated_operand;
9586           cp_unevaluated_operand = 0;
9587           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9588           c_inhibit_evaluation_warnings = 0;
9589
9590           /* First, determine the context for the type we are looking
9591              up.  */
9592           context = TYPE_CONTEXT (t);
9593           if (context && TYPE_P (context))
9594             {
9595               context = tsubst_aggr_type (context, args, complain,
9596                                           in_decl, /*entering_scope=*/1);
9597               /* If context is a nested class inside a class template,
9598                  it may still need to be instantiated (c++/33959).  */
9599               context = complete_type (context);
9600             }
9601
9602           /* Then, figure out what arguments are appropriate for the
9603              type we are trying to find.  For example, given:
9604
9605                template <class T> struct S;
9606                template <class T, class U> void f(T, U) { S<U> su; }
9607
9608              and supposing that we are instantiating f<int, double>,
9609              then our ARGS will be {int, double}, but, when looking up
9610              S we only want {double}.  */
9611           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9612                                          complain, in_decl);
9613           if (argvec == error_mark_node)
9614             r = error_mark_node;
9615           else
9616             {
9617               r = lookup_template_class (t, argvec, in_decl, context,
9618                                          entering_scope, complain);
9619               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9620             }
9621
9622           cp_unevaluated_operand = saved_unevaluated_operand;
9623           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9624
9625           return r;
9626         }
9627       else
9628         /* This is not a template type, so there's nothing to do.  */
9629         return t;
9630
9631     default:
9632       return tsubst (t, args, complain, in_decl);
9633     }
9634 }
9635
9636 /* Substitute into the default argument ARG (a default argument for
9637    FN), which has the indicated TYPE.  */
9638
9639 tree
9640 tsubst_default_argument (tree fn, tree type, tree arg)
9641 {
9642   tree saved_class_ptr = NULL_TREE;
9643   tree saved_class_ref = NULL_TREE;
9644
9645   /* This can happen in invalid code.  */
9646   if (TREE_CODE (arg) == DEFAULT_ARG)
9647     return arg;
9648
9649   /* This default argument came from a template.  Instantiate the
9650      default argument here, not in tsubst.  In the case of
9651      something like:
9652
9653        template <class T>
9654        struct S {
9655          static T t();
9656          void f(T = t());
9657        };
9658
9659      we must be careful to do name lookup in the scope of S<T>,
9660      rather than in the current class.  */
9661   push_access_scope (fn);
9662   /* The "this" pointer is not valid in a default argument.  */
9663   if (cfun)
9664     {
9665       saved_class_ptr = current_class_ptr;
9666       cp_function_chain->x_current_class_ptr = NULL_TREE;
9667       saved_class_ref = current_class_ref;
9668       cp_function_chain->x_current_class_ref = NULL_TREE;
9669     }
9670
9671   push_deferring_access_checks(dk_no_deferred);
9672   /* The default argument expression may cause implicitly defined
9673      member functions to be synthesized, which will result in garbage
9674      collection.  We must treat this situation as if we were within
9675      the body of function so as to avoid collecting live data on the
9676      stack.  */
9677   ++function_depth;
9678   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9679                      tf_warning_or_error, NULL_TREE,
9680                      /*integral_constant_expression_p=*/false);
9681   --function_depth;
9682   pop_deferring_access_checks();
9683
9684   /* Restore the "this" pointer.  */
9685   if (cfun)
9686     {
9687       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9688       cp_function_chain->x_current_class_ref = saved_class_ref;
9689     }
9690
9691   /* Make sure the default argument is reasonable.  */
9692   arg = check_default_argument (type, arg);
9693
9694   pop_access_scope (fn);
9695
9696   return arg;
9697 }
9698
9699 /* Substitute into all the default arguments for FN.  */
9700
9701 static void
9702 tsubst_default_arguments (tree fn)
9703 {
9704   tree arg;
9705   tree tmpl_args;
9706
9707   tmpl_args = DECL_TI_ARGS (fn);
9708
9709   /* If this function is not yet instantiated, we certainly don't need
9710      its default arguments.  */
9711   if (uses_template_parms (tmpl_args))
9712     return;
9713   /* Don't do this again for clones.  */
9714   if (DECL_CLONED_FUNCTION_P (fn))
9715     return;
9716
9717   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9718        arg;
9719        arg = TREE_CHAIN (arg))
9720     if (TREE_PURPOSE (arg))
9721       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9722                                                     TREE_VALUE (arg),
9723                                                     TREE_PURPOSE (arg));
9724 }
9725
9726 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9727    result of the substitution.  Issue error and warning messages under
9728    control of COMPLAIN.  */
9729
9730 static tree
9731 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9732 {
9733 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9734   location_t saved_loc;
9735   tree r = NULL_TREE;
9736   tree in_decl = t;
9737   hashval_t hash = 0;
9738
9739   /* Set the filename and linenumber to improve error-reporting.  */
9740   saved_loc = input_location;
9741   input_location = DECL_SOURCE_LOCATION (t);
9742
9743   switch (TREE_CODE (t))
9744     {
9745     case TEMPLATE_DECL:
9746       {
9747         /* We can get here when processing a member function template,
9748            member class template, or template template parameter.  */
9749         tree decl = DECL_TEMPLATE_RESULT (t);
9750         tree spec;
9751         tree tmpl_args;
9752         tree full_args;
9753
9754         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9755           {
9756             /* Template template parameter is treated here.  */
9757             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9758             if (new_type == error_mark_node)
9759               RETURN (error_mark_node);
9760
9761             r = copy_decl (t);
9762             DECL_CHAIN (r) = NULL_TREE;
9763             TREE_TYPE (r) = new_type;
9764             DECL_TEMPLATE_RESULT (r)
9765               = build_decl (DECL_SOURCE_LOCATION (decl),
9766                             TYPE_DECL, DECL_NAME (decl), new_type);
9767             DECL_TEMPLATE_PARMS (r)
9768               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9769                                        complain);
9770             TYPE_NAME (new_type) = r;
9771             break;
9772           }
9773
9774         /* We might already have an instance of this template.
9775            The ARGS are for the surrounding class type, so the
9776            full args contain the tsubst'd args for the context,
9777            plus the innermost args from the template decl.  */
9778         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9779           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9780           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9781         /* Because this is a template, the arguments will still be
9782            dependent, even after substitution.  If
9783            PROCESSING_TEMPLATE_DECL is not set, the dependency
9784            predicates will short-circuit.  */
9785         ++processing_template_decl;
9786         full_args = tsubst_template_args (tmpl_args, args,
9787                                           complain, in_decl);
9788         --processing_template_decl;
9789         if (full_args == error_mark_node)
9790           RETURN (error_mark_node);
9791
9792         /* If this is a default template template argument,
9793            tsubst might not have changed anything.  */
9794         if (full_args == tmpl_args)
9795           RETURN (t);
9796
9797         hash = hash_tmpl_and_args (t, full_args);
9798         spec = retrieve_specialization (t, full_args, hash);
9799         if (spec != NULL_TREE)
9800           {
9801             r = spec;
9802             break;
9803           }
9804
9805         /* Make a new template decl.  It will be similar to the
9806            original, but will record the current template arguments.
9807            We also create a new function declaration, which is just
9808            like the old one, but points to this new template, rather
9809            than the old one.  */
9810         r = copy_decl (t);
9811         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9812         DECL_CHAIN (r) = NULL_TREE;
9813
9814         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9815
9816         if (TREE_CODE (decl) == TYPE_DECL)
9817           {
9818             tree new_type;
9819             ++processing_template_decl;
9820             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9821             --processing_template_decl;
9822             if (new_type == error_mark_node)
9823               RETURN (error_mark_node);
9824
9825             TREE_TYPE (r) = new_type;
9826             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9827             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9828             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9829             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9830           }
9831         else
9832           {
9833             tree new_decl;
9834             ++processing_template_decl;
9835             new_decl = tsubst (decl, args, complain, in_decl);
9836             --processing_template_decl;
9837             if (new_decl == error_mark_node)
9838               RETURN (error_mark_node);
9839
9840             DECL_TEMPLATE_RESULT (r) = new_decl;
9841             DECL_TI_TEMPLATE (new_decl) = r;
9842             TREE_TYPE (r) = TREE_TYPE (new_decl);
9843             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9844             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9845           }
9846
9847         SET_DECL_IMPLICIT_INSTANTIATION (r);
9848         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9849         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9850
9851         /* The template parameters for this new template are all the
9852            template parameters for the old template, except the
9853            outermost level of parameters.  */
9854         DECL_TEMPLATE_PARMS (r)
9855           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9856                                    complain);
9857
9858         if (PRIMARY_TEMPLATE_P (t))
9859           DECL_PRIMARY_TEMPLATE (r) = r;
9860
9861         if (TREE_CODE (decl) != TYPE_DECL)
9862           /* Record this non-type partial instantiation.  */
9863           register_specialization (r, t,
9864                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9865                                    false, hash);
9866       }
9867       break;
9868
9869     case FUNCTION_DECL:
9870       {
9871         tree ctx;
9872         tree argvec = NULL_TREE;
9873         tree *friends;
9874         tree gen_tmpl;
9875         tree type;
9876         int member;
9877         int args_depth;
9878         int parms_depth;
9879
9880         /* Nobody should be tsubst'ing into non-template functions.  */
9881         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9882
9883         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9884           {
9885             tree spec;
9886             bool dependent_p;
9887
9888             /* If T is not dependent, just return it.  We have to
9889                increment PROCESSING_TEMPLATE_DECL because
9890                value_dependent_expression_p assumes that nothing is
9891                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9892             ++processing_template_decl;
9893             dependent_p = value_dependent_expression_p (t);
9894             --processing_template_decl;
9895             if (!dependent_p)
9896               RETURN (t);
9897
9898             /* Calculate the most general template of which R is a
9899                specialization, and the complete set of arguments used to
9900                specialize R.  */
9901             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9902             argvec = tsubst_template_args (DECL_TI_ARGS
9903                                           (DECL_TEMPLATE_RESULT
9904                                                  (DECL_TI_TEMPLATE (t))),
9905                                            args, complain, in_decl);
9906             if (argvec == error_mark_node)
9907               RETURN (error_mark_node);
9908
9909             /* Check to see if we already have this specialization.  */
9910             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9911             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9912
9913             if (spec)
9914               {
9915                 r = spec;
9916                 break;
9917               }
9918
9919             /* We can see more levels of arguments than parameters if
9920                there was a specialization of a member template, like
9921                this:
9922
9923                  template <class T> struct S { template <class U> void f(); }
9924                  template <> template <class U> void S<int>::f(U);
9925
9926                Here, we'll be substituting into the specialization,
9927                because that's where we can find the code we actually
9928                want to generate, but we'll have enough arguments for
9929                the most general template.
9930
9931                We also deal with the peculiar case:
9932
9933                  template <class T> struct S {
9934                    template <class U> friend void f();
9935                  };
9936                  template <class U> void f() {}
9937                  template S<int>;
9938                  template void f<double>();
9939
9940                Here, the ARGS for the instantiation of will be {int,
9941                double}.  But, we only need as many ARGS as there are
9942                levels of template parameters in CODE_PATTERN.  We are
9943                careful not to get fooled into reducing the ARGS in
9944                situations like:
9945
9946                  template <class T> struct S { template <class U> void f(U); }
9947                  template <class T> template <> void S<T>::f(int) {}
9948
9949                which we can spot because the pattern will be a
9950                specialization in this case.  */
9951             args_depth = TMPL_ARGS_DEPTH (args);
9952             parms_depth =
9953               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9954             if (args_depth > parms_depth
9955                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9956               args = get_innermost_template_args (args, parms_depth);
9957           }
9958         else
9959           {
9960             /* This special case arises when we have something like this:
9961
9962                  template <class T> struct S {
9963                    friend void f<int>(int, double);
9964                  };
9965
9966                Here, the DECL_TI_TEMPLATE for the friend declaration
9967                will be an IDENTIFIER_NODE.  We are being called from
9968                tsubst_friend_function, and we want only to create a
9969                new decl (R) with appropriate types so that we can call
9970                determine_specialization.  */
9971             gen_tmpl = NULL_TREE;
9972           }
9973
9974         if (DECL_CLASS_SCOPE_P (t))
9975           {
9976             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9977               member = 2;
9978             else
9979               member = 1;
9980             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9981                                     complain, t, /*entering_scope=*/1);
9982           }
9983         else
9984           {
9985             member = 0;
9986             ctx = DECL_CONTEXT (t);
9987           }
9988         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9989         if (type == error_mark_node)
9990           RETURN (error_mark_node);
9991
9992         /* We do NOT check for matching decls pushed separately at this
9993            point, as they may not represent instantiations of this
9994            template, and in any case are considered separate under the
9995            discrete model.  */
9996         r = copy_decl (t);
9997         DECL_USE_TEMPLATE (r) = 0;
9998         TREE_TYPE (r) = type;
9999         /* Clear out the mangled name and RTL for the instantiation.  */
10000         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10001         SET_DECL_RTL (r, NULL);
10002         /* Leave DECL_INITIAL set on deleted instantiations.  */
10003         if (!DECL_DELETED_FN (r))
10004           DECL_INITIAL (r) = NULL_TREE;
10005         DECL_CONTEXT (r) = ctx;
10006
10007         if (member && DECL_CONV_FN_P (r))
10008           /* Type-conversion operator.  Reconstruct the name, in
10009              case it's the name of one of the template's parameters.  */
10010           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10011
10012         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10013                                      complain, t);
10014         DECL_RESULT (r) = NULL_TREE;
10015
10016         TREE_STATIC (r) = 0;
10017         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10018         DECL_EXTERNAL (r) = 1;
10019         /* If this is an instantiation of a function with internal
10020            linkage, we already know what object file linkage will be
10021            assigned to the instantiation.  */
10022         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10023         DECL_DEFER_OUTPUT (r) = 0;
10024         DECL_CHAIN (r) = NULL_TREE;
10025         DECL_PENDING_INLINE_INFO (r) = 0;
10026         DECL_PENDING_INLINE_P (r) = 0;
10027         DECL_SAVED_TREE (r) = NULL_TREE;
10028         DECL_STRUCT_FUNCTION (r) = NULL;
10029         TREE_USED (r) = 0;
10030         /* We'll re-clone as appropriate in instantiate_template.  */
10031         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10032
10033         /* If we aren't complaining now, return on error before we register
10034            the specialization so that we'll complain eventually.  */
10035         if ((complain & tf_error) == 0
10036             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10037             && !grok_op_properties (r, /*complain=*/false))
10038           RETURN (error_mark_node);
10039
10040         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10041            this in the special friend case mentioned above where
10042            GEN_TMPL is NULL.  */
10043         if (gen_tmpl)
10044           {
10045             DECL_TEMPLATE_INFO (r)
10046               = build_template_info (gen_tmpl, argvec);
10047             SET_DECL_IMPLICIT_INSTANTIATION (r);
10048             register_specialization (r, gen_tmpl, argvec, false, hash);
10049
10050             /* We're not supposed to instantiate default arguments
10051                until they are called, for a template.  But, for a
10052                declaration like:
10053
10054                  template <class T> void f ()
10055                  { extern void g(int i = T()); }
10056
10057                we should do the substitution when the template is
10058                instantiated.  We handle the member function case in
10059                instantiate_class_template since the default arguments
10060                might refer to other members of the class.  */
10061             if (!member
10062                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10063                 && !uses_template_parms (argvec))
10064               tsubst_default_arguments (r);
10065           }
10066         else
10067           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10068
10069         /* Copy the list of befriending classes.  */
10070         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10071              *friends;
10072              friends = &TREE_CHAIN (*friends))
10073           {
10074             *friends = copy_node (*friends);
10075             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10076                                             args, complain,
10077                                             in_decl);
10078           }
10079
10080         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10081           {
10082             maybe_retrofit_in_chrg (r);
10083             if (DECL_CONSTRUCTOR_P (r))
10084               grok_ctor_properties (ctx, r);
10085             /* If this is an instantiation of a member template, clone it.
10086                If it isn't, that'll be handled by
10087                clone_constructors_and_destructors.  */
10088             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10089               clone_function_decl (r, /*update_method_vec_p=*/0);
10090           }
10091         else if ((complain & tf_error) != 0
10092                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10093                  && !grok_op_properties (r, /*complain=*/true))
10094           RETURN (error_mark_node);
10095
10096         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10097           SET_DECL_FRIEND_CONTEXT (r,
10098                                    tsubst (DECL_FRIEND_CONTEXT (t),
10099                                             args, complain, in_decl));
10100
10101         /* Possibly limit visibility based on template args.  */
10102         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10103         if (DECL_VISIBILITY_SPECIFIED (t))
10104           {
10105             DECL_VISIBILITY_SPECIFIED (r) = 0;
10106             DECL_ATTRIBUTES (r)
10107               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10108           }
10109         determine_visibility (r);
10110         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10111             && !processing_template_decl)
10112           defaulted_late_check (r);
10113
10114         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10115                                         args, complain, in_decl);
10116       }
10117       break;
10118
10119     case PARM_DECL:
10120       {
10121         tree type = NULL_TREE;
10122         int i, len = 1;
10123         tree expanded_types = NULL_TREE;
10124         tree prev_r = NULL_TREE;
10125         tree first_r = NULL_TREE;
10126
10127         if (FUNCTION_PARAMETER_PACK_P (t))
10128           {
10129             /* If there is a local specialization that isn't a
10130                parameter pack, it means that we're doing a "simple"
10131                substitution from inside tsubst_pack_expansion. Just
10132                return the local specialization (which will be a single
10133                parm).  */
10134             tree spec = retrieve_local_specialization (t);
10135             if (spec 
10136                 && TREE_CODE (spec) == PARM_DECL
10137                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10138               RETURN (spec);
10139
10140             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10141                the parameters in this function parameter pack.  */
10142             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10143                                                     complain, in_decl);
10144             if (TREE_CODE (expanded_types) == TREE_VEC)
10145               {
10146                 len = TREE_VEC_LENGTH (expanded_types);
10147
10148                 /* Zero-length parameter packs are boring. Just substitute
10149                    into the chain.  */
10150                 if (len == 0)
10151                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10152                                   TREE_CHAIN (t)));
10153               }
10154             else
10155               {
10156                 /* All we did was update the type. Make a note of that.  */
10157                 type = expanded_types;
10158                 expanded_types = NULL_TREE;
10159               }
10160           }
10161
10162         /* Loop through all of the parameter's we'll build. When T is
10163            a function parameter pack, LEN is the number of expanded
10164            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10165         r = NULL_TREE;
10166         for (i = 0; i < len; ++i)
10167           {
10168             prev_r = r;
10169             r = copy_node (t);
10170             if (DECL_TEMPLATE_PARM_P (t))
10171               SET_DECL_TEMPLATE_PARM_P (r);
10172
10173             if (expanded_types)
10174               /* We're on the Ith parameter of the function parameter
10175                  pack.  */
10176               {
10177                 /* An argument of a function parameter pack is not a parameter
10178                    pack.  */
10179                 FUNCTION_PARAMETER_PACK_P (r) = false;
10180
10181                 /* Get the Ith type.  */
10182                 type = TREE_VEC_ELT (expanded_types, i);
10183
10184                 if (DECL_NAME (r))
10185                   /* Rename the parameter to include the index.  */
10186                   DECL_NAME (r) =
10187                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10188               }
10189             else if (!type)
10190               /* We're dealing with a normal parameter.  */
10191               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10192
10193             type = type_decays_to (type);
10194             TREE_TYPE (r) = type;
10195             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10196
10197             if (DECL_INITIAL (r))
10198               {
10199                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10200                   DECL_INITIAL (r) = TREE_TYPE (r);
10201                 else
10202                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10203                                              complain, in_decl);
10204               }
10205
10206             DECL_CONTEXT (r) = NULL_TREE;
10207
10208             if (!DECL_TEMPLATE_PARM_P (r))
10209               DECL_ARG_TYPE (r) = type_passed_as (type);
10210
10211             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10212                                             args, complain, in_decl);
10213
10214             /* Keep track of the first new parameter we
10215                generate. That's what will be returned to the
10216                caller.  */
10217             if (!first_r)
10218               first_r = r;
10219
10220             /* Build a proper chain of parameters when substituting
10221                into a function parameter pack.  */
10222             if (prev_r)
10223               DECL_CHAIN (prev_r) = r;
10224           }
10225
10226         if (DECL_CHAIN (t))
10227           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10228                                    complain, DECL_CHAIN (t));
10229
10230         /* FIRST_R contains the start of the chain we've built.  */
10231         r = first_r;
10232       }
10233       break;
10234
10235     case FIELD_DECL:
10236       {
10237         tree type;
10238
10239         r = copy_decl (t);
10240         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10241         if (type == error_mark_node)
10242           RETURN (error_mark_node);
10243         TREE_TYPE (r) = type;
10244         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10245
10246         /* DECL_INITIAL gives the number of bits in a bit-field.  */
10247         DECL_INITIAL (r)
10248           = tsubst_expr (DECL_INITIAL (t), args,
10249                          complain, in_decl,
10250                          /*integral_constant_expression_p=*/true);
10251         /* We don't have to set DECL_CONTEXT here; it is set by
10252            finish_member_declaration.  */
10253         DECL_CHAIN (r) = NULL_TREE;
10254         if (VOID_TYPE_P (type))
10255           error ("instantiation of %q+D as type %qT", r, type);
10256
10257         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10258                                         args, complain, in_decl);
10259       }
10260       break;
10261
10262     case USING_DECL:
10263       /* We reach here only for member using decls.  */
10264       if (DECL_DEPENDENT_P (t))
10265         {
10266           r = do_class_using_decl
10267             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10268              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10269           if (!r)
10270             r = error_mark_node;
10271           else
10272             {
10273               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10274               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10275             }
10276         }
10277       else
10278         {
10279           r = copy_node (t);
10280           DECL_CHAIN (r) = NULL_TREE;
10281         }
10282       break;
10283
10284     case TYPE_DECL:
10285     case VAR_DECL:
10286       {
10287         tree argvec = NULL_TREE;
10288         tree gen_tmpl = NULL_TREE;
10289         tree spec;
10290         tree tmpl = NULL_TREE;
10291         tree ctx;
10292         tree type = NULL_TREE;
10293         bool local_p;
10294
10295         if (TREE_CODE (t) == TYPE_DECL
10296             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10297           {
10298             /* If this is the canonical decl, we don't have to
10299                mess with instantiations, and often we can't (for
10300                typename, template type parms and such).  Note that
10301                TYPE_NAME is not correct for the above test if
10302                we've copied the type for a typedef.  */
10303             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10304             if (type == error_mark_node)
10305               RETURN (error_mark_node);
10306             r = TYPE_NAME (type);
10307             break;
10308           }
10309
10310         /* Check to see if we already have the specialization we
10311            need.  */
10312         spec = NULL_TREE;
10313         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10314           {
10315             /* T is a static data member or namespace-scope entity.
10316                We have to substitute into namespace-scope variables
10317                (even though such entities are never templates) because
10318                of cases like:
10319                
10320                  template <class T> void f() { extern T t; }
10321
10322                where the entity referenced is not known until
10323                instantiation time.  */
10324             local_p = false;
10325             ctx = DECL_CONTEXT (t);
10326             if (DECL_CLASS_SCOPE_P (t))
10327               {
10328                 ctx = tsubst_aggr_type (ctx, args,
10329                                         complain,
10330                                         in_decl, /*entering_scope=*/1);
10331                 /* If CTX is unchanged, then T is in fact the
10332                    specialization we want.  That situation occurs when
10333                    referencing a static data member within in its own
10334                    class.  We can use pointer equality, rather than
10335                    same_type_p, because DECL_CONTEXT is always
10336                    canonical.  */
10337                 if (ctx == DECL_CONTEXT (t))
10338                   spec = t;
10339               }
10340
10341             if (!spec)
10342               {
10343                 tmpl = DECL_TI_TEMPLATE (t);
10344                 gen_tmpl = most_general_template (tmpl);
10345                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10346                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10347                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10348               }
10349           }
10350         else
10351           {
10352             /* A local variable.  */
10353             local_p = true;
10354             /* Subsequent calls to pushdecl will fill this in.  */
10355             ctx = NULL_TREE;
10356             spec = retrieve_local_specialization (t);
10357           }
10358         /* If we already have the specialization we need, there is
10359            nothing more to do.  */ 
10360         if (spec)
10361           {
10362             r = spec;
10363             break;
10364           }
10365
10366         /* Create a new node for the specialization we need.  */
10367         r = copy_decl (t);
10368         if (type == NULL_TREE)
10369           {
10370             if (is_typedef_decl (t))
10371               type = DECL_ORIGINAL_TYPE (t);
10372             else
10373               type = TREE_TYPE (t);
10374             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
10375               type = strip_array_domain (type);
10376             type = tsubst (type, args, complain, in_decl);
10377           }
10378         if (TREE_CODE (r) == VAR_DECL)
10379           {
10380             /* Even if the original location is out of scope, the
10381                newly substituted one is not.  */
10382             DECL_DEAD_FOR_LOCAL (r) = 0;
10383             DECL_INITIALIZED_P (r) = 0;
10384             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10385             if (type == error_mark_node)
10386               RETURN (error_mark_node);
10387             if (TREE_CODE (type) == FUNCTION_TYPE)
10388               {
10389                 /* It may seem that this case cannot occur, since:
10390
10391                      typedef void f();
10392                      void g() { f x; }
10393
10394                    declares a function, not a variable.  However:
10395       
10396                      typedef void f();
10397                      template <typename T> void g() { T t; }
10398                      template void g<f>();
10399
10400                    is an attempt to declare a variable with function
10401                    type.  */
10402                 error ("variable %qD has function type",
10403                        /* R is not yet sufficiently initialized, so we
10404                           just use its name.  */
10405                        DECL_NAME (r));
10406                 RETURN (error_mark_node);
10407               }
10408             type = complete_type (type);
10409             /* Wait until cp_finish_decl to set this again, to handle
10410                circular dependency (template/instantiate6.C). */
10411             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10412             type = check_var_type (DECL_NAME (r), type);
10413
10414             if (DECL_HAS_VALUE_EXPR_P (t))
10415               {
10416                 tree ve = DECL_VALUE_EXPR (t);
10417                 ve = tsubst_expr (ve, args, complain, in_decl,
10418                                   /*constant_expression_p=*/false);
10419                 if (REFERENCE_REF_P (ve))
10420                   {
10421                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10422                     ve = TREE_OPERAND (ve, 0);
10423                   }
10424                 SET_DECL_VALUE_EXPR (r, ve);
10425               }
10426           }
10427         else if (DECL_SELF_REFERENCE_P (t))
10428           SET_DECL_SELF_REFERENCE_P (r);
10429         TREE_TYPE (r) = type;
10430         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10431         DECL_CONTEXT (r) = ctx;
10432         /* Clear out the mangled name and RTL for the instantiation.  */
10433         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10434         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10435           SET_DECL_RTL (r, NULL);
10436         /* The initializer must not be expanded until it is required;
10437            see [temp.inst].  */
10438         DECL_INITIAL (r) = NULL_TREE;
10439         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10440           SET_DECL_RTL (r, NULL);
10441         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10442         if (TREE_CODE (r) == VAR_DECL)
10443           {
10444             /* Possibly limit visibility based on template args.  */
10445             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10446             if (DECL_VISIBILITY_SPECIFIED (t))
10447               {
10448                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10449                 DECL_ATTRIBUTES (r)
10450                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10451               }
10452             determine_visibility (r);
10453           }
10454
10455         if (!local_p)
10456           {
10457             /* A static data member declaration is always marked
10458                external when it is declared in-class, even if an
10459                initializer is present.  We mimic the non-template
10460                processing here.  */
10461             DECL_EXTERNAL (r) = 1;
10462
10463             register_specialization (r, gen_tmpl, argvec, false, hash);
10464             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10465             SET_DECL_IMPLICIT_INSTANTIATION (r);
10466           }
10467         else if (cp_unevaluated_operand)
10468           {
10469             /* We're substituting this var in a decltype outside of its
10470                scope, such as for a lambda return type.  Don't add it to
10471                local_specializations, do perform auto deduction.  */
10472             tree auto_node = type_uses_auto (type);
10473             if (auto_node)
10474               {
10475                 tree init
10476                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10477                                  /*constant_expression_p=*/false);
10478                 init = resolve_nondeduced_context (init);
10479                 TREE_TYPE (r) = type
10480                   = do_auto_deduction (type, init, auto_node);
10481               }
10482           }
10483         else
10484           register_local_specialization (r, t);
10485
10486         DECL_CHAIN (r) = NULL_TREE;
10487
10488         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10489                                         /*flags=*/0,
10490                                         args, complain, in_decl);
10491
10492         /* Preserve a typedef that names a type.  */
10493         if (is_typedef_decl (r))
10494           {
10495             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10496             set_underlying_type (r);
10497           }
10498
10499         layout_decl (r, 0);
10500       }
10501       break;
10502
10503     default:
10504       gcc_unreachable ();
10505     }
10506 #undef RETURN
10507
10508  out:
10509   /* Restore the file and line information.  */
10510   input_location = saved_loc;
10511
10512   return r;
10513 }
10514
10515 /* Substitute into the ARG_TYPES of a function type.  */
10516
10517 static tree
10518 tsubst_arg_types (tree arg_types,
10519                   tree args,
10520                   tsubst_flags_t complain,
10521                   tree in_decl)
10522 {
10523   tree remaining_arg_types;
10524   tree type = NULL_TREE;
10525   int i = 1;
10526   tree expanded_args = NULL_TREE;
10527   tree default_arg;
10528
10529   if (!arg_types || arg_types == void_list_node)
10530     return arg_types;
10531
10532   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10533                                           args, complain, in_decl);
10534   if (remaining_arg_types == error_mark_node)
10535     return error_mark_node;
10536
10537   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10538     {
10539       /* For a pack expansion, perform substitution on the
10540          entire expression. Later on, we'll handle the arguments
10541          one-by-one.  */
10542       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10543                                             args, complain, in_decl);
10544
10545       if (TREE_CODE (expanded_args) == TREE_VEC)
10546         /* So that we'll spin through the parameters, one by one.  */
10547         i = TREE_VEC_LENGTH (expanded_args);
10548       else
10549         {
10550           /* We only partially substituted into the parameter
10551              pack. Our type is TYPE_PACK_EXPANSION.  */
10552           type = expanded_args;
10553           expanded_args = NULL_TREE;
10554         }
10555     }
10556
10557   while (i > 0) {
10558     --i;
10559     
10560     if (expanded_args)
10561       type = TREE_VEC_ELT (expanded_args, i);
10562     else if (!type)
10563       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10564
10565     if (type == error_mark_node)
10566       return error_mark_node;
10567     if (VOID_TYPE_P (type))
10568       {
10569         if (complain & tf_error)
10570           {
10571             error ("invalid parameter type %qT", type);
10572             if (in_decl)
10573               error ("in declaration %q+D", in_decl);
10574           }
10575         return error_mark_node;
10576     }
10577     
10578     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10579        top-level qualifiers as required.  */
10580     type = cv_unqualified (type_decays_to (type));
10581
10582     /* We do not substitute into default arguments here.  The standard
10583        mandates that they be instantiated only when needed, which is
10584        done in build_over_call.  */
10585     default_arg = TREE_PURPOSE (arg_types);
10586
10587     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10588       {
10589         /* We've instantiated a template before its default arguments
10590            have been parsed.  This can happen for a nested template
10591            class, and is not an error unless we require the default
10592            argument in a call of this function.  */
10593         remaining_arg_types = 
10594           tree_cons (default_arg, type, remaining_arg_types);
10595         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10596                        remaining_arg_types);
10597       }
10598     else
10599       remaining_arg_types = 
10600         hash_tree_cons (default_arg, type, remaining_arg_types);
10601   }
10602         
10603   return remaining_arg_types;
10604 }
10605
10606 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10607    *not* handle the exception-specification for FNTYPE, because the
10608    initial substitution of explicitly provided template parameters
10609    during argument deduction forbids substitution into the
10610    exception-specification:
10611
10612      [temp.deduct]
10613
10614      All references in the function type of the function template to  the
10615      corresponding template parameters are replaced by the specified tem-
10616      plate argument values.  If a substitution in a template parameter or
10617      in  the function type of the function template results in an invalid
10618      type, type deduction fails.  [Note: The equivalent  substitution  in
10619      exception specifications is done only when the function is instanti-
10620      ated, at which point a program is  ill-formed  if  the  substitution
10621      results in an invalid type.]  */
10622
10623 static tree
10624 tsubst_function_type (tree t,
10625                       tree args,
10626                       tsubst_flags_t complain,
10627                       tree in_decl)
10628 {
10629   tree return_type;
10630   tree arg_types;
10631   tree fntype;
10632
10633   /* The TYPE_CONTEXT is not used for function/method types.  */
10634   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10635
10636   /* Substitute the return type.  */
10637   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10638   if (return_type == error_mark_node)
10639     return error_mark_node;
10640   /* The standard does not presently indicate that creation of a
10641      function type with an invalid return type is a deduction failure.
10642      However, that is clearly analogous to creating an array of "void"
10643      or a reference to a reference.  This is core issue #486.  */
10644   if (TREE_CODE (return_type) == ARRAY_TYPE
10645       || TREE_CODE (return_type) == FUNCTION_TYPE)
10646     {
10647       if (complain & tf_error)
10648         {
10649           if (TREE_CODE (return_type) == ARRAY_TYPE)
10650             error ("function returning an array");
10651           else
10652             error ("function returning a function");
10653         }
10654       return error_mark_node;
10655     }
10656
10657   /* Substitute the argument types.  */
10658   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10659                                 complain, in_decl);
10660   if (arg_types == error_mark_node)
10661     return error_mark_node;
10662
10663   /* Construct a new type node and return it.  */
10664   if (TREE_CODE (t) == FUNCTION_TYPE)
10665     {
10666       fntype = build_function_type (return_type, arg_types);
10667       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10668     }
10669   else
10670     {
10671       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10672       if (! MAYBE_CLASS_TYPE_P (r))
10673         {
10674           /* [temp.deduct]
10675
10676              Type deduction may fail for any of the following
10677              reasons:
10678
10679              -- Attempting to create "pointer to member of T" when T
10680              is not a class type.  */
10681           if (complain & tf_error)
10682             error ("creating pointer to member function of non-class type %qT",
10683                       r);
10684           return error_mark_node;
10685         }
10686
10687       fntype = build_method_type_directly (r, return_type,
10688                                            TREE_CHAIN (arg_types));
10689     }
10690   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10691
10692   return fntype;
10693 }
10694
10695 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10696    ARGS into that specification, and return the substituted
10697    specification.  If there is no specification, return NULL_TREE.  */
10698
10699 static tree
10700 tsubst_exception_specification (tree fntype,
10701                                 tree args,
10702                                 tsubst_flags_t complain,
10703                                 tree in_decl,
10704                                 bool defer_ok)
10705 {
10706   tree specs;
10707   tree new_specs;
10708
10709   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10710   new_specs = NULL_TREE;
10711   if (specs && TREE_PURPOSE (specs))
10712     {
10713       /* A noexcept-specifier.  */
10714       tree expr = TREE_PURPOSE (specs);
10715       if (expr == boolean_true_node || expr == boolean_false_node)
10716         new_specs = expr;
10717       else if (defer_ok)
10718         {
10719           /* Defer instantiation of noexcept-specifiers to avoid
10720              excessive instantiations (c++/49107).  */
10721           new_specs = make_node (DEFERRED_NOEXCEPT);
10722           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10723             {
10724               /* We already partially instantiated this member template,
10725                  so combine the new args with the old.  */
10726               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10727                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10728               DEFERRED_NOEXCEPT_ARGS (new_specs)
10729                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10730             }
10731           else
10732             {
10733               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10734               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10735             }
10736         }
10737       else
10738         new_specs = tsubst_copy_and_build
10739           (expr, args, complain, in_decl, /*function_p=*/false,
10740            /*integral_constant_expression_p=*/true);
10741       new_specs = build_noexcept_spec (new_specs, complain);
10742     }
10743   else if (specs)
10744     {
10745       if (! TREE_VALUE (specs))
10746         new_specs = specs;
10747       else
10748         while (specs)
10749           {
10750             tree spec;
10751             int i, len = 1;
10752             tree expanded_specs = NULL_TREE;
10753
10754             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10755               {
10756                 /* Expand the pack expansion type.  */
10757                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10758                                                        args, complain,
10759                                                        in_decl);
10760
10761                 if (expanded_specs == error_mark_node)
10762                   return error_mark_node;
10763                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10764                   len = TREE_VEC_LENGTH (expanded_specs);
10765                 else
10766                   {
10767                     /* We're substituting into a member template, so
10768                        we got a TYPE_PACK_EXPANSION back.  Add that
10769                        expansion and move on.  */
10770                     gcc_assert (TREE_CODE (expanded_specs) 
10771                                 == TYPE_PACK_EXPANSION);
10772                     new_specs = add_exception_specifier (new_specs,
10773                                                          expanded_specs,
10774                                                          complain);
10775                     specs = TREE_CHAIN (specs);
10776                     continue;
10777                   }
10778               }
10779
10780             for (i = 0; i < len; ++i)
10781               {
10782                 if (expanded_specs)
10783                   spec = TREE_VEC_ELT (expanded_specs, i);
10784                 else
10785                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10786                 if (spec == error_mark_node)
10787                   return spec;
10788                 new_specs = add_exception_specifier (new_specs, spec, 
10789                                                      complain);
10790               }
10791
10792             specs = TREE_CHAIN (specs);
10793           }
10794     }
10795   return new_specs;
10796 }
10797
10798 /* Take the tree structure T and replace template parameters used
10799    therein with the argument vector ARGS.  IN_DECL is an associated
10800    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10801    Issue error and warning messages under control of COMPLAIN.  Note
10802    that we must be relatively non-tolerant of extensions here, in
10803    order to preserve conformance; if we allow substitutions that
10804    should not be allowed, we may allow argument deductions that should
10805    not succeed, and therefore report ambiguous overload situations
10806    where there are none.  In theory, we could allow the substitution,
10807    but indicate that it should have failed, and allow our caller to
10808    make sure that the right thing happens, but we don't try to do this
10809    yet.
10810
10811    This function is used for dealing with types, decls and the like;
10812    for expressions, use tsubst_expr or tsubst_copy.  */
10813
10814 tree
10815 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10816 {
10817   enum tree_code code;
10818   tree type, r;
10819
10820   if (t == NULL_TREE || t == error_mark_node
10821       || t == integer_type_node
10822       || t == void_type_node
10823       || t == char_type_node
10824       || t == unknown_type_node
10825       || TREE_CODE (t) == NAMESPACE_DECL
10826       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10827     return t;
10828
10829   if (DECL_P (t))
10830     return tsubst_decl (t, args, complain);
10831
10832   if (args == NULL_TREE)
10833     return t;
10834
10835   code = TREE_CODE (t);
10836
10837   if (code == IDENTIFIER_NODE)
10838     type = IDENTIFIER_TYPE_VALUE (t);
10839   else
10840     type = TREE_TYPE (t);
10841
10842   gcc_assert (type != unknown_type_node);
10843
10844   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10845      such as attribute aligned.  */
10846   if (TYPE_P (t)
10847       && typedef_variant_p (t))
10848     {
10849       tree decl = TYPE_NAME (t);
10850       
10851       if (DECL_CLASS_SCOPE_P (decl)
10852           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10853           && uses_template_parms (DECL_CONTEXT (decl)))
10854         {
10855           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10856           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10857           r = retrieve_specialization (tmpl, gen_args, 0);
10858         }
10859       else if (DECL_FUNCTION_SCOPE_P (decl)
10860                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10861                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10862         r = retrieve_local_specialization (decl);
10863       else
10864         /* The typedef is from a non-template context.  */
10865         return t;
10866
10867       if (r)
10868         {
10869           r = TREE_TYPE (r);
10870           r = cp_build_qualified_type_real
10871             (r, cp_type_quals (t) | cp_type_quals (r),
10872              complain | tf_ignore_bad_quals);
10873           return r;
10874         }
10875       /* Else we must be instantiating the typedef, so fall through.  */
10876     }
10877
10878   if (type
10879       && code != TYPENAME_TYPE
10880       && code != TEMPLATE_TYPE_PARM
10881       && code != IDENTIFIER_NODE
10882       && code != FUNCTION_TYPE
10883       && code != METHOD_TYPE)
10884     type = tsubst (type, args, complain, in_decl);
10885   if (type == error_mark_node)
10886     return error_mark_node;
10887
10888   switch (code)
10889     {
10890     case RECORD_TYPE:
10891     case UNION_TYPE:
10892     case ENUMERAL_TYPE:
10893       return tsubst_aggr_type (t, args, complain, in_decl,
10894                                /*entering_scope=*/0);
10895
10896     case ERROR_MARK:
10897     case IDENTIFIER_NODE:
10898     case VOID_TYPE:
10899     case REAL_TYPE:
10900     case COMPLEX_TYPE:
10901     case VECTOR_TYPE:
10902     case BOOLEAN_TYPE:
10903     case NULLPTR_TYPE:
10904     case LANG_TYPE:
10905       return t;
10906
10907     case INTEGER_TYPE:
10908       if (t == integer_type_node)
10909         return t;
10910
10911       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10912           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10913         return t;
10914
10915       {
10916         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10917
10918         max = tsubst_expr (omax, args, complain, in_decl,
10919                            /*integral_constant_expression_p=*/false);
10920
10921         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10922            needed.  */
10923         if (TREE_CODE (max) == NOP_EXPR
10924             && TREE_SIDE_EFFECTS (omax)
10925             && !TREE_TYPE (max))
10926           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10927
10928         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10929            with TREE_SIDE_EFFECTS that indicates this is not an integral
10930            constant expression.  */
10931         if (processing_template_decl
10932             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10933           {
10934             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10935             TREE_SIDE_EFFECTS (max) = 1;
10936           }
10937
10938         return compute_array_index_type (NULL_TREE, max, complain);
10939       }
10940
10941     case TEMPLATE_TYPE_PARM:
10942     case TEMPLATE_TEMPLATE_PARM:
10943     case BOUND_TEMPLATE_TEMPLATE_PARM:
10944     case TEMPLATE_PARM_INDEX:
10945       {
10946         int idx;
10947         int level;
10948         int levels;
10949         tree arg = NULL_TREE;
10950
10951         r = NULL_TREE;
10952
10953         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10954         template_parm_level_and_index (t, &level, &idx); 
10955
10956         levels = TMPL_ARGS_DEPTH (args);
10957         if (level <= levels)
10958           {
10959             arg = TMPL_ARG (args, level, idx);
10960
10961             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10962               /* See through ARGUMENT_PACK_SELECT arguments. */
10963               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10964           }
10965
10966         if (arg == error_mark_node)
10967           return error_mark_node;
10968         else if (arg != NULL_TREE)
10969           {
10970             if (ARGUMENT_PACK_P (arg))
10971               /* If ARG is an argument pack, we don't actually want to
10972                  perform a substitution here, because substitutions
10973                  for argument packs are only done
10974                  element-by-element. We can get to this point when
10975                  substituting the type of a non-type template
10976                  parameter pack, when that type actually contains
10977                  template parameter packs from an outer template, e.g.,
10978
10979                  template<typename... Types> struct A {
10980                    template<Types... Values> struct B { };
10981                  };  */
10982               return t;
10983
10984             if (code == TEMPLATE_TYPE_PARM)
10985               {
10986                 int quals;
10987                 gcc_assert (TYPE_P (arg));
10988
10989                 quals = cp_type_quals (arg) | cp_type_quals (t);
10990                   
10991                 return cp_build_qualified_type_real
10992                   (arg, quals, complain | tf_ignore_bad_quals);
10993               }
10994             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10995               {
10996                 /* We are processing a type constructed from a
10997                    template template parameter.  */
10998                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10999                                       args, complain, in_decl);
11000                 if (argvec == error_mark_node)
11001                   return error_mark_node;
11002
11003                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11004                    are resolving nested-types in the signature of a
11005                    member function templates.  Otherwise ARG is a
11006                    TEMPLATE_DECL and is the real template to be
11007                    instantiated.  */
11008                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11009                   arg = TYPE_NAME (arg);
11010
11011                 r = lookup_template_class (arg,
11012                                            argvec, in_decl,
11013                                            DECL_CONTEXT (arg),
11014                                             /*entering_scope=*/0,
11015                                            complain);
11016                 return cp_build_qualified_type_real
11017                   (r, cp_type_quals (t), complain);
11018               }
11019             else
11020               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11021               return convert_from_reference (unshare_expr (arg));
11022           }
11023
11024         if (level == 1)
11025           /* This can happen during the attempted tsubst'ing in
11026              unify.  This means that we don't yet have any information
11027              about the template parameter in question.  */
11028           return t;
11029
11030         /* If we get here, we must have been looking at a parm for a
11031            more deeply nested template.  Make a new version of this
11032            template parameter, but with a lower level.  */
11033         switch (code)
11034           {
11035           case TEMPLATE_TYPE_PARM:
11036           case TEMPLATE_TEMPLATE_PARM:
11037           case BOUND_TEMPLATE_TEMPLATE_PARM:
11038             if (cp_type_quals (t))
11039               {
11040                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11041                 r = cp_build_qualified_type_real
11042                   (r, cp_type_quals (t),
11043                    complain | (code == TEMPLATE_TYPE_PARM
11044                                ? tf_ignore_bad_quals : 0));
11045               }
11046             else
11047               {
11048                 r = copy_type (t);
11049                 TEMPLATE_TYPE_PARM_INDEX (r)
11050                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11051                                                 r, levels, args, complain);
11052                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11053                 TYPE_MAIN_VARIANT (r) = r;
11054                 TYPE_POINTER_TO (r) = NULL_TREE;
11055                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11056
11057                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11058                   /* We have reduced the level of the template
11059                      template parameter, but not the levels of its
11060                      template parameters, so canonical_type_parameter
11061                      will not be able to find the canonical template
11062                      template parameter for this level. Thus, we
11063                      require structural equality checking to compare
11064                      TEMPLATE_TEMPLATE_PARMs. */
11065                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11066                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11067                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11068                 else
11069                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11070
11071                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11072                   {
11073                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11074                                           complain, in_decl);
11075                     if (argvec == error_mark_node)
11076                       return error_mark_node;
11077
11078                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11079                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11080                   }
11081               }
11082             break;
11083
11084           case TEMPLATE_PARM_INDEX:
11085             r = reduce_template_parm_level (t, type, levels, args, complain);
11086             break;
11087
11088           default:
11089             gcc_unreachable ();
11090           }
11091
11092         return r;
11093       }
11094
11095     case TREE_LIST:
11096       {
11097         tree purpose, value, chain;
11098
11099         if (t == void_list_node)
11100           return t;
11101
11102         purpose = TREE_PURPOSE (t);
11103         if (purpose)
11104           {
11105             purpose = tsubst (purpose, args, complain, in_decl);
11106             if (purpose == error_mark_node)
11107               return error_mark_node;
11108           }
11109         value = TREE_VALUE (t);
11110         if (value)
11111           {
11112             value = tsubst (value, args, complain, in_decl);
11113             if (value == error_mark_node)
11114               return error_mark_node;
11115           }
11116         chain = TREE_CHAIN (t);
11117         if (chain && chain != void_type_node)
11118           {
11119             chain = tsubst (chain, args, complain, in_decl);
11120             if (chain == error_mark_node)
11121               return error_mark_node;
11122           }
11123         if (purpose == TREE_PURPOSE (t)
11124             && value == TREE_VALUE (t)
11125             && chain == TREE_CHAIN (t))
11126           return t;
11127         return hash_tree_cons (purpose, value, chain);
11128       }
11129
11130     case TREE_BINFO:
11131       /* We should never be tsubsting a binfo.  */
11132       gcc_unreachable ();
11133
11134     case TREE_VEC:
11135       /* A vector of template arguments.  */
11136       gcc_assert (!type);
11137       return tsubst_template_args (t, args, complain, in_decl);
11138
11139     case POINTER_TYPE:
11140     case REFERENCE_TYPE:
11141       {
11142         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11143           return t;
11144
11145         /* [temp.deduct]
11146
11147            Type deduction may fail for any of the following
11148            reasons:
11149
11150            -- Attempting to create a pointer to reference type.
11151            -- Attempting to create a reference to a reference type or
11152               a reference to void.
11153
11154           Core issue 106 says that creating a reference to a reference
11155           during instantiation is no longer a cause for failure. We
11156           only enforce this check in strict C++98 mode.  */
11157         if ((TREE_CODE (type) == REFERENCE_TYPE
11158              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11159             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11160           {
11161             static location_t last_loc;
11162
11163             /* We keep track of the last time we issued this error
11164                message to avoid spewing a ton of messages during a
11165                single bad template instantiation.  */
11166             if (complain & tf_error
11167                 && last_loc != input_location)
11168               {
11169                 if (TREE_CODE (type) == VOID_TYPE)
11170                   error ("forming reference to void");
11171                else if (code == POINTER_TYPE)
11172                  error ("forming pointer to reference type %qT", type);
11173                else
11174                   error ("forming reference to reference type %qT", type);
11175                 last_loc = input_location;
11176               }
11177
11178             return error_mark_node;
11179           }
11180         else if (code == POINTER_TYPE)
11181           {
11182             r = build_pointer_type (type);
11183             if (TREE_CODE (type) == METHOD_TYPE)
11184               r = build_ptrmemfunc_type (r);
11185           }
11186         else if (TREE_CODE (type) == REFERENCE_TYPE)
11187           /* In C++0x, during template argument substitution, when there is an
11188              attempt to create a reference to a reference type, reference
11189              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11190
11191              "If a template-argument for a template-parameter T names a type
11192              that is a reference to a type A, an attempt to create the type
11193              'lvalue reference to cv T' creates the type 'lvalue reference to
11194              A,' while an attempt to create the type type rvalue reference to
11195              cv T' creates the type T"
11196           */
11197           r = cp_build_reference_type
11198               (TREE_TYPE (type),
11199                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11200         else
11201           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11202         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11203
11204         if (r != error_mark_node)
11205           /* Will this ever be needed for TYPE_..._TO values?  */
11206           layout_type (r);
11207
11208         return r;
11209       }
11210     case OFFSET_TYPE:
11211       {
11212         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11213         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11214           {
11215             /* [temp.deduct]
11216
11217                Type deduction may fail for any of the following
11218                reasons:
11219
11220                -- Attempting to create "pointer to member of T" when T
11221                   is not a class type.  */
11222             if (complain & tf_error)
11223               error ("creating pointer to member of non-class type %qT", r);
11224             return error_mark_node;
11225           }
11226         if (TREE_CODE (type) == REFERENCE_TYPE)
11227           {
11228             if (complain & tf_error)
11229               error ("creating pointer to member reference type %qT", type);
11230             return error_mark_node;
11231           }
11232         if (TREE_CODE (type) == VOID_TYPE)
11233           {
11234             if (complain & tf_error)
11235               error ("creating pointer to member of type void");
11236             return error_mark_node;
11237           }
11238         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11239         if (TREE_CODE (type) == FUNCTION_TYPE)
11240           {
11241             /* The type of the implicit object parameter gets its
11242                cv-qualifiers from the FUNCTION_TYPE. */
11243             tree memptr;
11244             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11245             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11246             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11247                                                  complain);
11248           }
11249         else
11250           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11251                                                cp_type_quals (t),
11252                                                complain);
11253       }
11254     case FUNCTION_TYPE:
11255     case METHOD_TYPE:
11256       {
11257         tree fntype;
11258         tree specs;
11259         fntype = tsubst_function_type (t, args, complain, in_decl);
11260         if (fntype == error_mark_node)
11261           return error_mark_node;
11262
11263         /* Substitute the exception specification.  */
11264         specs = tsubst_exception_specification (t, args, complain,
11265                                                 in_decl, /*defer_ok*/true);
11266         if (specs == error_mark_node)
11267           return error_mark_node;
11268         if (specs)
11269           fntype = build_exception_variant (fntype, specs);
11270         return fntype;
11271       }
11272     case ARRAY_TYPE:
11273       {
11274         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11275         if (domain == error_mark_node)
11276           return error_mark_node;
11277
11278         /* As an optimization, we avoid regenerating the array type if
11279            it will obviously be the same as T.  */
11280         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11281           return t;
11282
11283         /* These checks should match the ones in grokdeclarator.
11284
11285            [temp.deduct]
11286
11287            The deduction may fail for any of the following reasons:
11288
11289            -- Attempting to create an array with an element type that
11290               is void, a function type, or a reference type, or [DR337]
11291               an abstract class type.  */
11292         if (TREE_CODE (type) == VOID_TYPE
11293             || TREE_CODE (type) == FUNCTION_TYPE
11294             || TREE_CODE (type) == REFERENCE_TYPE)
11295           {
11296             if (complain & tf_error)
11297               error ("creating array of %qT", type);
11298             return error_mark_node;
11299           }
11300         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11301           {
11302             if (complain & tf_error)
11303               error ("creating array of %qT, which is an abstract class type",
11304                      type);
11305             return error_mark_node;
11306           }
11307
11308         r = build_cplus_array_type (type, domain);
11309
11310         if (TYPE_USER_ALIGN (t))
11311           {
11312             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11313             TYPE_USER_ALIGN (r) = 1;
11314           }
11315
11316         return r;
11317       }
11318
11319     case TYPENAME_TYPE:
11320       {
11321         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11322                                      in_decl, /*entering_scope=*/1);
11323         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11324                               complain, in_decl);
11325
11326         if (ctx == error_mark_node || f == error_mark_node)
11327           return error_mark_node;
11328
11329         if (!MAYBE_CLASS_TYPE_P (ctx))
11330           {
11331             if (complain & tf_error)
11332               error ("%qT is not a class, struct, or union type", ctx);
11333             return error_mark_node;
11334           }
11335         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11336           {
11337             /* Normally, make_typename_type does not require that the CTX
11338                have complete type in order to allow things like:
11339
11340                  template <class T> struct S { typename S<T>::X Y; };
11341
11342                But, such constructs have already been resolved by this
11343                point, so here CTX really should have complete type, unless
11344                it's a partial instantiation.  */
11345             ctx = complete_type (ctx);
11346             if (!COMPLETE_TYPE_P (ctx))
11347               {
11348                 if (complain & tf_error)
11349                   cxx_incomplete_type_error (NULL_TREE, ctx);
11350                 return error_mark_node;
11351               }
11352           }
11353
11354         f = make_typename_type (ctx, f, typename_type,
11355                                 (complain & tf_error) | tf_keep_type_decl);
11356         if (f == error_mark_node)
11357           return f;
11358         if (TREE_CODE (f) == TYPE_DECL)
11359           {
11360             complain |= tf_ignore_bad_quals;
11361             f = TREE_TYPE (f);
11362           }
11363
11364         if (TREE_CODE (f) != TYPENAME_TYPE)
11365           {
11366             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11367               {
11368                 if (complain & tf_error)
11369                   error ("%qT resolves to %qT, which is not an enumeration type",
11370                          t, f);
11371                 else
11372                   return error_mark_node;
11373               }
11374             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11375               {
11376                 if (complain & tf_error)
11377                   error ("%qT resolves to %qT, which is is not a class type",
11378                          t, f);
11379                 else
11380                   return error_mark_node;
11381               }
11382           }
11383
11384         return cp_build_qualified_type_real
11385           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11386       }
11387
11388     case UNBOUND_CLASS_TEMPLATE:
11389       {
11390         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11391                                      in_decl, /*entering_scope=*/1);
11392         tree name = TYPE_IDENTIFIER (t);
11393         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11394
11395         if (ctx == error_mark_node || name == error_mark_node)
11396           return error_mark_node;
11397
11398         if (parm_list)
11399           parm_list = tsubst_template_parms (parm_list, args, complain);
11400         return make_unbound_class_template (ctx, name, parm_list, complain);
11401       }
11402
11403     case TYPEOF_TYPE:
11404       {
11405         tree type;
11406
11407         ++cp_unevaluated_operand;
11408         ++c_inhibit_evaluation_warnings;
11409
11410         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11411                             complain, in_decl,
11412                             /*integral_constant_expression_p=*/false);
11413
11414         --cp_unevaluated_operand;
11415         --c_inhibit_evaluation_warnings;
11416
11417         type = finish_typeof (type);
11418         return cp_build_qualified_type_real (type,
11419                                              cp_type_quals (t)
11420                                              | cp_type_quals (type),
11421                                              complain);
11422       }
11423
11424     case DECLTYPE_TYPE:
11425       {
11426         tree type;
11427
11428         ++cp_unevaluated_operand;
11429         ++c_inhibit_evaluation_warnings;
11430
11431         type = tsubst_expr (DECLTYPE_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         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11439           type = lambda_capture_field_type (type);
11440         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11441           type = lambda_proxy_type (type);
11442         else
11443           type = finish_decltype_type
11444             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11445         return cp_build_qualified_type_real (type,
11446                                              cp_type_quals (t)
11447                                              | cp_type_quals (type),
11448                                              complain);
11449       }
11450
11451     case UNDERLYING_TYPE:
11452       {
11453         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11454                             complain, in_decl);
11455         return finish_underlying_type (type);
11456       }
11457
11458     case TYPE_ARGUMENT_PACK:
11459     case NONTYPE_ARGUMENT_PACK:
11460       {
11461         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11462         tree packed_out = 
11463           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11464                                 args,
11465                                 complain,
11466                                 in_decl);
11467         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11468
11469         /* For template nontype argument packs, also substitute into
11470            the type.  */
11471         if (code == NONTYPE_ARGUMENT_PACK)
11472           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11473
11474         return r;
11475       }
11476       break;
11477
11478     case INTEGER_CST:
11479     case REAL_CST:
11480     case STRING_CST:
11481     case PLUS_EXPR:
11482     case MINUS_EXPR:
11483     case NEGATE_EXPR:
11484     case NOP_EXPR:
11485     case INDIRECT_REF:
11486     case ADDR_EXPR:
11487     case CALL_EXPR:
11488     case ARRAY_REF:
11489     case SCOPE_REF:
11490       /* We should use one of the expression tsubsts for these codes.  */
11491       gcc_unreachable ();
11492
11493     default:
11494       sorry ("use of %qs in template", tree_code_name [(int) code]);
11495       return error_mark_node;
11496     }
11497 }
11498
11499 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11500    type of the expression on the left-hand side of the "." or "->"
11501    operator.  */
11502
11503 static tree
11504 tsubst_baselink (tree baselink, tree object_type,
11505                  tree args, tsubst_flags_t complain, tree in_decl)
11506 {
11507     tree name;
11508     tree qualifying_scope;
11509     tree fns;
11510     tree optype;
11511     tree template_args = 0;
11512     bool template_id_p = false;
11513
11514     /* A baselink indicates a function from a base class.  Both the
11515        BASELINK_ACCESS_BINFO and the base class referenced may
11516        indicate bases of the template class, rather than the
11517        instantiated class.  In addition, lookups that were not
11518        ambiguous before may be ambiguous now.  Therefore, we perform
11519        the lookup again.  */
11520     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11521     qualifying_scope = tsubst (qualifying_scope, args,
11522                                complain, in_decl);
11523     fns = BASELINK_FUNCTIONS (baselink);
11524     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11525     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11526       {
11527         template_id_p = true;
11528         template_args = TREE_OPERAND (fns, 1);
11529         fns = TREE_OPERAND (fns, 0);
11530         if (template_args)
11531           template_args = tsubst_template_args (template_args, args,
11532                                                 complain, in_decl);
11533       }
11534     name = DECL_NAME (get_first_fn (fns));
11535     if (IDENTIFIER_TYPENAME_P (name))
11536       name = mangle_conv_op_name_for_type (optype);
11537     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11538     if (!baselink)
11539       return error_mark_node;
11540
11541     /* If lookup found a single function, mark it as used at this
11542        point.  (If it lookup found multiple functions the one selected
11543        later by overload resolution will be marked as used at that
11544        point.)  */
11545     if (BASELINK_P (baselink))
11546       fns = BASELINK_FUNCTIONS (baselink);
11547     if (!template_id_p && !really_overloaded_fn (fns))
11548       mark_used (OVL_CURRENT (fns));
11549
11550     /* Add back the template arguments, if present.  */
11551     if (BASELINK_P (baselink) && template_id_p)
11552       BASELINK_FUNCTIONS (baselink)
11553         = build_nt (TEMPLATE_ID_EXPR,
11554                     BASELINK_FUNCTIONS (baselink),
11555                     template_args);
11556     /* Update the conversion operator type.  */
11557     BASELINK_OPTYPE (baselink) = optype;
11558
11559     if (!object_type)
11560       object_type = current_class_type;
11561     return adjust_result_of_qualified_name_lookup (baselink,
11562                                                    qualifying_scope,
11563                                                    object_type);
11564 }
11565
11566 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11567    true if the qualified-id will be a postfix-expression in-and-of
11568    itself; false if more of the postfix-expression follows the
11569    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11570    of "&".  */
11571
11572 static tree
11573 tsubst_qualified_id (tree qualified_id, tree args,
11574                      tsubst_flags_t complain, tree in_decl,
11575                      bool done, bool address_p)
11576 {
11577   tree expr;
11578   tree scope;
11579   tree name;
11580   bool is_template;
11581   tree template_args;
11582
11583   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11584
11585   /* Figure out what name to look up.  */
11586   name = TREE_OPERAND (qualified_id, 1);
11587   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11588     {
11589       is_template = true;
11590       template_args = TREE_OPERAND (name, 1);
11591       if (template_args)
11592         template_args = tsubst_template_args (template_args, args,
11593                                               complain, in_decl);
11594       name = TREE_OPERAND (name, 0);
11595     }
11596   else
11597     {
11598       is_template = false;
11599       template_args = NULL_TREE;
11600     }
11601
11602   /* Substitute into the qualifying scope.  When there are no ARGS, we
11603      are just trying to simplify a non-dependent expression.  In that
11604      case the qualifying scope may be dependent, and, in any case,
11605      substituting will not help.  */
11606   scope = TREE_OPERAND (qualified_id, 0);
11607   if (args)
11608     {
11609       scope = tsubst (scope, args, complain, in_decl);
11610       expr = tsubst_copy (name, args, complain, in_decl);
11611     }
11612   else
11613     expr = name;
11614
11615   if (dependent_scope_p (scope))
11616     {
11617       if (is_template)
11618         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11619       return build_qualified_name (NULL_TREE, scope, expr,
11620                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11621     }
11622
11623   if (!BASELINK_P (name) && !DECL_P (expr))
11624     {
11625       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11626         {
11627           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11628           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11629             {
11630               error ("qualifying type %qT does not match destructor name ~%qT",
11631                      scope, TREE_OPERAND (expr, 0));
11632               expr = error_mark_node;
11633             }
11634           else
11635             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11636                                           /*is_type_p=*/0, false);
11637         }
11638       else
11639         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11640       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11641                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11642         {
11643           if (complain & tf_error)
11644             {
11645               error ("dependent-name %qE is parsed as a non-type, but "
11646                      "instantiation yields a type", qualified_id);
11647               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11648             }
11649           return error_mark_node;
11650         }
11651     }
11652
11653   if (DECL_P (expr))
11654     {
11655       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11656                                            scope);
11657       /* Remember that there was a reference to this entity.  */
11658       mark_used (expr);
11659     }
11660
11661   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11662     {
11663       if (complain & tf_error)
11664         qualified_name_lookup_error (scope,
11665                                      TREE_OPERAND (qualified_id, 1),
11666                                      expr, input_location);
11667       return error_mark_node;
11668     }
11669
11670   if (is_template)
11671     expr = lookup_template_function (expr, template_args);
11672
11673   if (expr == error_mark_node && complain & tf_error)
11674     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11675                                  expr, input_location);
11676   else if (TYPE_P (scope))
11677     {
11678       expr = (adjust_result_of_qualified_name_lookup
11679               (expr, scope, current_class_type));
11680       expr = (finish_qualified_id_expr
11681               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11682                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11683                /*template_arg_p=*/false));
11684     }
11685
11686   /* Expressions do not generally have reference type.  */
11687   if (TREE_CODE (expr) != SCOPE_REF
11688       /* However, if we're about to form a pointer-to-member, we just
11689          want the referenced member referenced.  */
11690       && TREE_CODE (expr) != OFFSET_REF)
11691     expr = convert_from_reference (expr);
11692
11693   return expr;
11694 }
11695
11696 /* Like tsubst, but deals with expressions.  This function just replaces
11697    template parms; to finish processing the resultant expression, use
11698    tsubst_expr.  */
11699
11700 static tree
11701 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11702 {
11703   enum tree_code code;
11704   tree r;
11705
11706   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11707     return t;
11708
11709   code = TREE_CODE (t);
11710
11711   switch (code)
11712     {
11713     case PARM_DECL:
11714       r = retrieve_local_specialization (t);
11715
11716       if (r == NULL)
11717         {
11718           tree c;
11719           /* This can happen for a parameter name used later in a function
11720              declaration (such as in a late-specified return type).  Just
11721              make a dummy decl, since it's only used for its type.  */
11722           gcc_assert (cp_unevaluated_operand != 0);
11723           /* We copy T because want to tsubst the PARM_DECL only,
11724              not the following PARM_DECLs that are chained to T.  */
11725           c = copy_node (t);
11726           r = tsubst_decl (c, args, complain);
11727           /* Give it the template pattern as its context; its true context
11728              hasn't been instantiated yet and this is good enough for
11729              mangling.  */
11730           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11731         }
11732       
11733       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11734         r = ARGUMENT_PACK_SELECT_ARG (r);
11735       mark_used (r);
11736       return r;
11737
11738     case CONST_DECL:
11739       {
11740         tree enum_type;
11741         tree v;
11742
11743         if (DECL_TEMPLATE_PARM_P (t))
11744           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11745         /* There is no need to substitute into namespace-scope
11746            enumerators.  */
11747         if (DECL_NAMESPACE_SCOPE_P (t))
11748           return t;
11749         /* If ARGS is NULL, then T is known to be non-dependent.  */
11750         if (args == NULL_TREE)
11751           return integral_constant_value (t);
11752
11753         /* Unfortunately, we cannot just call lookup_name here.
11754            Consider:
11755
11756              template <int I> int f() {
11757              enum E { a = I };
11758              struct S { void g() { E e = a; } };
11759              };
11760
11761            When we instantiate f<7>::S::g(), say, lookup_name is not
11762            clever enough to find f<7>::a.  */
11763         enum_type
11764           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11765                               /*entering_scope=*/0);
11766
11767         for (v = TYPE_VALUES (enum_type);
11768              v != NULL_TREE;
11769              v = TREE_CHAIN (v))
11770           if (TREE_PURPOSE (v) == DECL_NAME (t))
11771             return TREE_VALUE (v);
11772
11773           /* We didn't find the name.  That should never happen; if
11774              name-lookup found it during preliminary parsing, we
11775              should find it again here during instantiation.  */
11776         gcc_unreachable ();
11777       }
11778       return t;
11779
11780     case FIELD_DECL:
11781       if (DECL_CONTEXT (t))
11782         {
11783           tree ctx;
11784
11785           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11786                                   /*entering_scope=*/1);
11787           if (ctx != DECL_CONTEXT (t))
11788             {
11789               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11790               if (!r)
11791                 {
11792                   if (complain & tf_error)
11793                     error ("using invalid field %qD", t);
11794                   return error_mark_node;
11795                 }
11796               return r;
11797             }
11798         }
11799
11800       return t;
11801
11802     case VAR_DECL:
11803     case FUNCTION_DECL:
11804       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11805           || local_variable_p (t))
11806         t = tsubst (t, args, complain, in_decl);
11807       mark_used (t);
11808       return t;
11809
11810     case OVERLOAD:
11811       /* An OVERLOAD will always be a non-dependent overload set; an
11812          overload set from function scope will just be represented with an
11813          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11814       gcc_assert (!uses_template_parms (t));
11815       return t;
11816
11817     case BASELINK:
11818       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11819
11820     case TEMPLATE_DECL:
11821       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11822         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11823                        args, complain, in_decl);
11824       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11825         return tsubst (t, args, complain, in_decl);
11826       else if (DECL_CLASS_SCOPE_P (t)
11827                && uses_template_parms (DECL_CONTEXT (t)))
11828         {
11829           /* Template template argument like the following example need
11830              special treatment:
11831
11832                template <template <class> class TT> struct C {};
11833                template <class T> struct D {
11834                  template <class U> struct E {};
11835                  C<E> c;                                // #1
11836                };
11837                D<int> d;                                // #2
11838
11839              We are processing the template argument `E' in #1 for
11840              the template instantiation #2.  Originally, `E' is a
11841              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11842              have to substitute this with one having context `D<int>'.  */
11843
11844           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11845           return lookup_field (context, DECL_NAME(t), 0, false);
11846         }
11847       else
11848         /* Ordinary template template argument.  */
11849         return t;
11850
11851     case CAST_EXPR:
11852     case REINTERPRET_CAST_EXPR:
11853     case CONST_CAST_EXPR:
11854     case STATIC_CAST_EXPR:
11855     case DYNAMIC_CAST_EXPR:
11856     case NOP_EXPR:
11857       return build1
11858         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11859          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11860
11861     case SIZEOF_EXPR:
11862       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11863         {
11864
11865           tree expanded;
11866           int len = 0;
11867
11868           ++cp_unevaluated_operand;
11869           ++c_inhibit_evaluation_warnings;
11870           /* We only want to compute the number of arguments.  */
11871           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11872                                             complain, in_decl);
11873           --cp_unevaluated_operand;
11874           --c_inhibit_evaluation_warnings;
11875
11876           if (TREE_CODE (expanded) == TREE_VEC)
11877             len = TREE_VEC_LENGTH (expanded);
11878
11879           if (expanded == error_mark_node)
11880             return error_mark_node;
11881           else if (PACK_EXPANSION_P (expanded)
11882                    || (TREE_CODE (expanded) == TREE_VEC
11883                        && len > 0
11884                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11885             {
11886               if (TREE_CODE (expanded) == TREE_VEC)
11887                 expanded = TREE_VEC_ELT (expanded, len - 1);
11888
11889               if (TYPE_P (expanded))
11890                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11891                                                    complain & tf_error);
11892               else
11893                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11894                                                    complain & tf_error);
11895             }
11896           else
11897             return build_int_cst (size_type_node, len);
11898         }
11899       /* Fall through */
11900
11901     case INDIRECT_REF:
11902     case NEGATE_EXPR:
11903     case TRUTH_NOT_EXPR:
11904     case BIT_NOT_EXPR:
11905     case ADDR_EXPR:
11906     case UNARY_PLUS_EXPR:      /* Unary + */
11907     case ALIGNOF_EXPR:
11908     case AT_ENCODE_EXPR:
11909     case ARROW_EXPR:
11910     case THROW_EXPR:
11911     case TYPEID_EXPR:
11912     case REALPART_EXPR:
11913     case IMAGPART_EXPR:
11914       return build1
11915         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11916          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11917
11918     case COMPONENT_REF:
11919       {
11920         tree object;
11921         tree name;
11922
11923         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11924         name = TREE_OPERAND (t, 1);
11925         if (TREE_CODE (name) == BIT_NOT_EXPR)
11926           {
11927             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11928                                 complain, in_decl);
11929             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11930           }
11931         else if (TREE_CODE (name) == SCOPE_REF
11932                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11933           {
11934             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11935                                      complain, in_decl);
11936             name = TREE_OPERAND (name, 1);
11937             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11938                                 complain, in_decl);
11939             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11940             name = build_qualified_name (/*type=*/NULL_TREE,
11941                                          base, name,
11942                                          /*template_p=*/false);
11943           }
11944         else if (TREE_CODE (name) == BASELINK)
11945           name = tsubst_baselink (name,
11946                                   non_reference (TREE_TYPE (object)),
11947                                   args, complain,
11948                                   in_decl);
11949         else
11950           name = tsubst_copy (name, args, complain, in_decl);
11951         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11952       }
11953
11954     case PLUS_EXPR:
11955     case MINUS_EXPR:
11956     case MULT_EXPR:
11957     case TRUNC_DIV_EXPR:
11958     case CEIL_DIV_EXPR:
11959     case FLOOR_DIV_EXPR:
11960     case ROUND_DIV_EXPR:
11961     case EXACT_DIV_EXPR:
11962     case BIT_AND_EXPR:
11963     case BIT_IOR_EXPR:
11964     case BIT_XOR_EXPR:
11965     case TRUNC_MOD_EXPR:
11966     case FLOOR_MOD_EXPR:
11967     case TRUTH_ANDIF_EXPR:
11968     case TRUTH_ORIF_EXPR:
11969     case TRUTH_AND_EXPR:
11970     case TRUTH_OR_EXPR:
11971     case RSHIFT_EXPR:
11972     case LSHIFT_EXPR:
11973     case RROTATE_EXPR:
11974     case LROTATE_EXPR:
11975     case EQ_EXPR:
11976     case NE_EXPR:
11977     case MAX_EXPR:
11978     case MIN_EXPR:
11979     case LE_EXPR:
11980     case GE_EXPR:
11981     case LT_EXPR:
11982     case GT_EXPR:
11983     case COMPOUND_EXPR:
11984     case DOTSTAR_EXPR:
11985     case MEMBER_REF:
11986     case PREDECREMENT_EXPR:
11987     case PREINCREMENT_EXPR:
11988     case POSTDECREMENT_EXPR:
11989     case POSTINCREMENT_EXPR:
11990       return build_nt
11991         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11992          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11993
11994     case SCOPE_REF:
11995       return build_qualified_name (/*type=*/NULL_TREE,
11996                                    tsubst_copy (TREE_OPERAND (t, 0),
11997                                                 args, complain, in_decl),
11998                                    tsubst_copy (TREE_OPERAND (t, 1),
11999                                                 args, complain, in_decl),
12000                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12001
12002     case ARRAY_REF:
12003       return build_nt
12004         (ARRAY_REF,
12005          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12006          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12007          NULL_TREE, NULL_TREE);
12008
12009     case CALL_EXPR:
12010       {
12011         int n = VL_EXP_OPERAND_LENGTH (t);
12012         tree result = build_vl_exp (CALL_EXPR, n);
12013         int i;
12014         for (i = 0; i < n; i++)
12015           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12016                                              complain, in_decl);
12017         return result;
12018       }
12019
12020     case COND_EXPR:
12021     case MODOP_EXPR:
12022     case PSEUDO_DTOR_EXPR:
12023       {
12024         r = build_nt
12025           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12026            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12027            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12028         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12029         return r;
12030       }
12031
12032     case NEW_EXPR:
12033       {
12034         r = build_nt
12035         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12036          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12037          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12038         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12039         return r;
12040       }
12041
12042     case DELETE_EXPR:
12043       {
12044         r = build_nt
12045         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12046          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12047         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12048         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12049         return r;
12050       }
12051
12052     case TEMPLATE_ID_EXPR:
12053       {
12054         /* Substituted template arguments */
12055         tree fn = TREE_OPERAND (t, 0);
12056         tree targs = TREE_OPERAND (t, 1);
12057
12058         fn = tsubst_copy (fn, args, complain, in_decl);
12059         if (targs)
12060           targs = tsubst_template_args (targs, args, complain, in_decl);
12061
12062         return lookup_template_function (fn, targs);
12063       }
12064
12065     case TREE_LIST:
12066       {
12067         tree purpose, value, chain;
12068
12069         if (t == void_list_node)
12070           return t;
12071
12072         purpose = TREE_PURPOSE (t);
12073         if (purpose)
12074           purpose = tsubst_copy (purpose, args, complain, in_decl);
12075         value = TREE_VALUE (t);
12076         if (value)
12077           value = tsubst_copy (value, args, complain, in_decl);
12078         chain = TREE_CHAIN (t);
12079         if (chain && chain != void_type_node)
12080           chain = tsubst_copy (chain, args, complain, in_decl);
12081         if (purpose == TREE_PURPOSE (t)
12082             && value == TREE_VALUE (t)
12083             && chain == TREE_CHAIN (t))
12084           return t;
12085         return tree_cons (purpose, value, chain);
12086       }
12087
12088     case RECORD_TYPE:
12089     case UNION_TYPE:
12090     case ENUMERAL_TYPE:
12091     case INTEGER_TYPE:
12092     case TEMPLATE_TYPE_PARM:
12093     case TEMPLATE_TEMPLATE_PARM:
12094     case BOUND_TEMPLATE_TEMPLATE_PARM:
12095     case TEMPLATE_PARM_INDEX:
12096     case POINTER_TYPE:
12097     case REFERENCE_TYPE:
12098     case OFFSET_TYPE:
12099     case FUNCTION_TYPE:
12100     case METHOD_TYPE:
12101     case ARRAY_TYPE:
12102     case TYPENAME_TYPE:
12103     case UNBOUND_CLASS_TEMPLATE:
12104     case TYPEOF_TYPE:
12105     case DECLTYPE_TYPE:
12106     case TYPE_DECL:
12107       return tsubst (t, args, complain, in_decl);
12108
12109     case IDENTIFIER_NODE:
12110       if (IDENTIFIER_TYPENAME_P (t))
12111         {
12112           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12113           return mangle_conv_op_name_for_type (new_type);
12114         }
12115       else
12116         return t;
12117
12118     case CONSTRUCTOR:
12119       /* This is handled by tsubst_copy_and_build.  */
12120       gcc_unreachable ();
12121
12122     case VA_ARG_EXPR:
12123       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12124                                           in_decl),
12125                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12126
12127     case CLEANUP_POINT_EXPR:
12128       /* We shouldn't have built any of these during initial template
12129          generation.  Instead, they should be built during instantiation
12130          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12131       gcc_unreachable ();
12132
12133     case OFFSET_REF:
12134       r = build2
12135         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12136          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12137          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12138       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12139       mark_used (TREE_OPERAND (r, 1));
12140       return r;
12141
12142     case EXPR_PACK_EXPANSION:
12143       error ("invalid use of pack expansion expression");
12144       return error_mark_node;
12145
12146     case NONTYPE_ARGUMENT_PACK:
12147       error ("use %<...%> to expand argument pack");
12148       return error_mark_node;
12149
12150     case INTEGER_CST:
12151     case REAL_CST:
12152     case STRING_CST:
12153     case COMPLEX_CST:
12154       {
12155         /* Instantiate any typedefs in the type.  */
12156         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12157         r = fold_convert (type, t);
12158         gcc_assert (TREE_CODE (r) == code);
12159         return r;
12160       }
12161
12162     case PTRMEM_CST:
12163       /* These can sometimes show up in a partial instantiation, but never
12164          involve template parms.  */
12165       gcc_assert (!uses_template_parms (t));
12166       return t;
12167
12168     default:
12169       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12170       gcc_checking_assert (false);
12171       return t;
12172     }
12173 }
12174
12175 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12176
12177 static tree
12178 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12179                     tree in_decl)
12180 {
12181   tree new_clauses = NULL, nc, oc;
12182
12183   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12184     {
12185       nc = copy_node (oc);
12186       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12187       new_clauses = nc;
12188
12189       switch (OMP_CLAUSE_CODE (nc))
12190         {
12191         case OMP_CLAUSE_LASTPRIVATE:
12192           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12193             {
12194               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12195               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12196                            in_decl, /*integral_constant_expression_p=*/false);
12197               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12198                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12199             }
12200           /* FALLTHRU */
12201         case OMP_CLAUSE_PRIVATE:
12202         case OMP_CLAUSE_SHARED:
12203         case OMP_CLAUSE_FIRSTPRIVATE:
12204         case OMP_CLAUSE_REDUCTION:
12205         case OMP_CLAUSE_COPYIN:
12206         case OMP_CLAUSE_COPYPRIVATE:
12207         case OMP_CLAUSE_IF:
12208         case OMP_CLAUSE_NUM_THREADS:
12209         case OMP_CLAUSE_SCHEDULE:
12210         case OMP_CLAUSE_COLLAPSE:
12211         case OMP_CLAUSE_FINAL:
12212           OMP_CLAUSE_OPERAND (nc, 0)
12213             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12214                            in_decl, /*integral_constant_expression_p=*/false);
12215           break;
12216         case OMP_CLAUSE_NOWAIT:
12217         case OMP_CLAUSE_ORDERED:
12218         case OMP_CLAUSE_DEFAULT:
12219         case OMP_CLAUSE_UNTIED:
12220         case OMP_CLAUSE_MERGEABLE:
12221           break;
12222         default:
12223           gcc_unreachable ();
12224         }
12225     }
12226
12227   return finish_omp_clauses (nreverse (new_clauses));
12228 }
12229
12230 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12231
12232 static tree
12233 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12234                           tree in_decl)
12235 {
12236 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12237
12238   tree purpose, value, chain;
12239
12240   if (t == NULL)
12241     return t;
12242
12243   if (TREE_CODE (t) != TREE_LIST)
12244     return tsubst_copy_and_build (t, args, complain, in_decl,
12245                                   /*function_p=*/false,
12246                                   /*integral_constant_expression_p=*/false);
12247
12248   if (t == void_list_node)
12249     return t;
12250
12251   purpose = TREE_PURPOSE (t);
12252   if (purpose)
12253     purpose = RECUR (purpose);
12254   value = TREE_VALUE (t);
12255   if (value && TREE_CODE (value) != LABEL_DECL)
12256     value = RECUR (value);
12257   chain = TREE_CHAIN (t);
12258   if (chain && chain != void_type_node)
12259     chain = RECUR (chain);
12260   return tree_cons (purpose, value, chain);
12261 #undef RECUR
12262 }
12263
12264 /* Substitute one OMP_FOR iterator.  */
12265
12266 static void
12267 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12268                          tree condv, tree incrv, tree *clauses,
12269                          tree args, tsubst_flags_t complain, tree in_decl,
12270                          bool integral_constant_expression_p)
12271 {
12272 #define RECUR(NODE)                             \
12273   tsubst_expr ((NODE), args, complain, in_decl, \
12274                integral_constant_expression_p)
12275   tree decl, init, cond, incr, auto_node;
12276
12277   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12278   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12279   decl = RECUR (TREE_OPERAND (init, 0));
12280   init = TREE_OPERAND (init, 1);
12281   auto_node = type_uses_auto (TREE_TYPE (decl));
12282   if (auto_node && init)
12283     {
12284       tree init_expr = init;
12285       if (TREE_CODE (init_expr) == DECL_EXPR)
12286         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12287       init_expr = RECUR (init_expr);
12288       TREE_TYPE (decl)
12289         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12290     }
12291   gcc_assert (!type_dependent_expression_p (decl));
12292
12293   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12294     {
12295       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12296       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12297       if (TREE_CODE (incr) == MODIFY_EXPR)
12298         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12299                                     RECUR (TREE_OPERAND (incr, 1)),
12300                                     complain);
12301       else
12302         incr = RECUR (incr);
12303       TREE_VEC_ELT (declv, i) = decl;
12304       TREE_VEC_ELT (initv, i) = init;
12305       TREE_VEC_ELT (condv, i) = cond;
12306       TREE_VEC_ELT (incrv, i) = incr;
12307       return;
12308     }
12309
12310   if (init && TREE_CODE (init) != DECL_EXPR)
12311     {
12312       tree c;
12313       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12314         {
12315           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12316                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12317               && OMP_CLAUSE_DECL (c) == decl)
12318             break;
12319           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12320                    && OMP_CLAUSE_DECL (c) == decl)
12321             error ("iteration variable %qD should not be firstprivate", decl);
12322           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12323                    && OMP_CLAUSE_DECL (c) == decl)
12324             error ("iteration variable %qD should not be reduction", decl);
12325         }
12326       if (c == NULL)
12327         {
12328           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12329           OMP_CLAUSE_DECL (c) = decl;
12330           c = finish_omp_clauses (c);
12331           if (c)
12332             {
12333               OMP_CLAUSE_CHAIN (c) = *clauses;
12334               *clauses = c;
12335             }
12336         }
12337     }
12338   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12339   if (COMPARISON_CLASS_P (cond))
12340     cond = build2 (TREE_CODE (cond), boolean_type_node,
12341                    RECUR (TREE_OPERAND (cond, 0)),
12342                    RECUR (TREE_OPERAND (cond, 1)));
12343   else
12344     cond = RECUR (cond);
12345   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12346   switch (TREE_CODE (incr))
12347     {
12348     case PREINCREMENT_EXPR:
12349     case PREDECREMENT_EXPR:
12350     case POSTINCREMENT_EXPR:
12351     case POSTDECREMENT_EXPR:
12352       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12353                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12354       break;
12355     case MODIFY_EXPR:
12356       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12357           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12358         {
12359           tree rhs = TREE_OPERAND (incr, 1);
12360           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12361                          RECUR (TREE_OPERAND (incr, 0)),
12362                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12363                                  RECUR (TREE_OPERAND (rhs, 0)),
12364                                  RECUR (TREE_OPERAND (rhs, 1))));
12365         }
12366       else
12367         incr = RECUR (incr);
12368       break;
12369     case MODOP_EXPR:
12370       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12371           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12372         {
12373           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12374           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12375                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12376                                  TREE_TYPE (decl), lhs,
12377                                  RECUR (TREE_OPERAND (incr, 2))));
12378         }
12379       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12380                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12381                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12382         {
12383           tree rhs = TREE_OPERAND (incr, 2);
12384           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12385                          RECUR (TREE_OPERAND (incr, 0)),
12386                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12387                                  RECUR (TREE_OPERAND (rhs, 0)),
12388                                  RECUR (TREE_OPERAND (rhs, 1))));
12389         }
12390       else
12391         incr = RECUR (incr);
12392       break;
12393     default:
12394       incr = RECUR (incr);
12395       break;
12396     }
12397
12398   TREE_VEC_ELT (declv, i) = decl;
12399   TREE_VEC_ELT (initv, i) = init;
12400   TREE_VEC_ELT (condv, i) = cond;
12401   TREE_VEC_ELT (incrv, i) = incr;
12402 #undef RECUR
12403 }
12404
12405 /* Like tsubst_copy for expressions, etc. but also does semantic
12406    processing.  */
12407
12408 static tree
12409 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12410              bool integral_constant_expression_p)
12411 {
12412 #define RECUR(NODE)                             \
12413   tsubst_expr ((NODE), args, complain, in_decl, \
12414                integral_constant_expression_p)
12415
12416   tree stmt, tmp;
12417
12418   if (t == NULL_TREE || t == error_mark_node)
12419     return t;
12420
12421   if (EXPR_HAS_LOCATION (t))
12422     input_location = EXPR_LOCATION (t);
12423   if (STATEMENT_CODE_P (TREE_CODE (t)))
12424     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12425
12426   switch (TREE_CODE (t))
12427     {
12428     case STATEMENT_LIST:
12429       {
12430         tree_stmt_iterator i;
12431         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12432           RECUR (tsi_stmt (i));
12433         break;
12434       }
12435
12436     case CTOR_INITIALIZER:
12437       finish_mem_initializers (tsubst_initializer_list
12438                                (TREE_OPERAND (t, 0), args));
12439       break;
12440
12441     case RETURN_EXPR:
12442       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12443       break;
12444
12445     case EXPR_STMT:
12446       tmp = RECUR (EXPR_STMT_EXPR (t));
12447       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12448         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12449       else
12450         finish_expr_stmt (tmp);
12451       break;
12452
12453     case USING_STMT:
12454       do_using_directive (USING_STMT_NAMESPACE (t));
12455       break;
12456
12457     case DECL_EXPR:
12458       {
12459         tree decl, pattern_decl;
12460         tree init;
12461
12462         pattern_decl = decl = DECL_EXPR_DECL (t);
12463         if (TREE_CODE (decl) == LABEL_DECL)
12464           finish_label_decl (DECL_NAME (decl));
12465         else if (TREE_CODE (decl) == USING_DECL)
12466           {
12467             tree scope = USING_DECL_SCOPE (decl);
12468             tree name = DECL_NAME (decl);
12469             tree decl;
12470
12471             scope = tsubst (scope, args, complain, in_decl);
12472             decl = lookup_qualified_name (scope, name,
12473                                           /*is_type_p=*/false,
12474                                           /*complain=*/false);
12475             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12476               qualified_name_lookup_error (scope, name, decl, input_location);
12477             else
12478               do_local_using_decl (decl, scope, name);
12479           }
12480         else
12481           {
12482             init = DECL_INITIAL (decl);
12483             decl = tsubst (decl, args, complain, in_decl);
12484             if (decl != error_mark_node)
12485               {
12486                 /* By marking the declaration as instantiated, we avoid
12487                    trying to instantiate it.  Since instantiate_decl can't
12488                    handle local variables, and since we've already done
12489                    all that needs to be done, that's the right thing to
12490                    do.  */
12491                 if (TREE_CODE (decl) == VAR_DECL)
12492                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12493                 if (TREE_CODE (decl) == VAR_DECL
12494                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12495                   /* Anonymous aggregates are a special case.  */
12496                   finish_anon_union (decl);
12497                 else
12498                   {
12499                     int const_init = false;
12500                     maybe_push_decl (decl);
12501                     if (TREE_CODE (decl) == VAR_DECL
12502                         && DECL_PRETTY_FUNCTION_P (decl))
12503                       {
12504                         /* For __PRETTY_FUNCTION__ we have to adjust the
12505                            initializer.  */
12506                         const char *const name
12507                           = cxx_printable_name (current_function_decl, 2);
12508                         init = cp_fname_init (name, &TREE_TYPE (decl));
12509                       }
12510                     else
12511                       {
12512                         tree t = RECUR (init);
12513
12514                         if (init && !t)
12515                           {
12516                             /* If we had an initializer but it
12517                                instantiated to nothing,
12518                                value-initialize the object.  This will
12519                                only occur when the initializer was a
12520                                pack expansion where the parameter packs
12521                                used in that expansion were of length
12522                                zero.  */
12523                             init = build_value_init (TREE_TYPE (decl),
12524                                                      complain);
12525                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12526                               init = get_target_expr_sfinae (init, complain);
12527                           }
12528                         else
12529                           init = t;
12530                       }
12531
12532                     if (TREE_CODE (decl) == VAR_DECL)
12533                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12534                                     (pattern_decl));
12535                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12536                   }
12537               }
12538           }
12539
12540         /* A DECL_EXPR can also be used as an expression, in the condition
12541            clause of an if/for/while construct.  */
12542         return decl;
12543       }
12544
12545     case FOR_STMT:
12546       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12547       RECUR (FOR_INIT_STMT (t));
12548       finish_for_init_stmt (stmt);
12549       tmp = RECUR (FOR_COND (t));
12550       finish_for_cond (tmp, stmt);
12551       tmp = RECUR (FOR_EXPR (t));
12552       finish_for_expr (tmp, stmt);
12553       RECUR (FOR_BODY (t));
12554       finish_for_stmt (stmt);
12555       break;
12556
12557     case RANGE_FOR_STMT:
12558       {
12559         tree decl, expr;
12560         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12561         decl = RANGE_FOR_DECL (t);
12562         decl = tsubst (decl, args, complain, in_decl);
12563         maybe_push_decl (decl);
12564         expr = RECUR (RANGE_FOR_EXPR (t));
12565         stmt = cp_convert_range_for (stmt, decl, expr);
12566         RECUR (RANGE_FOR_BODY (t));
12567         finish_for_stmt (stmt);
12568       }
12569       break;
12570
12571     case WHILE_STMT:
12572       stmt = begin_while_stmt ();
12573       tmp = RECUR (WHILE_COND (t));
12574       finish_while_stmt_cond (tmp, stmt);
12575       RECUR (WHILE_BODY (t));
12576       finish_while_stmt (stmt);
12577       break;
12578
12579     case DO_STMT:
12580       stmt = begin_do_stmt ();
12581       RECUR (DO_BODY (t));
12582       finish_do_body (stmt);
12583       tmp = RECUR (DO_COND (t));
12584       finish_do_stmt (tmp, stmt);
12585       break;
12586
12587     case IF_STMT:
12588       stmt = begin_if_stmt ();
12589       tmp = RECUR (IF_COND (t));
12590       finish_if_stmt_cond (tmp, stmt);
12591       RECUR (THEN_CLAUSE (t));
12592       finish_then_clause (stmt);
12593
12594       if (ELSE_CLAUSE (t))
12595         {
12596           begin_else_clause (stmt);
12597           RECUR (ELSE_CLAUSE (t));
12598           finish_else_clause (stmt);
12599         }
12600
12601       finish_if_stmt (stmt);
12602       break;
12603
12604     case BIND_EXPR:
12605       if (BIND_EXPR_BODY_BLOCK (t))
12606         stmt = begin_function_body ();
12607       else
12608         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12609                                     ? BCS_TRY_BLOCK : 0);
12610
12611       RECUR (BIND_EXPR_BODY (t));
12612
12613       if (BIND_EXPR_BODY_BLOCK (t))
12614         finish_function_body (stmt);
12615       else
12616         finish_compound_stmt (stmt);
12617       break;
12618
12619     case BREAK_STMT:
12620       finish_break_stmt ();
12621       break;
12622
12623     case CONTINUE_STMT:
12624       finish_continue_stmt ();
12625       break;
12626
12627     case SWITCH_STMT:
12628       stmt = begin_switch_stmt ();
12629       tmp = RECUR (SWITCH_STMT_COND (t));
12630       finish_switch_cond (tmp, stmt);
12631       RECUR (SWITCH_STMT_BODY (t));
12632       finish_switch_stmt (stmt);
12633       break;
12634
12635     case CASE_LABEL_EXPR:
12636       finish_case_label (EXPR_LOCATION (t),
12637                          RECUR (CASE_LOW (t)),
12638                          RECUR (CASE_HIGH (t)));
12639       break;
12640
12641     case LABEL_EXPR:
12642       {
12643         tree decl = LABEL_EXPR_LABEL (t);
12644         tree label;
12645
12646         label = finish_label_stmt (DECL_NAME (decl));
12647         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12648           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12649       }
12650       break;
12651
12652     case GOTO_EXPR:
12653       tmp = GOTO_DESTINATION (t);
12654       if (TREE_CODE (tmp) != LABEL_DECL)
12655         /* Computed goto's must be tsubst'd into.  On the other hand,
12656            non-computed gotos must not be; the identifier in question
12657            will have no binding.  */
12658         tmp = RECUR (tmp);
12659       else
12660         tmp = DECL_NAME (tmp);
12661       finish_goto_stmt (tmp);
12662       break;
12663
12664     case ASM_EXPR:
12665       tmp = finish_asm_stmt
12666         (ASM_VOLATILE_P (t),
12667          RECUR (ASM_STRING (t)),
12668          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12669          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12670          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12671          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12672       {
12673         tree asm_expr = tmp;
12674         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12675           asm_expr = TREE_OPERAND (asm_expr, 0);
12676         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12677       }
12678       break;
12679
12680     case TRY_BLOCK:
12681       if (CLEANUP_P (t))
12682         {
12683           stmt = begin_try_block ();
12684           RECUR (TRY_STMTS (t));
12685           finish_cleanup_try_block (stmt);
12686           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12687         }
12688       else
12689         {
12690           tree compound_stmt = NULL_TREE;
12691
12692           if (FN_TRY_BLOCK_P (t))
12693             stmt = begin_function_try_block (&compound_stmt);
12694           else
12695             stmt = begin_try_block ();
12696
12697           RECUR (TRY_STMTS (t));
12698
12699           if (FN_TRY_BLOCK_P (t))
12700             finish_function_try_block (stmt);
12701           else
12702             finish_try_block (stmt);
12703
12704           RECUR (TRY_HANDLERS (t));
12705           if (FN_TRY_BLOCK_P (t))
12706             finish_function_handler_sequence (stmt, compound_stmt);
12707           else
12708             finish_handler_sequence (stmt);
12709         }
12710       break;
12711
12712     case HANDLER:
12713       {
12714         tree decl = HANDLER_PARMS (t);
12715
12716         if (decl)
12717           {
12718             decl = tsubst (decl, args, complain, in_decl);
12719             /* Prevent instantiate_decl from trying to instantiate
12720                this variable.  We've already done all that needs to be
12721                done.  */
12722             if (decl != error_mark_node)
12723               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12724           }
12725         stmt = begin_handler ();
12726         finish_handler_parms (decl, stmt);
12727         RECUR (HANDLER_BODY (t));
12728         finish_handler (stmt);
12729       }
12730       break;
12731
12732     case TAG_DEFN:
12733       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12734       break;
12735
12736     case STATIC_ASSERT:
12737       {
12738         tree condition = 
12739           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12740                        args,
12741                        complain, in_decl,
12742                        /*integral_constant_expression_p=*/true);
12743         finish_static_assert (condition,
12744                               STATIC_ASSERT_MESSAGE (t),
12745                               STATIC_ASSERT_SOURCE_LOCATION (t),
12746                               /*member_p=*/false);
12747       }
12748       break;
12749
12750     case OMP_PARALLEL:
12751       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12752                                 args, complain, in_decl);
12753       stmt = begin_omp_parallel ();
12754       RECUR (OMP_PARALLEL_BODY (t));
12755       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12756         = OMP_PARALLEL_COMBINED (t);
12757       break;
12758
12759     case OMP_TASK:
12760       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12761                                 args, complain, in_decl);
12762       stmt = begin_omp_task ();
12763       RECUR (OMP_TASK_BODY (t));
12764       finish_omp_task (tmp, stmt);
12765       break;
12766
12767     case OMP_FOR:
12768       {
12769         tree clauses, body, pre_body;
12770         tree declv, initv, condv, incrv;
12771         int i;
12772
12773         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12774                                       args, complain, in_decl);
12775         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12776         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12777         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12778         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12779
12780         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12781           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12782                                    &clauses, args, complain, in_decl,
12783                                    integral_constant_expression_p);
12784
12785         stmt = begin_omp_structured_block ();
12786
12787         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12788           if (TREE_VEC_ELT (initv, i) == NULL
12789               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12790             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12791           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12792             {
12793               tree init = RECUR (TREE_VEC_ELT (initv, i));
12794               gcc_assert (init == TREE_VEC_ELT (declv, i));
12795               TREE_VEC_ELT (initv, i) = NULL_TREE;
12796             }
12797           else
12798             {
12799               tree decl_expr = TREE_VEC_ELT (initv, i);
12800               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12801               gcc_assert (init != NULL);
12802               TREE_VEC_ELT (initv, i) = RECUR (init);
12803               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12804               RECUR (decl_expr);
12805               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12806             }
12807
12808         pre_body = push_stmt_list ();
12809         RECUR (OMP_FOR_PRE_BODY (t));
12810         pre_body = pop_stmt_list (pre_body);
12811
12812         body = push_stmt_list ();
12813         RECUR (OMP_FOR_BODY (t));
12814         body = pop_stmt_list (body);
12815
12816         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12817                             body, pre_body, clauses);
12818
12819         add_stmt (finish_omp_structured_block (stmt));
12820       }
12821       break;
12822
12823     case OMP_SECTIONS:
12824     case OMP_SINGLE:
12825       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12826       stmt = push_stmt_list ();
12827       RECUR (OMP_BODY (t));
12828       stmt = pop_stmt_list (stmt);
12829
12830       t = copy_node (t);
12831       OMP_BODY (t) = stmt;
12832       OMP_CLAUSES (t) = tmp;
12833       add_stmt (t);
12834       break;
12835
12836     case OMP_SECTION:
12837     case OMP_CRITICAL:
12838     case OMP_MASTER:
12839     case OMP_ORDERED:
12840       stmt = push_stmt_list ();
12841       RECUR (OMP_BODY (t));
12842       stmt = pop_stmt_list (stmt);
12843
12844       t = copy_node (t);
12845       OMP_BODY (t) = stmt;
12846       add_stmt (t);
12847       break;
12848
12849     case OMP_ATOMIC:
12850       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12851       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12852         {
12853           tree op1 = TREE_OPERAND (t, 1);
12854           tree rhs1 = NULL_TREE;
12855           tree lhs, rhs;
12856           if (TREE_CODE (op1) == COMPOUND_EXPR)
12857             {
12858               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12859               op1 = TREE_OPERAND (op1, 1);
12860             }
12861           lhs = RECUR (TREE_OPERAND (op1, 0));
12862           rhs = RECUR (TREE_OPERAND (op1, 1));
12863           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12864                              NULL_TREE, NULL_TREE, rhs1);
12865         }
12866       else
12867         {
12868           tree op1 = TREE_OPERAND (t, 1);
12869           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12870           tree rhs1 = NULL_TREE;
12871           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12872           enum tree_code opcode = NOP_EXPR;
12873           if (code == OMP_ATOMIC_READ)
12874             {
12875               v = RECUR (TREE_OPERAND (op1, 0));
12876               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12877             }
12878           else if (code == OMP_ATOMIC_CAPTURE_OLD
12879                    || code == OMP_ATOMIC_CAPTURE_NEW)
12880             {
12881               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12882               v = RECUR (TREE_OPERAND (op1, 0));
12883               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12884               if (TREE_CODE (op11) == COMPOUND_EXPR)
12885                 {
12886                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12887                   op11 = TREE_OPERAND (op11, 1);
12888                 }
12889               lhs = RECUR (TREE_OPERAND (op11, 0));
12890               rhs = RECUR (TREE_OPERAND (op11, 1));
12891               opcode = TREE_CODE (op11);
12892             }
12893           else
12894             {
12895               code = OMP_ATOMIC;
12896               lhs = RECUR (TREE_OPERAND (op1, 0));
12897               rhs = RECUR (TREE_OPERAND (op1, 1));
12898             }
12899           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
12900         }
12901       break;
12902
12903     case EXPR_PACK_EXPANSION:
12904       error ("invalid use of pack expansion expression");
12905       return error_mark_node;
12906
12907     case NONTYPE_ARGUMENT_PACK:
12908       error ("use %<...%> to expand argument pack");
12909       return error_mark_node;
12910
12911     default:
12912       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12913
12914       return tsubst_copy_and_build (t, args, complain, in_decl,
12915                                     /*function_p=*/false,
12916                                     integral_constant_expression_p);
12917     }
12918
12919   return NULL_TREE;
12920 #undef RECUR
12921 }
12922
12923 /* T is a postfix-expression that is not being used in a function
12924    call.  Return the substituted version of T.  */
12925
12926 static tree
12927 tsubst_non_call_postfix_expression (tree t, tree args,
12928                                     tsubst_flags_t complain,
12929                                     tree in_decl)
12930 {
12931   if (TREE_CODE (t) == SCOPE_REF)
12932     t = tsubst_qualified_id (t, args, complain, in_decl,
12933                              /*done=*/false, /*address_p=*/false);
12934   else
12935     t = tsubst_copy_and_build (t, args, complain, in_decl,
12936                                /*function_p=*/false,
12937                                /*integral_constant_expression_p=*/false);
12938
12939   return t;
12940 }
12941
12942 /* Like tsubst but deals with expressions and performs semantic
12943    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12944
12945 tree
12946 tsubst_copy_and_build (tree t,
12947                        tree args,
12948                        tsubst_flags_t complain,
12949                        tree in_decl,
12950                        bool function_p,
12951                        bool integral_constant_expression_p)
12952 {
12953 #define RECUR(NODE)                                             \
12954   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12955                          /*function_p=*/false,                  \
12956                          integral_constant_expression_p)
12957
12958   tree op1;
12959
12960   if (t == NULL_TREE || t == error_mark_node)
12961     return t;
12962
12963   switch (TREE_CODE (t))
12964     {
12965     case USING_DECL:
12966       t = DECL_NAME (t);
12967       /* Fall through.  */
12968     case IDENTIFIER_NODE:
12969       {
12970         tree decl;
12971         cp_id_kind idk;
12972         bool non_integral_constant_expression_p;
12973         const char *error_msg;
12974
12975         if (IDENTIFIER_TYPENAME_P (t))
12976           {
12977             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12978             t = mangle_conv_op_name_for_type (new_type);
12979           }
12980
12981         /* Look up the name.  */
12982         decl = lookup_name (t);
12983
12984         /* By convention, expressions use ERROR_MARK_NODE to indicate
12985            failure, not NULL_TREE.  */
12986         if (decl == NULL_TREE)
12987           decl = error_mark_node;
12988
12989         decl = finish_id_expression (t, decl, NULL_TREE,
12990                                      &idk,
12991                                      integral_constant_expression_p,
12992                                      /*allow_non_integral_constant_expression_p=*/false,
12993                                      &non_integral_constant_expression_p,
12994                                      /*template_p=*/false,
12995                                      /*done=*/true,
12996                                      /*address_p=*/false,
12997                                      /*template_arg_p=*/false,
12998                                      &error_msg,
12999                                      input_location);
13000         if (error_msg)
13001           error (error_msg);
13002         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13003           decl = unqualified_name_lookup_error (decl);
13004         return decl;
13005       }
13006
13007     case TEMPLATE_ID_EXPR:
13008       {
13009         tree object;
13010         tree templ = RECUR (TREE_OPERAND (t, 0));
13011         tree targs = TREE_OPERAND (t, 1);
13012
13013         if (targs)
13014           targs = tsubst_template_args (targs, args, complain, in_decl);
13015
13016         if (TREE_CODE (templ) == COMPONENT_REF)
13017           {
13018             object = TREE_OPERAND (templ, 0);
13019             templ = TREE_OPERAND (templ, 1);
13020           }
13021         else
13022           object = NULL_TREE;
13023         templ = lookup_template_function (templ, targs);
13024
13025         if (object)
13026           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13027                          object, templ, NULL_TREE);
13028         else
13029           return baselink_for_fns (templ);
13030       }
13031
13032     case INDIRECT_REF:
13033       {
13034         tree r = RECUR (TREE_OPERAND (t, 0));
13035
13036         if (REFERENCE_REF_P (t))
13037           {
13038             /* A type conversion to reference type will be enclosed in
13039                such an indirect ref, but the substitution of the cast
13040                will have also added such an indirect ref.  */
13041             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13042               r = convert_from_reference (r);
13043           }
13044         else
13045           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13046         return r;
13047       }
13048
13049     case NOP_EXPR:
13050       return build_nop
13051         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13052          RECUR (TREE_OPERAND (t, 0)));
13053
13054     case CAST_EXPR:
13055     case REINTERPRET_CAST_EXPR:
13056     case CONST_CAST_EXPR:
13057     case DYNAMIC_CAST_EXPR:
13058     case STATIC_CAST_EXPR:
13059       {
13060         tree type;
13061         tree op;
13062
13063         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13064         if (integral_constant_expression_p
13065             && !cast_valid_in_integral_constant_expression_p (type))
13066           {
13067             if (complain & tf_error)
13068               error ("a cast to a type other than an integral or "
13069                      "enumeration type cannot appear in a constant-expression");
13070             return error_mark_node; 
13071           }
13072
13073         op = RECUR (TREE_OPERAND (t, 0));
13074
13075         switch (TREE_CODE (t))
13076           {
13077           case CAST_EXPR:
13078             return build_functional_cast (type, op, complain);
13079           case REINTERPRET_CAST_EXPR:
13080             return build_reinterpret_cast (type, op, complain);
13081           case CONST_CAST_EXPR:
13082             return build_const_cast (type, op, complain);
13083           case DYNAMIC_CAST_EXPR:
13084             return build_dynamic_cast (type, op, complain);
13085           case STATIC_CAST_EXPR:
13086             return build_static_cast (type, op, complain);
13087           default:
13088             gcc_unreachable ();
13089           }
13090       }
13091
13092     case POSTDECREMENT_EXPR:
13093     case POSTINCREMENT_EXPR:
13094       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13095                                                 args, complain, in_decl);
13096       return build_x_unary_op (TREE_CODE (t), op1, complain);
13097
13098     case PREDECREMENT_EXPR:
13099     case PREINCREMENT_EXPR:
13100     case NEGATE_EXPR:
13101     case BIT_NOT_EXPR:
13102     case ABS_EXPR:
13103     case TRUTH_NOT_EXPR:
13104     case UNARY_PLUS_EXPR:  /* Unary + */
13105     case REALPART_EXPR:
13106     case IMAGPART_EXPR:
13107       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13108                                complain);
13109
13110     case ADDR_EXPR:
13111       op1 = TREE_OPERAND (t, 0);
13112       if (TREE_CODE (op1) == LABEL_DECL)
13113         return finish_label_address_expr (DECL_NAME (op1),
13114                                           EXPR_LOCATION (op1));
13115       if (TREE_CODE (op1) == SCOPE_REF)
13116         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13117                                    /*done=*/true, /*address_p=*/true);
13118       else
13119         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13120                                                   in_decl);
13121       return build_x_unary_op (ADDR_EXPR, op1, complain);
13122
13123     case PLUS_EXPR:
13124     case MINUS_EXPR:
13125     case MULT_EXPR:
13126     case TRUNC_DIV_EXPR:
13127     case CEIL_DIV_EXPR:
13128     case FLOOR_DIV_EXPR:
13129     case ROUND_DIV_EXPR:
13130     case EXACT_DIV_EXPR:
13131     case BIT_AND_EXPR:
13132     case BIT_IOR_EXPR:
13133     case BIT_XOR_EXPR:
13134     case TRUNC_MOD_EXPR:
13135     case FLOOR_MOD_EXPR:
13136     case TRUTH_ANDIF_EXPR:
13137     case TRUTH_ORIF_EXPR:
13138     case TRUTH_AND_EXPR:
13139     case TRUTH_OR_EXPR:
13140     case RSHIFT_EXPR:
13141     case LSHIFT_EXPR:
13142     case RROTATE_EXPR:
13143     case LROTATE_EXPR:
13144     case EQ_EXPR:
13145     case NE_EXPR:
13146     case MAX_EXPR:
13147     case MIN_EXPR:
13148     case LE_EXPR:
13149     case GE_EXPR:
13150     case LT_EXPR:
13151     case GT_EXPR:
13152     case MEMBER_REF:
13153     case DOTSTAR_EXPR:
13154       return build_x_binary_op
13155         (TREE_CODE (t),
13156          RECUR (TREE_OPERAND (t, 0)),
13157          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13158           ? ERROR_MARK
13159           : TREE_CODE (TREE_OPERAND (t, 0))),
13160          RECUR (TREE_OPERAND (t, 1)),
13161          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13162           ? ERROR_MARK
13163           : TREE_CODE (TREE_OPERAND (t, 1))),
13164          /*overload=*/NULL,
13165          complain);
13166
13167     case SCOPE_REF:
13168       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13169                                   /*address_p=*/false);
13170     case ARRAY_REF:
13171       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13172                                                 args, complain, in_decl);
13173       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13174
13175     case SIZEOF_EXPR:
13176       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13177         return tsubst_copy (t, args, complain, in_decl);
13178       /* Fall through */
13179       
13180     case ALIGNOF_EXPR:
13181       op1 = TREE_OPERAND (t, 0);
13182       if (!args)
13183         {
13184           /* When there are no ARGS, we are trying to evaluate a
13185              non-dependent expression from the parser.  Trying to do
13186              the substitutions may not work.  */
13187           if (!TYPE_P (op1))
13188             op1 = TREE_TYPE (op1);
13189         }
13190       else
13191         {
13192           ++cp_unevaluated_operand;
13193           ++c_inhibit_evaluation_warnings;
13194           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13195                                        /*function_p=*/false,
13196                                        /*integral_constant_expression_p=*/false);
13197           --cp_unevaluated_operand;
13198           --c_inhibit_evaluation_warnings;
13199         }
13200       if (TYPE_P (op1))
13201         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13202                                            complain & tf_error);
13203       else
13204         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13205                                            complain & tf_error);
13206
13207     case AT_ENCODE_EXPR:
13208       {
13209         op1 = TREE_OPERAND (t, 0);
13210         ++cp_unevaluated_operand;
13211         ++c_inhibit_evaluation_warnings;
13212         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13213                                      /*function_p=*/false,
13214                                      /*integral_constant_expression_p=*/false);
13215         --cp_unevaluated_operand;
13216         --c_inhibit_evaluation_warnings;
13217         return objc_build_encode_expr (op1);
13218       }
13219
13220     case NOEXCEPT_EXPR:
13221       op1 = TREE_OPERAND (t, 0);
13222       ++cp_unevaluated_operand;
13223       ++c_inhibit_evaluation_warnings;
13224       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13225                                    /*function_p=*/false,
13226                                    /*integral_constant_expression_p=*/false);
13227       --cp_unevaluated_operand;
13228       --c_inhibit_evaluation_warnings;
13229       return finish_noexcept_expr (op1, complain);
13230
13231     case MODOP_EXPR:
13232       {
13233         tree r = build_x_modify_expr
13234           (RECUR (TREE_OPERAND (t, 0)),
13235            TREE_CODE (TREE_OPERAND (t, 1)),
13236            RECUR (TREE_OPERAND (t, 2)),
13237            complain);
13238         /* TREE_NO_WARNING must be set if either the expression was
13239            parenthesized or it uses an operator such as >>= rather
13240            than plain assignment.  In the former case, it was already
13241            set and must be copied.  In the latter case,
13242            build_x_modify_expr sets it and it must not be reset
13243            here.  */
13244         if (TREE_NO_WARNING (t))
13245           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13246         return r;
13247       }
13248
13249     case ARROW_EXPR:
13250       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13251                                                 args, complain, in_decl);
13252       /* Remember that there was a reference to this entity.  */
13253       if (DECL_P (op1))
13254         mark_used (op1);
13255       return build_x_arrow (op1);
13256
13257     case NEW_EXPR:
13258       {
13259         tree placement = RECUR (TREE_OPERAND (t, 0));
13260         tree init = RECUR (TREE_OPERAND (t, 3));
13261         VEC(tree,gc) *placement_vec;
13262         VEC(tree,gc) *init_vec;
13263         tree ret;
13264
13265         if (placement == NULL_TREE)
13266           placement_vec = NULL;
13267         else
13268           {
13269             placement_vec = make_tree_vector ();
13270             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13271               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13272           }
13273
13274         /* If there was an initializer in the original tree, but it
13275            instantiated to an empty list, then we should pass a
13276            non-NULL empty vector to tell build_new that it was an
13277            empty initializer() rather than no initializer.  This can
13278            only happen when the initializer is a pack expansion whose
13279            parameter packs are of length zero.  */
13280         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13281           init_vec = NULL;
13282         else
13283           {
13284             init_vec = make_tree_vector ();
13285             if (init == void_zero_node)
13286               gcc_assert (init_vec != NULL);
13287             else
13288               {
13289                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13290                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13291               }
13292           }
13293
13294         ret = build_new (&placement_vec,
13295                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13296                          RECUR (TREE_OPERAND (t, 2)),
13297                          &init_vec,
13298                          NEW_EXPR_USE_GLOBAL (t),
13299                          complain);
13300
13301         if (placement_vec != NULL)
13302           release_tree_vector (placement_vec);
13303         if (init_vec != NULL)
13304           release_tree_vector (init_vec);
13305
13306         return ret;
13307       }
13308
13309     case DELETE_EXPR:
13310      return delete_sanity
13311        (RECUR (TREE_OPERAND (t, 0)),
13312         RECUR (TREE_OPERAND (t, 1)),
13313         DELETE_EXPR_USE_VEC (t),
13314         DELETE_EXPR_USE_GLOBAL (t),
13315         complain);
13316
13317     case COMPOUND_EXPR:
13318       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13319                                     RECUR (TREE_OPERAND (t, 1)),
13320                                     complain);
13321
13322     case CALL_EXPR:
13323       {
13324         tree function;
13325         VEC(tree,gc) *call_args;
13326         unsigned int nargs, i;
13327         bool qualified_p;
13328         bool koenig_p;
13329         tree ret;
13330
13331         function = CALL_EXPR_FN (t);
13332         /* When we parsed the expression,  we determined whether or
13333            not Koenig lookup should be performed.  */
13334         koenig_p = KOENIG_LOOKUP_P (t);
13335         if (TREE_CODE (function) == SCOPE_REF)
13336           {
13337             qualified_p = true;
13338             function = tsubst_qualified_id (function, args, complain, in_decl,
13339                                             /*done=*/false,
13340                                             /*address_p=*/false);
13341           }
13342         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13343           {
13344             /* Do nothing; calling tsubst_copy_and_build on an identifier
13345                would incorrectly perform unqualified lookup again.
13346
13347                Note that we can also have an IDENTIFIER_NODE if the earlier
13348                unqualified lookup found a member function; in that case
13349                koenig_p will be false and we do want to do the lookup
13350                again to find the instantiated member function.
13351
13352                FIXME but doing that causes c++/15272, so we need to stop
13353                using IDENTIFIER_NODE in that situation.  */
13354             qualified_p = false;
13355           }
13356         else
13357           {
13358             if (TREE_CODE (function) == COMPONENT_REF)
13359               {
13360                 tree op = TREE_OPERAND (function, 1);
13361
13362                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13363                                || (BASELINK_P (op)
13364                                    && BASELINK_QUALIFIED_P (op)));
13365               }
13366             else
13367               qualified_p = false;
13368
13369             function = tsubst_copy_and_build (function, args, complain,
13370                                               in_decl,
13371                                               !qualified_p,
13372                                               integral_constant_expression_p);
13373
13374             if (BASELINK_P (function))
13375               qualified_p = true;
13376           }
13377
13378         nargs = call_expr_nargs (t);
13379         call_args = make_tree_vector ();
13380         for (i = 0; i < nargs; ++i)
13381           {
13382             tree arg = CALL_EXPR_ARG (t, i);
13383
13384             if (!PACK_EXPANSION_P (arg))
13385               VEC_safe_push (tree, gc, call_args,
13386                              RECUR (CALL_EXPR_ARG (t, i)));
13387             else
13388               {
13389                 /* Expand the pack expansion and push each entry onto
13390                    CALL_ARGS.  */
13391                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13392                 if (TREE_CODE (arg) == TREE_VEC)
13393                   {
13394                     unsigned int len, j;
13395
13396                     len = TREE_VEC_LENGTH (arg);
13397                     for (j = 0; j < len; ++j)
13398                       {
13399                         tree value = TREE_VEC_ELT (arg, j);
13400                         if (value != NULL_TREE)
13401                           value = convert_from_reference (value);
13402                         VEC_safe_push (tree, gc, call_args, value);
13403                       }
13404                   }
13405                 else
13406                   {
13407                     /* A partial substitution.  Add one entry.  */
13408                     VEC_safe_push (tree, gc, call_args, arg);
13409                   }
13410               }
13411           }
13412
13413         /* We do not perform argument-dependent lookup if normal
13414            lookup finds a non-function, in accordance with the
13415            expected resolution of DR 218.  */
13416         if (koenig_p
13417             && ((is_overloaded_fn (function)
13418                  /* If lookup found a member function, the Koenig lookup is
13419                     not appropriate, even if an unqualified-name was used
13420                     to denote the function.  */
13421                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13422                 || TREE_CODE (function) == IDENTIFIER_NODE)
13423             /* Only do this when substitution turns a dependent call
13424                into a non-dependent call.  */
13425             && type_dependent_expression_p_push (t)
13426             && !any_type_dependent_arguments_p (call_args))
13427           function = perform_koenig_lookup (function, call_args, false,
13428                                             tf_none);
13429
13430         if (TREE_CODE (function) == IDENTIFIER_NODE
13431             && !any_type_dependent_arguments_p (call_args))
13432           {
13433             if (koenig_p && (complain & tf_warning_or_error))
13434               {
13435                 /* For backwards compatibility and good diagnostics, try
13436                    the unqualified lookup again if we aren't in SFINAE
13437                    context.  */
13438                 tree unq = (tsubst_copy_and_build
13439                             (function, args, complain, in_decl, true,
13440                              integral_constant_expression_p));
13441                 if (unq != function)
13442                   {
13443                     tree fn = unq;
13444                     if (TREE_CODE (fn) == COMPONENT_REF)
13445                       fn = TREE_OPERAND (fn, 1);
13446                     if (is_overloaded_fn (fn))
13447                       fn = get_first_fn (fn);
13448                     permerror (EXPR_LOC_OR_HERE (t),
13449                                "%qD was not declared in this scope, "
13450                                "and no declarations were found by "
13451                                "argument-dependent lookup at the point "
13452                                "of instantiation", function);
13453                     if (DECL_CLASS_SCOPE_P (fn))
13454                       {
13455                         inform (EXPR_LOC_OR_HERE (t),
13456                                 "declarations in dependent base %qT are "
13457                                 "not found by unqualified lookup",
13458                                 DECL_CLASS_CONTEXT (fn));
13459                         if (current_class_ptr)
13460                           inform (EXPR_LOC_OR_HERE (t),
13461                                   "use %<this->%D%> instead", function);
13462                         else
13463                           inform (EXPR_LOC_OR_HERE (t),
13464                                   "use %<%T::%D%> instead",
13465                                   current_class_name, function);
13466                       }
13467                     else
13468                       inform (0, "%q+D declared here, later in the "
13469                                 "translation unit", fn);
13470                     function = unq;
13471                   }
13472               }
13473             if (TREE_CODE (function) == IDENTIFIER_NODE)
13474               {
13475                 unqualified_name_lookup_error (function);
13476                 release_tree_vector (call_args);
13477                 return error_mark_node;
13478               }
13479           }
13480
13481         /* Remember that there was a reference to this entity.  */
13482         if (DECL_P (function))
13483           mark_used (function);
13484
13485         if (TREE_CODE (function) == OFFSET_REF)
13486           ret = build_offset_ref_call_from_tree (function, &call_args);
13487         else if (TREE_CODE (function) == COMPONENT_REF)
13488           {
13489             tree instance = TREE_OPERAND (function, 0);
13490             tree fn = TREE_OPERAND (function, 1);
13491
13492             if (processing_template_decl
13493                 && (type_dependent_expression_p (instance)
13494                     || (!BASELINK_P (fn)
13495                         && TREE_CODE (fn) != FIELD_DECL)
13496                     || type_dependent_expression_p (fn)
13497                     || any_type_dependent_arguments_p (call_args)))
13498               ret = build_nt_call_vec (function, call_args);
13499             else if (!BASELINK_P (fn))
13500               ret = finish_call_expr (function, &call_args,
13501                                        /*disallow_virtual=*/false,
13502                                        /*koenig_p=*/false,
13503                                        complain);
13504             else
13505               ret = (build_new_method_call
13506                       (instance, fn,
13507                        &call_args, NULL_TREE,
13508                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13509                        /*fn_p=*/NULL,
13510                        complain));
13511           }
13512         else
13513           ret = finish_call_expr (function, &call_args,
13514                                   /*disallow_virtual=*/qualified_p,
13515                                   koenig_p,
13516                                   complain);
13517
13518         release_tree_vector (call_args);
13519
13520         return ret;
13521       }
13522
13523     case COND_EXPR:
13524       return build_x_conditional_expr
13525         (RECUR (TREE_OPERAND (t, 0)),
13526          RECUR (TREE_OPERAND (t, 1)),
13527          RECUR (TREE_OPERAND (t, 2)),
13528          complain);
13529
13530     case PSEUDO_DTOR_EXPR:
13531       return finish_pseudo_destructor_expr
13532         (RECUR (TREE_OPERAND (t, 0)),
13533          RECUR (TREE_OPERAND (t, 1)),
13534          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13535
13536     case TREE_LIST:
13537       {
13538         tree purpose, value, chain;
13539
13540         if (t == void_list_node)
13541           return t;
13542
13543         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13544             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13545           {
13546             /* We have pack expansions, so expand those and
13547                create a new list out of it.  */
13548             tree purposevec = NULL_TREE;
13549             tree valuevec = NULL_TREE;
13550             tree chain;
13551             int i, len = -1;
13552
13553             /* Expand the argument expressions.  */
13554             if (TREE_PURPOSE (t))
13555               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13556                                                  complain, in_decl);
13557             if (TREE_VALUE (t))
13558               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13559                                                complain, in_decl);
13560
13561             /* Build the rest of the list.  */
13562             chain = TREE_CHAIN (t);
13563             if (chain && chain != void_type_node)
13564               chain = RECUR (chain);
13565
13566             /* Determine the number of arguments.  */
13567             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13568               {
13569                 len = TREE_VEC_LENGTH (purposevec);
13570                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13571               }
13572             else if (TREE_CODE (valuevec) == TREE_VEC)
13573               len = TREE_VEC_LENGTH (valuevec);
13574             else
13575               {
13576                 /* Since we only performed a partial substitution into
13577                    the argument pack, we only return a single list
13578                    node.  */
13579                 if (purposevec == TREE_PURPOSE (t)
13580                     && valuevec == TREE_VALUE (t)
13581                     && chain == TREE_CHAIN (t))
13582                   return t;
13583
13584                 return tree_cons (purposevec, valuevec, chain);
13585               }
13586             
13587             /* Convert the argument vectors into a TREE_LIST */
13588             i = len;
13589             while (i > 0)
13590               {
13591                 /* Grab the Ith values.  */
13592                 i--;
13593                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13594                                      : NULL_TREE;
13595                 value 
13596                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13597                              : NULL_TREE;
13598
13599                 /* Build the list (backwards).  */
13600                 chain = tree_cons (purpose, value, chain);
13601               }
13602
13603             return chain;
13604           }
13605
13606         purpose = TREE_PURPOSE (t);
13607         if (purpose)
13608           purpose = RECUR (purpose);
13609         value = TREE_VALUE (t);
13610         if (value)
13611           value = RECUR (value);
13612         chain = TREE_CHAIN (t);
13613         if (chain && chain != void_type_node)
13614           chain = RECUR (chain);
13615         if (purpose == TREE_PURPOSE (t)
13616             && value == TREE_VALUE (t)
13617             && chain == TREE_CHAIN (t))
13618           return t;
13619         return tree_cons (purpose, value, chain);
13620       }
13621
13622     case COMPONENT_REF:
13623       {
13624         tree object;
13625         tree object_type;
13626         tree member;
13627
13628         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13629                                                      args, complain, in_decl);
13630         /* Remember that there was a reference to this entity.  */
13631         if (DECL_P (object))
13632           mark_used (object);
13633         object_type = TREE_TYPE (object);
13634
13635         member = TREE_OPERAND (t, 1);
13636         if (BASELINK_P (member))
13637           member = tsubst_baselink (member,
13638                                     non_reference (TREE_TYPE (object)),
13639                                     args, complain, in_decl);
13640         else
13641           member = tsubst_copy (member, args, complain, in_decl);
13642         if (member == error_mark_node)
13643           return error_mark_node;
13644
13645         if (object_type && !CLASS_TYPE_P (object_type))
13646           {
13647             if (SCALAR_TYPE_P (object_type))
13648               {
13649                 tree s = NULL_TREE;
13650                 tree dtor = member;
13651
13652                 if (TREE_CODE (dtor) == SCOPE_REF)
13653                   {
13654                     s = TREE_OPERAND (dtor, 0);
13655                     dtor = TREE_OPERAND (dtor, 1);
13656                   }
13657                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13658                   {
13659                     dtor = TREE_OPERAND (dtor, 0);
13660                     if (TYPE_P (dtor))
13661                       return finish_pseudo_destructor_expr (object, s, dtor);
13662                   }
13663               }
13664           }
13665         else if (TREE_CODE (member) == SCOPE_REF
13666                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13667           {
13668             tree tmpl;
13669             tree args;
13670
13671             /* Lookup the template functions now that we know what the
13672                scope is.  */
13673             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13674             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13675             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13676                                             /*is_type_p=*/false,
13677                                             /*complain=*/false);
13678             if (BASELINK_P (member))
13679               {
13680                 BASELINK_FUNCTIONS (member)
13681                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13682                               args);
13683                 member = (adjust_result_of_qualified_name_lookup
13684                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13685                            object_type));
13686               }
13687             else
13688               {
13689                 qualified_name_lookup_error (object_type, tmpl, member,
13690                                              input_location);
13691                 return error_mark_node;
13692               }
13693           }
13694         else if (TREE_CODE (member) == SCOPE_REF
13695                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13696                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13697           {
13698             if (complain & tf_error)
13699               {
13700                 if (TYPE_P (TREE_OPERAND (member, 0)))
13701                   error ("%qT is not a class or namespace",
13702                          TREE_OPERAND (member, 0));
13703                 else
13704                   error ("%qD is not a class or namespace",
13705                          TREE_OPERAND (member, 0));
13706               }
13707             return error_mark_node;
13708           }
13709         else if (TREE_CODE (member) == FIELD_DECL)
13710           return finish_non_static_data_member (member, object, NULL_TREE);
13711
13712         return finish_class_member_access_expr (object, member,
13713                                                 /*template_p=*/false,
13714                                                 complain);
13715       }
13716
13717     case THROW_EXPR:
13718       return build_throw
13719         (RECUR (TREE_OPERAND (t, 0)));
13720
13721     case CONSTRUCTOR:
13722       {
13723         VEC(constructor_elt,gc) *n;
13724         constructor_elt *ce;
13725         unsigned HOST_WIDE_INT idx;
13726         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13727         bool process_index_p;
13728         int newlen;
13729         bool need_copy_p = false;
13730         tree r;
13731
13732         if (type == error_mark_node)
13733           return error_mark_node;
13734
13735         /* digest_init will do the wrong thing if we let it.  */
13736         if (type && TYPE_PTRMEMFUNC_P (type))
13737           return t;
13738
13739         /* We do not want to process the index of aggregate
13740            initializers as they are identifier nodes which will be
13741            looked up by digest_init.  */
13742         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13743
13744         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13745         newlen = VEC_length (constructor_elt, n);
13746         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13747           {
13748             if (ce->index && process_index_p)
13749               ce->index = RECUR (ce->index);
13750
13751             if (PACK_EXPANSION_P (ce->value))
13752               {
13753                 /* Substitute into the pack expansion.  */
13754                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13755                                                   in_decl);
13756
13757                 if (ce->value == error_mark_node
13758                     || PACK_EXPANSION_P (ce->value))
13759                   ;
13760                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13761                   /* Just move the argument into place.  */
13762                   ce->value = TREE_VEC_ELT (ce->value, 0);
13763                 else
13764                   {
13765                     /* Update the length of the final CONSTRUCTOR
13766                        arguments vector, and note that we will need to
13767                        copy.*/
13768                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13769                     need_copy_p = true;
13770                   }
13771               }
13772             else
13773               ce->value = RECUR (ce->value);
13774           }
13775
13776         if (need_copy_p)
13777           {
13778             VEC(constructor_elt,gc) *old_n = n;
13779
13780             n = VEC_alloc (constructor_elt, gc, newlen);
13781             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13782               {
13783                 if (TREE_CODE (ce->value) == TREE_VEC)
13784                   {
13785                     int i, len = TREE_VEC_LENGTH (ce->value);
13786                     for (i = 0; i < len; ++i)
13787                       CONSTRUCTOR_APPEND_ELT (n, 0,
13788                                               TREE_VEC_ELT (ce->value, i));
13789                   }
13790                 else
13791                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13792               }
13793           }
13794
13795         r = build_constructor (init_list_type_node, n);
13796         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13797
13798         if (TREE_HAS_CONSTRUCTOR (t))
13799           return finish_compound_literal (type, r, complain);
13800
13801         TREE_TYPE (r) = type;
13802         return r;
13803       }
13804
13805     case TYPEID_EXPR:
13806       {
13807         tree operand_0 = TREE_OPERAND (t, 0);
13808         if (TYPE_P (operand_0))
13809           {
13810             operand_0 = tsubst (operand_0, args, complain, in_decl);
13811             return get_typeid (operand_0);
13812           }
13813         else
13814           {
13815             operand_0 = RECUR (operand_0);
13816             return build_typeid (operand_0);
13817           }
13818       }
13819
13820     case VAR_DECL:
13821       if (!args)
13822         return t;
13823       /* Fall through */
13824
13825     case PARM_DECL:
13826       {
13827         tree r = tsubst_copy (t, args, complain, in_decl);
13828
13829         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13830           /* If the original type was a reference, we'll be wrapped in
13831              the appropriate INDIRECT_REF.  */
13832           r = convert_from_reference (r);
13833         return r;
13834       }
13835
13836     case VA_ARG_EXPR:
13837       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13838                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13839
13840     case OFFSETOF_EXPR:
13841       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13842
13843     case TRAIT_EXPR:
13844       {
13845         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13846                                   complain, in_decl);
13847
13848         tree type2 = TRAIT_EXPR_TYPE2 (t);
13849         if (type2)
13850           type2 = tsubst_copy (type2, args, complain, in_decl);
13851         
13852         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13853       }
13854
13855     case STMT_EXPR:
13856       {
13857         tree old_stmt_expr = cur_stmt_expr;
13858         tree stmt_expr = begin_stmt_expr ();
13859
13860         cur_stmt_expr = stmt_expr;
13861         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13862                      integral_constant_expression_p);
13863         stmt_expr = finish_stmt_expr (stmt_expr, false);
13864         cur_stmt_expr = old_stmt_expr;
13865
13866         /* If the resulting list of expression statement is empty,
13867            fold it further into void_zero_node.  */
13868         if (empty_expr_stmt_p (stmt_expr))
13869           stmt_expr = void_zero_node;
13870
13871         return stmt_expr;
13872       }
13873
13874     case CONST_DECL:
13875       t = tsubst_copy (t, args, complain, in_decl);
13876       /* As in finish_id_expression, we resolve enumeration constants
13877          to their underlying values.  */
13878       if (TREE_CODE (t) == CONST_DECL)
13879         {
13880           used_types_insert (TREE_TYPE (t));
13881           return DECL_INITIAL (t);
13882         }
13883       return t;
13884
13885     case LAMBDA_EXPR:
13886       {
13887         tree r = build_lambda_expr ();
13888
13889         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13890         TREE_TYPE (r) = type;
13891         CLASSTYPE_LAMBDA_EXPR (type) = r;
13892
13893         LAMBDA_EXPR_LOCATION (r)
13894           = LAMBDA_EXPR_LOCATION (t);
13895         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13896           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13897         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13898         LAMBDA_EXPR_DISCRIMINATOR (r)
13899           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13900         LAMBDA_EXPR_EXTRA_SCOPE (r)
13901           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13902         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
13903           {
13904             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
13905             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
13906           }
13907         else
13908           LAMBDA_EXPR_RETURN_TYPE (r)
13909             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13910
13911         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
13912                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
13913
13914         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13915         determine_visibility (TYPE_NAME (type));
13916         /* Now that we know visibility, instantiate the type so we have a
13917            declaration of the op() for later calls to lambda_function.  */
13918         complete_type (type);
13919
13920         /* The capture list refers to closure members, so this needs to
13921            wait until after we finish instantiating the type.  */
13922         LAMBDA_EXPR_CAPTURE_LIST (r)
13923           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13924
13925         return build_lambda_object (r);
13926       }
13927
13928     case TARGET_EXPR:
13929       /* We can get here for a constant initializer of non-dependent type.
13930          FIXME stop folding in cp_parser_initializer_clause.  */
13931       gcc_assert (TREE_CONSTANT (t));
13932       {
13933         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13934         TREE_CONSTANT (r) = true;
13935         return r;
13936       }
13937
13938     default:
13939       /* Handle Objective-C++ constructs, if appropriate.  */
13940       {
13941         tree subst
13942           = objcp_tsubst_copy_and_build (t, args, complain,
13943                                          in_decl, /*function_p=*/false);
13944         if (subst)
13945           return subst;
13946       }
13947       return tsubst_copy (t, args, complain, in_decl);
13948     }
13949
13950 #undef RECUR
13951 }
13952
13953 /* Verify that the instantiated ARGS are valid. For type arguments,
13954    make sure that the type's linkage is ok. For non-type arguments,
13955    make sure they are constants if they are integral or enumerations.
13956    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13957
13958 static bool
13959 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13960 {
13961   if (ARGUMENT_PACK_P (t))
13962     {
13963       tree vec = ARGUMENT_PACK_ARGS (t);
13964       int len = TREE_VEC_LENGTH (vec);
13965       bool result = false;
13966       int i;
13967
13968       for (i = 0; i < len; ++i)
13969         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13970           result = true;
13971       return result;
13972     }
13973   else if (TYPE_P (t))
13974     {
13975       /* [basic.link]: A name with no linkage (notably, the name
13976          of a class or enumeration declared in a local scope)
13977          shall not be used to declare an entity with linkage.
13978          This implies that names with no linkage cannot be used as
13979          template arguments
13980
13981          DR 757 relaxes this restriction for C++0x.  */
13982       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13983                  : no_linkage_check (t, /*relaxed_p=*/false));
13984
13985       if (nt)
13986         {
13987           /* DR 488 makes use of a type with no linkage cause
13988              type deduction to fail.  */
13989           if (complain & tf_error)
13990             {
13991               if (TYPE_ANONYMOUS_P (nt))
13992                 error ("%qT is/uses anonymous type", t);
13993               else
13994                 error ("template argument for %qD uses local type %qT",
13995                        tmpl, t);
13996             }
13997           return true;
13998         }
13999       /* In order to avoid all sorts of complications, we do not
14000          allow variably-modified types as template arguments.  */
14001       else if (variably_modified_type_p (t, NULL_TREE))
14002         {
14003           if (complain & tf_error)
14004             error ("%qT is a variably modified type", t);
14005           return true;
14006         }
14007     }
14008   /* A non-type argument of integral or enumerated type must be a
14009      constant.  */
14010   else if (TREE_TYPE (t)
14011            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14012            && !TREE_CONSTANT (t))
14013     {
14014       if (complain & tf_error)
14015         error ("integral expression %qE is not constant", t);
14016       return true;
14017     }
14018   return false;
14019 }
14020
14021 static bool
14022 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14023 {
14024   int ix, len = DECL_NTPARMS (tmpl);
14025   bool result = false;
14026
14027   for (ix = 0; ix != len; ix++)
14028     {
14029       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14030         result = true;
14031     }
14032   if (result && (complain & tf_error))
14033     error ("  trying to instantiate %qD", tmpl);
14034   return result;
14035 }
14036
14037 /* In C++0x, it's possible to have a function template whose type depends
14038    on itself recursively.  This is most obvious with decltype, but can also
14039    occur with enumeration scope (c++/48969).  So we need to catch infinite
14040    recursion and reject the substitution at deduction time; this function
14041    will return error_mark_node for any repeated substitution.
14042
14043    This also catches excessive recursion such as when f<N> depends on
14044    f<N-1> across all integers, and returns error_mark_node for all the
14045    substitutions back up to the initial one.
14046
14047    This is, of course, not reentrant.  */
14048
14049 static tree
14050 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14051 {
14052   static bool excessive_deduction_depth;
14053   static int deduction_depth;
14054   struct pending_template *old_last_pend = last_pending_template;
14055   struct tinst_level *old_error_tinst = last_error_tinst_level;
14056
14057   tree fntype = TREE_TYPE (fn);
14058   tree tinst;
14059   tree r;
14060
14061   if (excessive_deduction_depth)
14062     return error_mark_node;
14063
14064   tinst = build_tree_list (fn, targs);
14065   if (!push_tinst_level (tinst))
14066     {
14067       excessive_deduction_depth = true;
14068       ggc_free (tinst);
14069       return error_mark_node;
14070     }
14071
14072   input_location = DECL_SOURCE_LOCATION (fn);
14073   ++deduction_depth;
14074   push_deduction_access_scope (fn);
14075   r = tsubst (fntype, targs, complain, NULL_TREE);
14076   pop_deduction_access_scope (fn);
14077   --deduction_depth;
14078
14079   if (excessive_deduction_depth)
14080     {
14081       r = error_mark_node;
14082       if (deduction_depth == 0)
14083         /* Reset once we're all the way out.  */
14084         excessive_deduction_depth = false;
14085     }
14086
14087   pop_tinst_level ();
14088   /* We can't free this if a pending_template entry or last_error_tinst_level
14089      is pointing at it.  */
14090   if (last_pending_template == old_last_pend
14091       && last_error_tinst_level == old_error_tinst)
14092     ggc_free (tinst);
14093   return r;
14094 }
14095
14096 /* Instantiate the indicated variable or function template TMPL with
14097    the template arguments in TARG_PTR.  */
14098
14099 static tree
14100 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14101 {
14102   tree targ_ptr = orig_args;
14103   tree fndecl;
14104   tree gen_tmpl;
14105   tree spec;
14106   HOST_WIDE_INT saved_processing_template_decl;
14107
14108   if (tmpl == error_mark_node)
14109     return error_mark_node;
14110
14111   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14112
14113   /* If this function is a clone, handle it specially.  */
14114   if (DECL_CLONED_FUNCTION_P (tmpl))
14115     {
14116       tree spec;
14117       tree clone;
14118
14119       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14120          DECL_CLONED_FUNCTION.  */
14121       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14122                                    targ_ptr, complain);
14123       if (spec == error_mark_node)
14124         return error_mark_node;
14125
14126       /* Look for the clone.  */
14127       FOR_EACH_CLONE (clone, spec)
14128         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14129           return clone;
14130       /* We should always have found the clone by now.  */
14131       gcc_unreachable ();
14132       return NULL_TREE;
14133     }
14134
14135   /* Check to see if we already have this specialization.  */
14136   gen_tmpl = most_general_template (tmpl);
14137   if (tmpl != gen_tmpl)
14138     /* The TMPL is a partial instantiation.  To get a full set of
14139        arguments we must add the arguments used to perform the
14140        partial instantiation.  */
14141     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14142                                             targ_ptr);
14143
14144   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14145      but it doesn't seem to be on the hot path.  */
14146   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14147
14148   gcc_assert (tmpl == gen_tmpl
14149               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14150                   == spec)
14151               || fndecl == NULL_TREE);
14152
14153   if (spec != NULL_TREE)
14154     return spec;
14155
14156   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14157                                complain))
14158     return error_mark_node;
14159
14160   /* We are building a FUNCTION_DECL, during which the access of its
14161      parameters and return types have to be checked.  However this
14162      FUNCTION_DECL which is the desired context for access checking
14163      is not built yet.  We solve this chicken-and-egg problem by
14164      deferring all checks until we have the FUNCTION_DECL.  */
14165   push_deferring_access_checks (dk_deferred);
14166
14167   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
14168      (because, for example, we have encountered a non-dependent
14169      function call in the body of a template function and must now
14170      determine which of several overloaded functions will be called),
14171      within the instantiation itself we are not processing a
14172      template.  */  
14173   saved_processing_template_decl = processing_template_decl;
14174   processing_template_decl = 0;
14175   /* Substitute template parameters to obtain the specialization.  */
14176   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14177                    targ_ptr, complain, gen_tmpl);
14178   processing_template_decl = saved_processing_template_decl;
14179   if (fndecl == error_mark_node)
14180     return error_mark_node;
14181
14182   /* Now we know the specialization, compute access previously
14183      deferred.  */
14184   push_access_scope (fndecl);
14185
14186   /* Some typedefs referenced from within the template code need to be access
14187      checked at template instantiation time, i.e now. These types were
14188      added to the template at parsing time. Let's get those and perfom
14189      the acces checks then.  */
14190   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14191   perform_deferred_access_checks ();
14192   pop_access_scope (fndecl);
14193   pop_deferring_access_checks ();
14194
14195   /* The DECL_TI_TEMPLATE should always be the immediate parent
14196      template, not the most general template.  */
14197   DECL_TI_TEMPLATE (fndecl) = tmpl;
14198
14199   /* If we've just instantiated the main entry point for a function,
14200      instantiate all the alternate entry points as well.  We do this
14201      by cloning the instantiation of the main entry point, not by
14202      instantiating the template clones.  */
14203   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14204     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14205
14206   return fndecl;
14207 }
14208
14209 /* Wrapper for instantiate_template_1.  */
14210
14211 tree
14212 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14213 {
14214   tree ret;
14215   timevar_push (TV_TEMPLATE_INST);
14216   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14217   timevar_pop (TV_TEMPLATE_INST);
14218   return ret;
14219 }
14220
14221 /* We're going to do deduction substitution on the type of TMPL, a function
14222    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14223    disable access checking.  */
14224
14225 static void
14226 push_deduction_access_scope (tree tmpl)
14227 {
14228   if (cxx_dialect >= cxx0x)
14229     {
14230       int ptd = processing_template_decl;
14231       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14232       /* Preserve processing_template_decl across push_to_top_level.  */
14233       if (ptd && !processing_template_decl)
14234         ++processing_template_decl;
14235     }
14236   else
14237     push_deferring_access_checks (dk_no_check);
14238 }
14239
14240 /* And pop back out.  */
14241
14242 static void
14243 pop_deduction_access_scope (tree tmpl)
14244 {
14245   if (cxx_dialect >= cxx0x)
14246     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14247   else
14248     pop_deferring_access_checks ();
14249 }
14250
14251 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14252    NARGS elements of the arguments that are being used when calling
14253    it.  TARGS is a vector into which the deduced template arguments
14254    are placed.
14255
14256    Return zero for success, 2 for an incomplete match that doesn't resolve
14257    all the types, and 1 for complete failure.  An error message will be
14258    printed only for an incomplete match.
14259
14260    If FN is a conversion operator, or we are trying to produce a specific
14261    specialization, RETURN_TYPE is the return type desired.
14262
14263    The EXPLICIT_TARGS are explicit template arguments provided via a
14264    template-id.
14265
14266    The parameter STRICT is one of:
14267
14268    DEDUCE_CALL:
14269      We are deducing arguments for a function call, as in
14270      [temp.deduct.call].
14271
14272    DEDUCE_CONV:
14273      We are deducing arguments for a conversion function, as in
14274      [temp.deduct.conv].
14275
14276    DEDUCE_EXACT:
14277      We are deducing arguments when doing an explicit instantiation
14278      as in [temp.explicit], when determining an explicit specialization
14279      as in [temp.expl.spec], or when taking the address of a function
14280      template, as in [temp.deduct.funcaddr].  */
14281
14282 int
14283 fn_type_unification (tree fn,
14284                      tree explicit_targs,
14285                      tree targs,
14286                      const tree *args,
14287                      unsigned int nargs,
14288                      tree return_type,
14289                      unification_kind_t strict,
14290                      int flags,
14291                      bool explain_p)
14292 {
14293   tree parms;
14294   tree fntype;
14295   int result;
14296   bool incomplete_argument_packs_p = false;
14297
14298   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14299
14300   fntype = TREE_TYPE (fn);
14301   if (explicit_targs)
14302     {
14303       /* [temp.deduct]
14304
14305          The specified template arguments must match the template
14306          parameters in kind (i.e., type, nontype, template), and there
14307          must not be more arguments than there are parameters;
14308          otherwise type deduction fails.
14309
14310          Nontype arguments must match the types of the corresponding
14311          nontype template parameters, or must be convertible to the
14312          types of the corresponding nontype parameters as specified in
14313          _temp.arg.nontype_, otherwise type deduction fails.
14314
14315          All references in the function type of the function template
14316          to the corresponding template parameters are replaced by the
14317          specified template argument values.  If a substitution in a
14318          template parameter or in the function type of the function
14319          template results in an invalid type, type deduction fails.  */
14320       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14321       int i, len = TREE_VEC_LENGTH (tparms);
14322       tree converted_args;
14323       bool incomplete = false;
14324
14325       if (explicit_targs == error_mark_node)
14326         return unify_invalid (explain_p);
14327
14328       converted_args
14329         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14330                                   (explain_p
14331                                    ? tf_warning_or_error
14332                                    : tf_none),
14333                                    /*require_all_args=*/false,
14334                                    /*use_default_args=*/false));
14335       if (converted_args == error_mark_node)
14336         return 1;
14337
14338       /* Substitute the explicit args into the function type.  This is
14339          necessary so that, for instance, explicitly declared function
14340          arguments can match null pointed constants.  If we were given
14341          an incomplete set of explicit args, we must not do semantic
14342          processing during substitution as we could create partial
14343          instantiations.  */
14344       for (i = 0; i < len; i++)
14345         {
14346           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14347           bool parameter_pack = false;
14348
14349           /* Dig out the actual parm.  */
14350           if (TREE_CODE (parm) == TYPE_DECL
14351               || TREE_CODE (parm) == TEMPLATE_DECL)
14352             {
14353               parm = TREE_TYPE (parm);
14354               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14355             }
14356           else if (TREE_CODE (parm) == PARM_DECL)
14357             {
14358               parm = DECL_INITIAL (parm);
14359               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14360             }
14361
14362           if (parameter_pack)
14363             {
14364               int level, idx;
14365               tree targ;
14366               template_parm_level_and_index (parm, &level, &idx);
14367
14368               /* Mark the argument pack as "incomplete". We could
14369                  still deduce more arguments during unification.
14370                  We remove this mark in type_unification_real.  */
14371               targ = TMPL_ARG (converted_args, level, idx);
14372               if (targ)
14373                 {
14374                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14375                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14376                     = ARGUMENT_PACK_ARGS (targ);
14377                 }
14378
14379               /* We have some incomplete argument packs.  */
14380               incomplete_argument_packs_p = true;
14381             }
14382         }
14383
14384       if (incomplete_argument_packs_p)
14385         /* Any substitution is guaranteed to be incomplete if there
14386            are incomplete argument packs, because we can still deduce
14387            more arguments.  */
14388         incomplete = 1;
14389       else
14390         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
14391
14392       processing_template_decl += incomplete;
14393       fntype = deduction_tsubst_fntype (fn, converted_args,
14394                                         (explain_p
14395                                          ? tf_warning_or_error
14396                                          : tf_none));
14397       processing_template_decl -= incomplete;
14398
14399       if (fntype == error_mark_node)
14400         return 1;
14401
14402       /* Place the explicitly specified arguments in TARGS.  */
14403       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14404         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14405     }
14406
14407   /* Never do unification on the 'this' parameter.  */
14408   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14409
14410   if (return_type)
14411     {
14412       tree *new_args;
14413
14414       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14415       new_args = XALLOCAVEC (tree, nargs + 1);
14416       new_args[0] = return_type;
14417       memcpy (new_args + 1, args, nargs * sizeof (tree));
14418       args = new_args;
14419       ++nargs;
14420     }
14421
14422   /* We allow incomplete unification without an error message here
14423      because the standard doesn't seem to explicitly prohibit it.  Our
14424      callers must be ready to deal with unification failures in any
14425      event.  */
14426   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14427                                   targs, parms, args, nargs, /*subr=*/0,
14428                                   strict, flags, explain_p);
14429
14430   /* Now that we have bindings for all of the template arguments,
14431      ensure that the arguments deduced for the template template
14432      parameters have compatible template parameter lists.  We cannot
14433      check this property before we have deduced all template
14434      arguments, because the template parameter types of a template
14435      template parameter might depend on prior template parameters
14436      deduced after the template template parameter.  The following
14437      ill-formed example illustrates this issue:
14438
14439        template<typename T, template<T> class C> void f(C<5>, T);
14440
14441        template<int N> struct X {};
14442
14443        void g() {
14444          f(X<5>(), 5l); // error: template argument deduction fails
14445        }
14446
14447      The template parameter list of 'C' depends on the template type
14448      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14449      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14450      time that we deduce 'C'.  */
14451   if (result == 0
14452       && !template_template_parm_bindings_ok_p 
14453            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14454     return unify_inconsistent_template_template_parameters (explain_p);
14455
14456   if (result == 0)
14457     /* All is well so far.  Now, check:
14458
14459        [temp.deduct]
14460
14461        When all template arguments have been deduced, all uses of
14462        template parameters in nondeduced contexts are replaced with
14463        the corresponding deduced argument values.  If the
14464        substitution results in an invalid type, as described above,
14465        type deduction fails.  */
14466     {
14467       tree substed = deduction_tsubst_fntype (fn, targs,
14468                                               (explain_p
14469                                                ? tf_warning_or_error
14470                                                : tf_none));
14471       if (substed == error_mark_node)
14472         return 1;
14473
14474       /* If we're looking for an exact match, check that what we got
14475          is indeed an exact match.  It might not be if some template
14476          parameters are used in non-deduced contexts.  */
14477       if (strict == DEDUCE_EXACT)
14478         {
14479           unsigned int i;
14480
14481           tree sarg
14482             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14483           if (return_type)
14484             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14485           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14486             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14487               return unify_type_mismatch (explain_p, args[i],
14488                                           TREE_VALUE (sarg));
14489         }
14490     }
14491
14492   return result;
14493 }
14494
14495 /* Adjust types before performing type deduction, as described in
14496    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14497    sections are symmetric.  PARM is the type of a function parameter
14498    or the return type of the conversion function.  ARG is the type of
14499    the argument passed to the call, or the type of the value
14500    initialized with the result of the conversion function.
14501    ARG_EXPR is the original argument expression, which may be null.  */
14502
14503 static int
14504 maybe_adjust_types_for_deduction (unification_kind_t strict,
14505                                   tree* parm,
14506                                   tree* arg,
14507                                   tree arg_expr)
14508 {
14509   int result = 0;
14510
14511   switch (strict)
14512     {
14513     case DEDUCE_CALL:
14514       break;
14515
14516     case DEDUCE_CONV:
14517       {
14518         /* Swap PARM and ARG throughout the remainder of this
14519            function; the handling is precisely symmetric since PARM
14520            will initialize ARG rather than vice versa.  */
14521         tree* temp = parm;
14522         parm = arg;
14523         arg = temp;
14524         break;
14525       }
14526
14527     case DEDUCE_EXACT:
14528       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14529          too, but here handle it by stripping the reference from PARM
14530          rather than by adding it to ARG.  */
14531       if (TREE_CODE (*parm) == REFERENCE_TYPE
14532           && TYPE_REF_IS_RVALUE (*parm)
14533           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14534           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14535           && TREE_CODE (*arg) == REFERENCE_TYPE
14536           && !TYPE_REF_IS_RVALUE (*arg))
14537         *parm = TREE_TYPE (*parm);
14538       /* Nothing else to do in this case.  */
14539       return 0;
14540
14541     default:
14542       gcc_unreachable ();
14543     }
14544
14545   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14546     {
14547       /* [temp.deduct.call]
14548
14549          If P is not a reference type:
14550
14551          --If A is an array type, the pointer type produced by the
14552          array-to-pointer standard conversion (_conv.array_) is
14553          used in place of A for type deduction; otherwise,
14554
14555          --If A is a function type, the pointer type produced by
14556          the function-to-pointer standard conversion
14557          (_conv.func_) is used in place of A for type deduction;
14558          otherwise,
14559
14560          --If A is a cv-qualified type, the top level
14561          cv-qualifiers of A's type are ignored for type
14562          deduction.  */
14563       if (TREE_CODE (*arg) == ARRAY_TYPE)
14564         *arg = build_pointer_type (TREE_TYPE (*arg));
14565       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14566         *arg = build_pointer_type (*arg);
14567       else
14568         *arg = TYPE_MAIN_VARIANT (*arg);
14569     }
14570
14571   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14572      of the form T&&, where T is a template parameter, and the argument
14573      is an lvalue, T is deduced as A& */
14574   if (TREE_CODE (*parm) == REFERENCE_TYPE
14575       && TYPE_REF_IS_RVALUE (*parm)
14576       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14577       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14578       && (arg_expr ? real_lvalue_p (arg_expr)
14579           /* try_one_overload doesn't provide an arg_expr, but
14580              functions are always lvalues.  */
14581           : TREE_CODE (*arg) == FUNCTION_TYPE))
14582     *arg = build_reference_type (*arg);
14583
14584   /* [temp.deduct.call]
14585
14586      If P is a cv-qualified type, the top level cv-qualifiers
14587      of P's type are ignored for type deduction.  If P is a
14588      reference type, the type referred to by P is used for
14589      type deduction.  */
14590   *parm = TYPE_MAIN_VARIANT (*parm);
14591   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14592     {
14593       *parm = TREE_TYPE (*parm);
14594       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14595     }
14596
14597   /* DR 322. For conversion deduction, remove a reference type on parm
14598      too (which has been swapped into ARG).  */
14599   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14600     *arg = TREE_TYPE (*arg);
14601
14602   return result;
14603 }
14604
14605 /* Most parms like fn_type_unification.
14606
14607    If SUBR is 1, we're being called recursively (to unify the
14608    arguments of a function or method parameter of a function
14609    template). */
14610
14611 static int
14612 type_unification_real (tree tparms,
14613                        tree targs,
14614                        tree xparms,
14615                        const tree *xargs,
14616                        unsigned int xnargs,
14617                        int subr,
14618                        unification_kind_t strict,
14619                        int flags,
14620                        bool explain_p)
14621 {
14622   tree parm, arg, arg_expr;
14623   int i;
14624   int ntparms = TREE_VEC_LENGTH (tparms);
14625   int sub_strict;
14626   int saw_undeduced = 0;
14627   tree parms;
14628   const tree *args;
14629   unsigned int nargs;
14630   unsigned int ia;
14631
14632   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14633   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14634   gcc_assert (ntparms > 0);
14635
14636   /* Reset the number of non-defaulted template arguments contained
14637      in TARGS.  */
14638   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14639
14640   switch (strict)
14641     {
14642     case DEDUCE_CALL:
14643       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
14644                     | UNIFY_ALLOW_DERIVED);
14645       break;
14646
14647     case DEDUCE_CONV:
14648       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14649       break;
14650
14651     case DEDUCE_EXACT:
14652       sub_strict = UNIFY_ALLOW_NONE;
14653       break;
14654
14655     default:
14656       gcc_unreachable ();
14657     }
14658
14659  again:
14660   parms = xparms;
14661   args = xargs;
14662   nargs = xnargs;
14663
14664   ia = 0;
14665   while (parms && parms != void_list_node
14666          && ia < nargs)
14667     {
14668       parm = TREE_VALUE (parms);
14669
14670       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14671           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14672         /* For a function parameter pack that occurs at the end of the
14673            parameter-declaration-list, the type A of each remaining
14674            argument of the call is compared with the type P of the
14675            declarator-id of the function parameter pack.  */
14676         break;
14677
14678       parms = TREE_CHAIN (parms);
14679
14680       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
14681         /* For a function parameter pack that does not occur at the
14682            end of the parameter-declaration-list, the type of the
14683            parameter pack is a non-deduced context.  */
14684         continue;
14685
14686       arg = args[ia];
14687       ++ia;
14688       arg_expr = NULL;
14689
14690       if (arg == error_mark_node)
14691         return unify_invalid (explain_p);
14692       if (arg == unknown_type_node)
14693         /* We can't deduce anything from this, but we might get all the
14694            template args from other function args.  */
14695         continue;
14696
14697       /* Conversions will be performed on a function argument that
14698          corresponds with a function parameter that contains only
14699          non-deducible template parameters and explicitly specified
14700          template parameters.  */
14701       if (!uses_template_parms (parm))
14702         {
14703           tree type;
14704
14705           if (!TYPE_P (arg))
14706             type = TREE_TYPE (arg);
14707           else
14708             type = arg;
14709
14710           if (same_type_p (parm, type))
14711             continue;
14712           if (strict != DEDUCE_EXACT
14713               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14714                                   flags))
14715             continue;
14716
14717           if (strict == DEDUCE_EXACT)
14718             return unify_type_mismatch (explain_p, parm, arg);
14719           else
14720             return unify_arg_conversion (explain_p, parm, type, arg);
14721         }
14722
14723       if (!TYPE_P (arg))
14724         {
14725           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14726           if (type_unknown_p (arg))
14727             {
14728               /* [temp.deduct.type] 
14729
14730                  A template-argument can be deduced from a pointer to
14731                  function or pointer to member function argument if
14732                  the set of overloaded functions does not contain
14733                  function templates and at most one of a set of
14734                  overloaded functions provides a unique match.  */
14735               if (resolve_overloaded_unification
14736                   (tparms, targs, parm, arg, strict, sub_strict, explain_p))
14737                 continue;
14738
14739               return unify_overload_resolution_failure (explain_p, arg);
14740             }
14741           arg_expr = arg;
14742           arg = unlowered_expr_type (arg);
14743           if (arg == error_mark_node)
14744             return unify_invalid (explain_p);
14745         }
14746
14747       {
14748         int arg_strict = sub_strict;
14749
14750         if (!subr)
14751           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14752                                                           arg_expr);
14753
14754         if (arg == init_list_type_node && arg_expr)
14755           arg = arg_expr;
14756         if (unify (tparms, targs, parm, arg, arg_strict, explain_p))
14757           /* If unification failed, the recursive call will have updated
14758              UI appropriately.  */
14759           return 1;
14760       }
14761     }
14762
14763
14764   if (parms 
14765       && parms != void_list_node
14766       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14767     {
14768       /* Unify the remaining arguments with the pack expansion type.  */
14769       tree argvec;
14770       tree parmvec = make_tree_vec (1);
14771
14772       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14773       argvec = make_tree_vec (nargs - ia);
14774       for (i = 0; ia < nargs; ++ia, ++i)
14775         TREE_VEC_ELT (argvec, i) = args[ia];
14776
14777       /* Copy the parameter into parmvec.  */
14778       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14779       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14780                                 /*call_args_p=*/true, /*subr=*/subr, explain_p))
14781         return 1;
14782
14783       /* Advance to the end of the list of parameters.  */
14784       parms = TREE_CHAIN (parms);
14785     }
14786
14787   /* Fail if we've reached the end of the parm list, and more args
14788      are present, and the parm list isn't variadic.  */
14789   if (ia < nargs && parms == void_list_node)
14790     return unify_too_many_arguments (explain_p, nargs, ia);
14791   /* Fail if parms are left and they don't have default values.  */
14792   if (parms && parms != void_list_node
14793       && TREE_PURPOSE (parms) == NULL_TREE)
14794     {
14795       unsigned int count = nargs;
14796       tree p = parms;
14797       while (p && p != void_list_node)
14798         {
14799           count++;
14800           p = TREE_CHAIN (p);
14801         }
14802       return unify_too_few_arguments (explain_p, ia, count);
14803     }
14804
14805   if (!subr)
14806     {
14807       /* Check to see if we need another pass before we start clearing
14808          ARGUMENT_PACK_INCOMPLETE_P.  */
14809       for (i = 0; i < ntparms; i++)
14810         {
14811           tree targ = TREE_VEC_ELT (targs, i);
14812           tree tparm = TREE_VEC_ELT (tparms, i);
14813
14814           if (targ || tparm == error_mark_node)
14815             continue;
14816           tparm = TREE_VALUE (tparm);
14817
14818           /* If this is an undeduced nontype parameter that depends on
14819              a type parameter, try another pass; its type may have been
14820              deduced from a later argument than the one from which
14821              this parameter can be deduced.  */
14822           if (TREE_CODE (tparm) == PARM_DECL
14823               && uses_template_parms (TREE_TYPE (tparm))
14824               && !saw_undeduced++)
14825             goto again;
14826         }
14827
14828       for (i = 0; i < ntparms; i++)
14829         {
14830           tree targ = TREE_VEC_ELT (targs, i);
14831           tree tparm = TREE_VEC_ELT (tparms, i);
14832
14833           /* Clear the "incomplete" flags on all argument packs now so that
14834              substituting them into later default arguments works.  */
14835           if (targ && ARGUMENT_PACK_P (targ))
14836             {
14837               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
14838               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
14839             }
14840
14841           if (targ || tparm == error_mark_node)
14842             continue;
14843           tparm = TREE_VALUE (tparm);
14844
14845           /* Core issue #226 (C++0x) [temp.deduct]:
14846
14847              If a template argument has not been deduced, its
14848              default template argument, if any, is used. 
14849
14850              When we are in C++98 mode, TREE_PURPOSE will either
14851              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14852              to explicitly check cxx_dialect here.  */
14853           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14854             {
14855               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14856               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14857               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14858               arg = convert_template_argument (parm, arg, targs,
14859                                                (explain_p
14860                                                 ? tf_warning_or_error
14861                                                 : tf_none),
14862                                                i, NULL_TREE);
14863               if (arg == error_mark_node)
14864                 return 1;
14865               else
14866                 {
14867                   TREE_VEC_ELT (targs, i) = arg;
14868                   /* The position of the first default template argument,
14869                      is also the number of non-defaulted arguments in TARGS.
14870                      Record that.  */
14871                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14872                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14873                   continue;
14874                 }
14875             }
14876
14877           /* If the type parameter is a parameter pack, then it will
14878              be deduced to an empty parameter pack.  */
14879           if (template_parameter_pack_p (tparm))
14880             {
14881               tree arg;
14882
14883               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14884                 {
14885                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14886                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14887                   TREE_CONSTANT (arg) = 1;
14888                 }
14889               else
14890                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14891
14892               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14893
14894               TREE_VEC_ELT (targs, i) = arg;
14895               continue;
14896             }
14897
14898           return unify_parameter_deduction_failure (explain_p, tparm);
14899         }
14900     }
14901 #ifdef ENABLE_CHECKING
14902   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14903     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14904 #endif
14905
14906   return unify_success (explain_p);
14907 }
14908
14909 /* Subroutine of type_unification_real.  Args are like the variables
14910    at the call site.  ARG is an overloaded function (or template-id);
14911    we try deducing template args from each of the overloads, and if
14912    only one succeeds, we go with that.  Modifies TARGS and returns
14913    true on success.  */
14914
14915 static bool
14916 resolve_overloaded_unification (tree tparms,
14917                                 tree targs,
14918                                 tree parm,
14919                                 tree arg,
14920                                 unification_kind_t strict,
14921                                 int sub_strict,
14922                                 bool explain_p)
14923 {
14924   tree tempargs = copy_node (targs);
14925   int good = 0;
14926   tree goodfn = NULL_TREE;
14927   bool addr_p;
14928
14929   if (TREE_CODE (arg) == ADDR_EXPR)
14930     {
14931       arg = TREE_OPERAND (arg, 0);
14932       addr_p = true;
14933     }
14934   else
14935     addr_p = false;
14936
14937   if (TREE_CODE (arg) == COMPONENT_REF)
14938     /* Handle `&x' where `x' is some static or non-static member
14939        function name.  */
14940     arg = TREE_OPERAND (arg, 1);
14941
14942   if (TREE_CODE (arg) == OFFSET_REF)
14943     arg = TREE_OPERAND (arg, 1);
14944
14945   /* Strip baselink information.  */
14946   if (BASELINK_P (arg))
14947     arg = BASELINK_FUNCTIONS (arg);
14948
14949   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14950     {
14951       /* If we got some explicit template args, we need to plug them into
14952          the affected templates before we try to unify, in case the
14953          explicit args will completely resolve the templates in question.  */
14954
14955       int ok = 0;
14956       tree expl_subargs = TREE_OPERAND (arg, 1);
14957       arg = TREE_OPERAND (arg, 0);
14958
14959       for (; arg; arg = OVL_NEXT (arg))
14960         {
14961           tree fn = OVL_CURRENT (arg);
14962           tree subargs, elem;
14963
14964           if (TREE_CODE (fn) != TEMPLATE_DECL)
14965             continue;
14966
14967           ++processing_template_decl;
14968           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14969                                   expl_subargs, /*check_ret=*/false);
14970           if (subargs && !any_dependent_template_arguments_p (subargs))
14971             {
14972               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14973               if (try_one_overload (tparms, targs, tempargs, parm,
14974                                     elem, strict, sub_strict, addr_p, explain_p)
14975                   && (!goodfn || !decls_match (goodfn, elem)))
14976                 {
14977                   goodfn = elem;
14978                   ++good;
14979                 }
14980             }
14981           else if (subargs)
14982             ++ok;
14983           --processing_template_decl;
14984         }
14985       /* If no templates (or more than one) are fully resolved by the
14986          explicit arguments, this template-id is a non-deduced context; it
14987          could still be OK if we deduce all template arguments for the
14988          enclosing call through other arguments.  */
14989       if (good != 1)
14990         good = ok;
14991     }
14992   else if (TREE_CODE (arg) != OVERLOAD
14993            && TREE_CODE (arg) != FUNCTION_DECL)
14994     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14995        -- but the deduction does not succeed because the expression is
14996        not just the function on its own.  */
14997     return false;
14998   else
14999     for (; arg; arg = OVL_NEXT (arg))
15000       if (try_one_overload (tparms, targs, tempargs, parm,
15001                             TREE_TYPE (OVL_CURRENT (arg)),
15002                             strict, sub_strict, addr_p, explain_p)
15003           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15004         {
15005           goodfn = OVL_CURRENT (arg);
15006           ++good;
15007         }
15008
15009   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15010      to function or pointer to member function argument if the set of
15011      overloaded functions does not contain function templates and at most
15012      one of a set of overloaded functions provides a unique match.
15013
15014      So if we found multiple possibilities, we return success but don't
15015      deduce anything.  */
15016
15017   if (good == 1)
15018     {
15019       int i = TREE_VEC_LENGTH (targs);
15020       for (; i--; )
15021         if (TREE_VEC_ELT (tempargs, i))
15022           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15023     }
15024   if (good)
15025     return true;
15026
15027   return false;
15028 }
15029
15030 /* Core DR 115: In contexts where deduction is done and fails, or in
15031    contexts where deduction is not done, if a template argument list is
15032    specified and it, along with any default template arguments, identifies
15033    a single function template specialization, then the template-id is an
15034    lvalue for the function template specialization.  */
15035
15036 tree
15037 resolve_nondeduced_context (tree orig_expr)
15038 {
15039   tree expr, offset, baselink;
15040   bool addr;
15041
15042   if (!type_unknown_p (orig_expr))
15043     return orig_expr;
15044
15045   expr = orig_expr;
15046   addr = false;
15047   offset = NULL_TREE;
15048   baselink = NULL_TREE;
15049
15050   if (TREE_CODE (expr) == ADDR_EXPR)
15051     {
15052       expr = TREE_OPERAND (expr, 0);
15053       addr = true;
15054     }
15055   if (TREE_CODE (expr) == OFFSET_REF)
15056     {
15057       offset = expr;
15058       expr = TREE_OPERAND (expr, 1);
15059     }
15060   if (TREE_CODE (expr) == BASELINK)
15061     {
15062       baselink = expr;
15063       expr = BASELINK_FUNCTIONS (expr);
15064     }
15065
15066   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15067     {
15068       int good = 0;
15069       tree goodfn = NULL_TREE;
15070
15071       /* If we got some explicit template args, we need to plug them into
15072          the affected templates before we try to unify, in case the
15073          explicit args will completely resolve the templates in question.  */
15074
15075       tree expl_subargs = TREE_OPERAND (expr, 1);
15076       tree arg = TREE_OPERAND (expr, 0);
15077       tree badfn = NULL_TREE;
15078       tree badargs = NULL_TREE;
15079
15080       for (; arg; arg = OVL_NEXT (arg))
15081         {
15082           tree fn = OVL_CURRENT (arg);
15083           tree subargs, elem;
15084
15085           if (TREE_CODE (fn) != TEMPLATE_DECL)
15086             continue;
15087
15088           ++processing_template_decl;
15089           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15090                                   expl_subargs, /*check_ret=*/false);
15091           if (subargs && !any_dependent_template_arguments_p (subargs))
15092             {
15093               elem = instantiate_template (fn, subargs, tf_none);
15094               if (elem == error_mark_node)
15095                 {
15096                   badfn = fn;
15097                   badargs = subargs;
15098                 }
15099               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15100                 {
15101                   goodfn = elem;
15102                   ++good;
15103                 }
15104             }
15105           --processing_template_decl;
15106         }
15107       if (good == 1)
15108         {
15109           mark_used (goodfn);
15110           expr = goodfn;
15111           if (baselink)
15112             expr = build_baselink (BASELINK_BINFO (baselink),
15113                                    BASELINK_ACCESS_BINFO (baselink),
15114                                    expr, BASELINK_OPTYPE (baselink));
15115           if (offset)
15116             {
15117               tree base
15118                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15119               expr = build_offset_ref (base, expr, addr);
15120             }
15121           if (addr)
15122             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15123           return expr;
15124         }
15125       else if (good == 0 && badargs)
15126         /* There were no good options and at least one bad one, so let the
15127            user know what the problem is.  */
15128         instantiate_template (badfn, badargs, tf_warning_or_error);
15129     }
15130   return orig_expr;
15131 }
15132
15133 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15134    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15135    different overloads deduce different arguments for a given parm.
15136    ADDR_P is true if the expression for which deduction is being
15137    performed was of the form "& fn" rather than simply "fn".
15138
15139    Returns 1 on success.  */
15140
15141 static int
15142 try_one_overload (tree tparms,
15143                   tree orig_targs,
15144                   tree targs,
15145                   tree parm,
15146                   tree arg,
15147                   unification_kind_t strict,
15148                   int sub_strict,
15149                   bool addr_p,
15150                   bool explain_p)
15151 {
15152   int nargs;
15153   tree tempargs;
15154   int i;
15155
15156   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15157      to function or pointer to member function argument if the set of
15158      overloaded functions does not contain function templates and at most
15159      one of a set of overloaded functions provides a unique match.
15160
15161      So if this is a template, just return success.  */
15162
15163   if (uses_template_parms (arg))
15164     return 1;
15165
15166   if (TREE_CODE (arg) == METHOD_TYPE)
15167     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15168   else if (addr_p)
15169     arg = build_pointer_type (arg);
15170
15171   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15172
15173   /* We don't copy orig_targs for this because if we have already deduced
15174      some template args from previous args, unify would complain when we
15175      try to deduce a template parameter for the same argument, even though
15176      there isn't really a conflict.  */
15177   nargs = TREE_VEC_LENGTH (targs);
15178   tempargs = make_tree_vec (nargs);
15179
15180   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15181     return 0;
15182
15183   /* First make sure we didn't deduce anything that conflicts with
15184      explicitly specified args.  */
15185   for (i = nargs; i--; )
15186     {
15187       tree elt = TREE_VEC_ELT (tempargs, i);
15188       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15189
15190       if (!elt)
15191         /*NOP*/;
15192       else if (uses_template_parms (elt))
15193         /* Since we're unifying against ourselves, we will fill in
15194            template args used in the function parm list with our own
15195            template parms.  Discard them.  */
15196         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15197       else if (oldelt && !template_args_equal (oldelt, elt))
15198         return 0;
15199     }
15200
15201   for (i = nargs; i--; )
15202     {
15203       tree elt = TREE_VEC_ELT (tempargs, i);
15204
15205       if (elt)
15206         TREE_VEC_ELT (targs, i) = elt;
15207     }
15208
15209   return 1;
15210 }
15211
15212 /* PARM is a template class (perhaps with unbound template
15213    parameters).  ARG is a fully instantiated type.  If ARG can be
15214    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15215    TARGS are as for unify.  */
15216
15217 static tree
15218 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15219                        bool explain_p)
15220 {
15221   tree copy_of_targs;
15222
15223   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15224       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15225           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15226     return NULL_TREE;
15227
15228   /* We need to make a new template argument vector for the call to
15229      unify.  If we used TARGS, we'd clutter it up with the result of
15230      the attempted unification, even if this class didn't work out.
15231      We also don't want to commit ourselves to all the unifications
15232      we've already done, since unification is supposed to be done on
15233      an argument-by-argument basis.  In other words, consider the
15234      following pathological case:
15235
15236        template <int I, int J, int K>
15237        struct S {};
15238
15239        template <int I, int J>
15240        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15241
15242        template <int I, int J, int K>
15243        void f(S<I, J, K>, S<I, I, I>);
15244
15245        void g() {
15246          S<0, 0, 0> s0;
15247          S<0, 1, 2> s2;
15248
15249          f(s0, s2);
15250        }
15251
15252      Now, by the time we consider the unification involving `s2', we
15253      already know that we must have `f<0, 0, 0>'.  But, even though
15254      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15255      because there are two ways to unify base classes of S<0, 1, 2>
15256      with S<I, I, I>.  If we kept the already deduced knowledge, we
15257      would reject the possibility I=1.  */
15258   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15259
15260   /* If unification failed, we're done.  */
15261   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15262              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15263     return NULL_TREE;
15264
15265   return arg;
15266 }
15267
15268 /* Given a template type PARM and a class type ARG, find the unique
15269    base type in ARG that is an instance of PARM.  We do not examine
15270    ARG itself; only its base-classes.  If there is not exactly one
15271    appropriate base class, return NULL_TREE.  PARM may be the type of
15272    a partial specialization, as well as a plain template type.  Used
15273    by unify.  */
15274
15275 static enum template_base_result
15276 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15277                    bool explain_p, tree *result)
15278 {
15279   tree rval = NULL_TREE;
15280   tree binfo;
15281
15282   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15283
15284   binfo = TYPE_BINFO (complete_type (arg));
15285   if (!binfo)
15286     {
15287       /* The type could not be completed.  */
15288       *result = NULL_TREE;
15289       return tbr_incomplete_type;
15290     }
15291
15292   /* Walk in inheritance graph order.  The search order is not
15293      important, and this avoids multiple walks of virtual bases.  */
15294   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15295     {
15296       tree r = try_class_unification (tparms, targs, parm,
15297                                       BINFO_TYPE (binfo), explain_p);
15298
15299       if (r)
15300         {
15301           /* If there is more than one satisfactory baseclass, then:
15302
15303                [temp.deduct.call]
15304
15305               If they yield more than one possible deduced A, the type
15306               deduction fails.
15307
15308              applies.  */
15309           if (rval && !same_type_p (r, rval))
15310             {
15311               *result = NULL_TREE;
15312               return tbr_ambiguous_baseclass;
15313             }
15314
15315           rval = r;
15316         }
15317     }
15318
15319   *result = rval;
15320   return tbr_success;
15321 }
15322
15323 /* Returns the level of DECL, which declares a template parameter.  */
15324
15325 static int
15326 template_decl_level (tree decl)
15327 {
15328   switch (TREE_CODE (decl))
15329     {
15330     case TYPE_DECL:
15331     case TEMPLATE_DECL:
15332       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15333
15334     case PARM_DECL:
15335       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15336
15337     default:
15338       gcc_unreachable ();
15339     }
15340   return 0;
15341 }
15342
15343 /* Decide whether ARG can be unified with PARM, considering only the
15344    cv-qualifiers of each type, given STRICT as documented for unify.
15345    Returns nonzero iff the unification is OK on that basis.  */
15346
15347 static int
15348 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15349 {
15350   int arg_quals = cp_type_quals (arg);
15351   int parm_quals = cp_type_quals (parm);
15352
15353   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15354       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15355     {
15356       /*  Although a CVR qualifier is ignored when being applied to a
15357           substituted template parameter ([8.3.2]/1 for example), that
15358           does not allow us to unify "const T" with "int&" because both
15359           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15360           It is ok when we're allowing additional CV qualifiers
15361           at the outer level [14.8.2.1]/3,1st bullet.  */
15362       if ((TREE_CODE (arg) == REFERENCE_TYPE
15363            || TREE_CODE (arg) == FUNCTION_TYPE
15364            || TREE_CODE (arg) == METHOD_TYPE)
15365           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15366         return 0;
15367
15368       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15369           && (parm_quals & TYPE_QUAL_RESTRICT))
15370         return 0;
15371     }
15372
15373   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15374       && (arg_quals & parm_quals) != parm_quals)
15375     return 0;
15376
15377   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15378       && (parm_quals & arg_quals) != arg_quals)
15379     return 0;
15380
15381   return 1;
15382 }
15383
15384 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15385 void 
15386 template_parm_level_and_index (tree parm, int* level, int* index)
15387 {
15388   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15389       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15390       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15391     {
15392       *index = TEMPLATE_TYPE_IDX (parm);
15393       *level = TEMPLATE_TYPE_LEVEL (parm);
15394     }
15395   else
15396     {
15397       *index = TEMPLATE_PARM_IDX (parm);
15398       *level = TEMPLATE_PARM_LEVEL (parm);
15399     }
15400 }
15401
15402 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15403   do {                                                                  \
15404     if (unify (TP, TA, P, A, S, EP))                                    \
15405       return 1;                                                         \
15406   } while (0);
15407
15408 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15409    expansion at the end of PACKED_PARMS. Returns 0 if the type
15410    deduction succeeds, 1 otherwise. STRICT is the same as in
15411    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15412    call argument list. We'll need to adjust the arguments to make them
15413    types. SUBR tells us if this is from a recursive call to
15414    type_unification_real.  */
15415 static int
15416 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15417                       tree packed_args, int strict, bool call_args_p,
15418                       bool subr, bool explain_p)
15419 {
15420   tree parm 
15421     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15422   tree pattern = PACK_EXPANSION_PATTERN (parm);
15423   tree pack, packs = NULL_TREE;
15424   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15425   int len = TREE_VEC_LENGTH (packed_args);
15426
15427   /* Determine the parameter packs we will be deducing from the
15428      pattern, and record their current deductions.  */
15429   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15430        pack; pack = TREE_CHAIN (pack))
15431     {
15432       tree parm_pack = TREE_VALUE (pack);
15433       int idx, level;
15434
15435       /* Determine the index and level of this parameter pack.  */
15436       template_parm_level_and_index (parm_pack, &level, &idx);
15437
15438       /* Keep track of the parameter packs and their corresponding
15439          argument packs.  */
15440       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15441       TREE_TYPE (packs) = make_tree_vec (len - start);
15442     }
15443   
15444   /* Loop through all of the arguments that have not yet been
15445      unified and unify each with the pattern.  */
15446   for (i = start; i < len; i++)
15447     {
15448       tree parm = pattern;
15449
15450       /* For each parameter pack, clear out the deduced value so that
15451          we can deduce it again.  */
15452       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15453         {
15454           int idx, level;
15455           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15456
15457           TMPL_ARG (targs, level, idx) = NULL_TREE;
15458         }
15459
15460       /* Unify the pattern with the current argument.  */
15461       {
15462         tree arg = TREE_VEC_ELT (packed_args, i);
15463         tree arg_expr = NULL_TREE;
15464         int arg_strict = strict;
15465
15466         if (call_args_p)
15467           {
15468             int sub_strict;
15469
15470             /* This mirrors what we do in type_unification_real.  */
15471             switch (strict)
15472               {
15473               case DEDUCE_CALL:
15474                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
15475                               | UNIFY_ALLOW_MORE_CV_QUAL
15476                               | UNIFY_ALLOW_DERIVED);
15477                 break;
15478                 
15479               case DEDUCE_CONV:
15480                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
15481                 break;
15482                 
15483               case DEDUCE_EXACT:
15484                 sub_strict = UNIFY_ALLOW_NONE;
15485                 break;
15486                 
15487               default:
15488                 gcc_unreachable ();
15489               }
15490
15491             if (!TYPE_P (arg))
15492               {
15493                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
15494                 if (type_unknown_p (arg))
15495                   {
15496                     /* [temp.deduct.type] A template-argument can be
15497                        deduced from a pointer to function or pointer
15498                        to member function argument if the set of
15499                        overloaded functions does not contain function
15500                        templates and at most one of a set of
15501                        overloaded functions provides a unique
15502                        match.  */
15503
15504                     if (resolve_overloaded_unification
15505                         (tparms, targs, parm, arg,
15506                          (unification_kind_t) strict,
15507                          sub_strict, explain_p))
15508                       goto unified;
15509                     return unify_overload_resolution_failure (explain_p, arg);
15510                   }
15511
15512                 arg_expr = arg;
15513                 arg = unlowered_expr_type (arg);
15514                 if (arg == error_mark_node)
15515                   return unify_invalid (explain_p);
15516               }
15517       
15518             arg_strict = sub_strict;
15519
15520             if (!subr)
15521               arg_strict |= 
15522                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
15523                                                   &parm, &arg, arg_expr);
15524           }
15525
15526         /* For deduction from an init-list we need the actual list.  */
15527         if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15528           arg = arg_expr;
15529         RECUR_AND_CHECK_FAILURE (tparms, targs, parm, arg, arg_strict,
15530                                  explain_p);
15531       }
15532
15533     unified:
15534       /* For each parameter pack, collect the deduced value.  */
15535       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15536         {
15537           int idx, level;
15538           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15539
15540           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15541             TMPL_ARG (targs, level, idx);
15542         }
15543     }
15544
15545   /* Verify that the results of unification with the parameter packs
15546      produce results consistent with what we've seen before, and make
15547      the deduced argument packs available.  */
15548   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15549     {
15550       tree old_pack = TREE_VALUE (pack);
15551       tree new_args = TREE_TYPE (pack);
15552       int i, len = TREE_VEC_LENGTH (new_args);
15553       int idx, level;
15554       bool nondeduced_p = false;
15555
15556       /* By default keep the original deduced argument pack.
15557          If necessary, more specific code is going to update the
15558          resulting deduced argument later down in this function.  */
15559       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15560       TMPL_ARG (targs, level, idx) = old_pack;
15561
15562       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15563          actually deduce anything.  */
15564       for (i = 0; i < len && !nondeduced_p; ++i)
15565         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15566           nondeduced_p = true;
15567       if (nondeduced_p)
15568         continue;
15569
15570       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15571         {
15572           /* Prepend the explicit arguments onto NEW_ARGS.  */
15573           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15574           tree old_args = new_args;
15575           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
15576           int len = explicit_len + TREE_VEC_LENGTH (old_args);
15577
15578           /* Copy the explicit arguments.  */
15579           new_args = make_tree_vec (len);
15580           for (i = 0; i < explicit_len; i++)
15581             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
15582
15583           /* Copy the deduced arguments.  */
15584           for (; i < len; i++)
15585             TREE_VEC_ELT (new_args, i) =
15586               TREE_VEC_ELT (old_args, i - explicit_len);
15587         }
15588
15589       if (!old_pack)
15590         {
15591           tree result;
15592           /* Build the deduced *_ARGUMENT_PACK.  */
15593           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15594             {
15595               result = make_node (NONTYPE_ARGUMENT_PACK);
15596               TREE_TYPE (result) = 
15597                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15598               TREE_CONSTANT (result) = 1;
15599             }
15600           else
15601             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15602
15603           SET_ARGUMENT_PACK_ARGS (result, new_args);
15604
15605           /* Note the deduced argument packs for this parameter
15606              pack.  */
15607           TMPL_ARG (targs, level, idx) = result;
15608         }
15609       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15610                && (ARGUMENT_PACK_ARGS (old_pack) 
15611                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15612         {
15613           /* We only had the explicitly-provided arguments before, but
15614              now we have a complete set of arguments.  */
15615           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15616
15617           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15618           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15619           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15620         }
15621       else
15622         {
15623           tree bad_old_arg, bad_new_arg;
15624           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15625
15626           if (!comp_template_args_with_info (old_args, new_args,
15627                                              &bad_old_arg, &bad_new_arg))
15628             /* Inconsistent unification of this parameter pack.  */
15629             return unify_parameter_pack_inconsistent (explain_p,
15630                                                       bad_old_arg,
15631                                                       bad_new_arg);
15632         }
15633     }
15634
15635   return unify_success (explain_p);
15636 }
15637
15638 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15639    set of template parameters to a template.  TARGS is the bindings
15640    for those template parameters, as determined thus far; TARGS may
15641    include template arguments for outer levels of template parameters
15642    as well.  PARM is a parameter to a template function, or a
15643    subcomponent of that parameter; ARG is the corresponding argument.
15644    This function attempts to match PARM with ARG in a manner
15645    consistent with the existing assignments in TARGS.  If more values
15646    are deduced, then TARGS is updated.
15647
15648    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15649    parameter STRICT is a bitwise or of the following flags:
15650
15651      UNIFY_ALLOW_NONE:
15652        Require an exact match between PARM and ARG.
15653      UNIFY_ALLOW_MORE_CV_QUAL:
15654        Allow the deduced ARG to be more cv-qualified (by qualification
15655        conversion) than ARG.
15656      UNIFY_ALLOW_LESS_CV_QUAL:
15657        Allow the deduced ARG to be less cv-qualified than ARG.
15658      UNIFY_ALLOW_DERIVED:
15659        Allow the deduced ARG to be a template base class of ARG,
15660        or a pointer to a template base class of the type pointed to by
15661        ARG.
15662      UNIFY_ALLOW_INTEGER:
15663        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15664        case for more information.
15665      UNIFY_ALLOW_OUTER_LEVEL:
15666        This is the outermost level of a deduction. Used to determine validity
15667        of qualification conversions. A valid qualification conversion must
15668        have const qualified pointers leading up to the inner type which
15669        requires additional CV quals, except at the outer level, where const
15670        is not required [conv.qual]. It would be normal to set this flag in
15671        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15672      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15673        This is the outermost level of a deduction, and PARM can be more CV
15674        qualified at this point.
15675      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15676        This is the outermost level of a deduction, and PARM can be less CV
15677        qualified at this point.  */
15678
15679 static int
15680 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15681        bool explain_p)
15682 {
15683   int idx;
15684   tree targ;
15685   tree tparm;
15686   int strict_in = strict;
15687
15688   /* I don't think this will do the right thing with respect to types.
15689      But the only case I've seen it in so far has been array bounds, where
15690      signedness is the only information lost, and I think that will be
15691      okay.  */
15692   while (TREE_CODE (parm) == NOP_EXPR)
15693     parm = TREE_OPERAND (parm, 0);
15694
15695   if (arg == error_mark_node)
15696     return unify_invalid (explain_p);
15697   if (arg == unknown_type_node
15698       || arg == init_list_type_node)
15699     /* We can't deduce anything from this, but we might get all the
15700        template args from other function args.  */
15701     return unify_success (explain_p);
15702
15703   /* If PARM uses template parameters, then we can't bail out here,
15704      even if ARG == PARM, since we won't record unifications for the
15705      template parameters.  We might need them if we're trying to
15706      figure out which of two things is more specialized.  */
15707   if (arg == parm && !uses_template_parms (parm))
15708     return unify_success (explain_p);
15709
15710   /* Handle init lists early, so the rest of the function can assume
15711      we're dealing with a type. */
15712   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15713     {
15714       tree elt, elttype;
15715       unsigned i;
15716       tree orig_parm = parm;
15717
15718       /* Replace T with std::initializer_list<T> for deduction.  */
15719       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15720           && flag_deduce_init_list)
15721         parm = listify (parm);
15722
15723       if (!is_std_init_list (parm))
15724         /* We can only deduce from an initializer list argument if the
15725            parameter is std::initializer_list; otherwise this is a
15726            non-deduced context. */
15727         return unify_success (explain_p);
15728
15729       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15730
15731       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15732         {
15733           int elt_strict = strict;
15734
15735           if (elt == error_mark_node)
15736             return unify_invalid (explain_p);
15737
15738           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15739             {
15740               tree type = TREE_TYPE (elt);
15741               /* It should only be possible to get here for a call.  */
15742               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15743               elt_strict |= maybe_adjust_types_for_deduction
15744                 (DEDUCE_CALL, &elttype, &type, elt);
15745               elt = type;
15746             }
15747
15748           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15749                                    explain_p);
15750         }
15751
15752       /* If the std::initializer_list<T> deduction worked, replace the
15753          deduced A with std::initializer_list<A>.  */
15754       if (orig_parm != parm)
15755         {
15756           idx = TEMPLATE_TYPE_IDX (orig_parm);
15757           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15758           targ = listify (targ);
15759           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15760         }
15761       return unify_success (explain_p);
15762     }
15763
15764   /* Immediately reject some pairs that won't unify because of
15765      cv-qualification mismatches.  */
15766   if (TREE_CODE (arg) == TREE_CODE (parm)
15767       && TYPE_P (arg)
15768       /* It is the elements of the array which hold the cv quals of an array
15769          type, and the elements might be template type parms. We'll check
15770          when we recurse.  */
15771       && TREE_CODE (arg) != ARRAY_TYPE
15772       /* We check the cv-qualifiers when unifying with template type
15773          parameters below.  We want to allow ARG `const T' to unify with
15774          PARM `T' for example, when computing which of two templates
15775          is more specialized, for example.  */
15776       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15777       && !check_cv_quals_for_unify (strict_in, arg, parm))
15778     return unify_cv_qual_mismatch (explain_p, parm, arg);
15779
15780   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15781       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15782     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15783   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15784   strict &= ~UNIFY_ALLOW_DERIVED;
15785   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15786   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15787
15788   switch (TREE_CODE (parm))
15789     {
15790     case TYPENAME_TYPE:
15791     case SCOPE_REF:
15792     case UNBOUND_CLASS_TEMPLATE:
15793       /* In a type which contains a nested-name-specifier, template
15794          argument values cannot be deduced for template parameters used
15795          within the nested-name-specifier.  */
15796       return unify_success (explain_p);
15797
15798     case TEMPLATE_TYPE_PARM:
15799     case TEMPLATE_TEMPLATE_PARM:
15800     case BOUND_TEMPLATE_TEMPLATE_PARM:
15801       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15802       if (tparm == error_mark_node)
15803         return unify_invalid (explain_p);
15804
15805       if (TEMPLATE_TYPE_LEVEL (parm)
15806           != template_decl_level (tparm))
15807         /* The PARM is not one we're trying to unify.  Just check
15808            to see if it matches ARG.  */
15809         {
15810           if (TREE_CODE (arg) == TREE_CODE (parm)
15811               && same_type_p (parm, arg))
15812             return unify_success (explain_p);
15813           else
15814             return unify_type_mismatch (explain_p, parm, arg);
15815         }
15816       idx = TEMPLATE_TYPE_IDX (parm);
15817       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15818       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15819
15820       /* Check for mixed types and values.  */
15821       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15822            && TREE_CODE (tparm) != TYPE_DECL)
15823           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15824               && TREE_CODE (tparm) != TEMPLATE_DECL))
15825         gcc_unreachable ();
15826
15827       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15828         {
15829           /* ARG must be constructed from a template class or a template
15830              template parameter.  */
15831           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15832               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15833             return unify_template_deduction_failure (explain_p, parm, arg);
15834
15835           {
15836             tree parmvec = TYPE_TI_ARGS (parm);
15837             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15838             tree full_argvec = add_to_template_args (targs, argvec);
15839             tree parm_parms 
15840               = DECL_INNERMOST_TEMPLATE_PARMS
15841                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15842             int i, len;
15843             int parm_variadic_p = 0;
15844
15845             /* The resolution to DR150 makes clear that default
15846                arguments for an N-argument may not be used to bind T
15847                to a template template parameter with fewer than N
15848                parameters.  It is not safe to permit the binding of
15849                default arguments as an extension, as that may change
15850                the meaning of a conforming program.  Consider:
15851
15852                   struct Dense { static const unsigned int dim = 1; };
15853
15854                   template <template <typename> class View,
15855                             typename Block>
15856                   void operator+(float, View<Block> const&);
15857
15858                   template <typename Block,
15859                             unsigned int Dim = Block::dim>
15860                   struct Lvalue_proxy { operator float() const; };
15861
15862                   void
15863                   test_1d (void) {
15864                     Lvalue_proxy<Dense> p;
15865                     float b;
15866                     b + p;
15867                   }
15868
15869               Here, if Lvalue_proxy is permitted to bind to View, then
15870               the global operator+ will be used; if they are not, the
15871               Lvalue_proxy will be converted to float.  */
15872             if (coerce_template_parms (parm_parms,
15873                                        full_argvec,
15874                                        TYPE_TI_TEMPLATE (parm),
15875                                        (explain_p
15876                                         ? tf_warning_or_error
15877                                         : tf_none),
15878                                        /*require_all_args=*/true,
15879                                        /*use_default_args=*/false)
15880                 == error_mark_node)
15881               return 1;
15882
15883             /* Deduce arguments T, i from TT<T> or TT<i>.
15884                We check each element of PARMVEC and ARGVEC individually
15885                rather than the whole TREE_VEC since they can have
15886                different number of elements.  */
15887
15888             parmvec = expand_template_argument_pack (parmvec);
15889             argvec = expand_template_argument_pack (argvec);
15890
15891             len = TREE_VEC_LENGTH (parmvec);
15892
15893             /* Check if the parameters end in a pack, making them
15894                variadic.  */
15895             if (len > 0
15896                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15897               parm_variadic_p = 1;
15898             
15899             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15900               return unify_too_few_arguments (explain_p,
15901                                               TREE_VEC_LENGTH (argvec), len);
15902
15903              for (i = 0; i < len - parm_variadic_p; ++i)
15904               {
15905                 RECUR_AND_CHECK_FAILURE (tparms, targs,
15906                                          TREE_VEC_ELT (parmvec, i),
15907                                          TREE_VEC_ELT (argvec, i),
15908                                          UNIFY_ALLOW_NONE, explain_p);
15909               }
15910
15911             if (parm_variadic_p
15912                 && unify_pack_expansion (tparms, targs,
15913                                          parmvec, argvec,
15914                                          UNIFY_ALLOW_NONE,
15915                                          /*call_args_p=*/false,
15916                                          /*subr=*/false, explain_p))
15917               return 1;
15918           }
15919           arg = TYPE_TI_TEMPLATE (arg);
15920
15921           /* Fall through to deduce template name.  */
15922         }
15923
15924       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15925           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15926         {
15927           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15928
15929           /* Simple cases: Value already set, does match or doesn't.  */
15930           if (targ != NULL_TREE && template_args_equal (targ, arg))
15931             return unify_success (explain_p);
15932           else if (targ)
15933             return unify_inconsistency (explain_p, parm, targ, arg);
15934         }
15935       else
15936         {
15937           /* If PARM is `const T' and ARG is only `int', we don't have
15938              a match unless we are allowing additional qualification.
15939              If ARG is `const int' and PARM is just `T' that's OK;
15940              that binds `const int' to `T'.  */
15941           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15942                                          arg, parm))
15943             return unify_cv_qual_mismatch (explain_p, parm, arg);
15944
15945           /* Consider the case where ARG is `const volatile int' and
15946              PARM is `const T'.  Then, T should be `volatile int'.  */
15947           arg = cp_build_qualified_type_real
15948             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15949           if (arg == error_mark_node)
15950             return unify_invalid (explain_p);
15951
15952           /* Simple cases: Value already set, does match or doesn't.  */
15953           if (targ != NULL_TREE && same_type_p (targ, arg))
15954             return unify_success (explain_p);
15955           else if (targ)
15956             return unify_inconsistency (explain_p, parm, targ, arg);
15957
15958           /* Make sure that ARG is not a variable-sized array.  (Note
15959              that were talking about variable-sized arrays (like
15960              `int[n]'), rather than arrays of unknown size (like
15961              `int[]').)  We'll get very confused by such a type since
15962              the bound of the array is not constant, and therefore
15963              not mangleable.  Besides, such types are not allowed in
15964              ISO C++, so we can do as we please here.  We do allow
15965              them for 'auto' deduction, since that isn't ABI-exposed.  */
15966           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
15967             return unify_vla_arg (explain_p, arg);
15968
15969           /* Strip typedefs as in convert_template_argument.  */
15970           arg = canonicalize_type_argument (arg, tf_none);
15971         }
15972
15973       /* If ARG is a parameter pack or an expansion, we cannot unify
15974          against it unless PARM is also a parameter pack.  */
15975       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15976           && !template_parameter_pack_p (parm))
15977         return unify_parameter_pack_mismatch (explain_p, parm, arg);
15978
15979       /* If the argument deduction results is a METHOD_TYPE,
15980          then there is a problem.
15981          METHOD_TYPE doesn't map to any real C++ type the result of
15982          the deduction can not be of that type.  */
15983       if (TREE_CODE (arg) == METHOD_TYPE)
15984         return unify_method_type_error (explain_p, arg);
15985
15986       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15987       return unify_success (explain_p);
15988
15989     case TEMPLATE_PARM_INDEX:
15990       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15991       if (tparm == error_mark_node)
15992         return unify_invalid (explain_p);
15993
15994       if (TEMPLATE_PARM_LEVEL (parm)
15995           != template_decl_level (tparm))
15996         {
15997           /* The PARM is not one we're trying to unify.  Just check
15998              to see if it matches ARG.  */
15999           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16000                          && cp_tree_equal (parm, arg));
16001           if (result)
16002             unify_expression_unequal (explain_p, parm, arg);
16003           return result;
16004         }
16005
16006       idx = TEMPLATE_PARM_IDX (parm);
16007       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16008
16009       if (targ)
16010         {
16011           int x = !cp_tree_equal (targ, arg);
16012           if (x)
16013             unify_inconsistency (explain_p, parm, targ, arg);
16014           return x;
16015         }
16016
16017       /* [temp.deduct.type] If, in the declaration of a function template
16018          with a non-type template-parameter, the non-type
16019          template-parameter is used in an expression in the function
16020          parameter-list and, if the corresponding template-argument is
16021          deduced, the template-argument type shall match the type of the
16022          template-parameter exactly, except that a template-argument
16023          deduced from an array bound may be of any integral type.
16024          The non-type parameter might use already deduced type parameters.  */
16025       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16026       if (!TREE_TYPE (arg))
16027         /* Template-parameter dependent expression.  Just accept it for now.
16028            It will later be processed in convert_template_argument.  */
16029         ;
16030       else if (same_type_p (TREE_TYPE (arg), tparm))
16031         /* OK */;
16032       else if ((strict & UNIFY_ALLOW_INTEGER)
16033                && (TREE_CODE (tparm) == INTEGER_TYPE
16034                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16035         /* Convert the ARG to the type of PARM; the deduced non-type
16036            template argument must exactly match the types of the
16037            corresponding parameter.  */
16038         arg = fold (build_nop (tparm, arg));
16039       else if (uses_template_parms (tparm))
16040         /* We haven't deduced the type of this parameter yet.  Try again
16041            later.  */
16042         return unify_success (explain_p);
16043       else
16044         return unify_type_mismatch (explain_p, tparm, arg);
16045
16046       /* If ARG is a parameter pack or an expansion, we cannot unify
16047          against it unless PARM is also a parameter pack.  */
16048       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16049           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16050         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16051
16052       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16053       return unify_success (explain_p);
16054
16055     case PTRMEM_CST:
16056      {
16057         /* A pointer-to-member constant can be unified only with
16058          another constant.  */
16059       if (TREE_CODE (arg) != PTRMEM_CST)
16060         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16061
16062       /* Just unify the class member. It would be useless (and possibly
16063          wrong, depending on the strict flags) to unify also
16064          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16065          arg refer to the same variable, even if through different
16066          classes. For instance:
16067
16068          struct A { int x; };
16069          struct B : A { };
16070
16071          Unification of &A::x and &B::x must succeed.  */
16072       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16073                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16074      }
16075
16076     case POINTER_TYPE:
16077       {
16078         if (TREE_CODE (arg) != POINTER_TYPE)
16079           return unify_type_mismatch (explain_p, parm, arg);
16080
16081         /* [temp.deduct.call]
16082
16083            A can be another pointer or pointer to member type that can
16084            be converted to the deduced A via a qualification
16085            conversion (_conv.qual_).
16086
16087            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16088            This will allow for additional cv-qualification of the
16089            pointed-to types if appropriate.  */
16090
16091         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16092           /* The derived-to-base conversion only persists through one
16093              level of pointers.  */
16094           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16095
16096         return unify (tparms, targs, TREE_TYPE (parm),
16097                       TREE_TYPE (arg), strict, explain_p);
16098       }
16099
16100     case REFERENCE_TYPE:
16101       if (TREE_CODE (arg) != REFERENCE_TYPE)
16102         return unify_type_mismatch (explain_p, parm, arg);
16103       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16104                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16105
16106     case ARRAY_TYPE:
16107       if (TREE_CODE (arg) != ARRAY_TYPE)
16108         return unify_type_mismatch (explain_p, parm, arg);
16109       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16110           != (TYPE_DOMAIN (arg) == NULL_TREE))
16111         return unify_type_mismatch (explain_p, parm, arg);
16112       if (TYPE_DOMAIN (parm) != NULL_TREE)
16113         {
16114           tree parm_max;
16115           tree arg_max;
16116           bool parm_cst;
16117           bool arg_cst;
16118
16119           /* Our representation of array types uses "N - 1" as the
16120              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16121              not an integer constant.  We cannot unify arbitrarily
16122              complex expressions, so we eliminate the MINUS_EXPRs
16123              here.  */
16124           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16125           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16126           if (!parm_cst)
16127             {
16128               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16129               parm_max = TREE_OPERAND (parm_max, 0);
16130             }
16131           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16132           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16133           if (!arg_cst)
16134             {
16135               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16136                  trying to unify the type of a variable with the type
16137                  of a template parameter.  For example:
16138
16139                    template <unsigned int N>
16140                    void f (char (&) [N]);
16141                    int g(); 
16142                    void h(int i) {
16143                      char a[g(i)];
16144                      f(a); 
16145                    }
16146
16147                 Here, the type of the ARG will be "int [g(i)]", and
16148                 may be a SAVE_EXPR, etc.  */
16149               if (TREE_CODE (arg_max) != MINUS_EXPR)
16150                 return unify_vla_arg (explain_p, arg);
16151               arg_max = TREE_OPERAND (arg_max, 0);
16152             }
16153
16154           /* If only one of the bounds used a MINUS_EXPR, compensate
16155              by adding one to the other bound.  */
16156           if (parm_cst && !arg_cst)
16157             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16158                                     integer_type_node,
16159                                     parm_max,
16160                                     integer_one_node);
16161           else if (arg_cst && !parm_cst)
16162             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16163                                    integer_type_node,
16164                                    arg_max,
16165                                    integer_one_node);
16166
16167           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16168                                    UNIFY_ALLOW_INTEGER, explain_p);
16169         }
16170       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16171                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16172
16173     case REAL_TYPE:
16174     case COMPLEX_TYPE:
16175     case VECTOR_TYPE:
16176     case INTEGER_TYPE:
16177     case BOOLEAN_TYPE:
16178     case ENUMERAL_TYPE:
16179     case VOID_TYPE:
16180       if (TREE_CODE (arg) != TREE_CODE (parm))
16181         return unify_type_mismatch (explain_p, parm, arg);
16182
16183       /* We have already checked cv-qualification at the top of the
16184          function.  */
16185       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16186         return unify_type_mismatch (explain_p, parm, arg);
16187
16188       /* As far as unification is concerned, this wins.  Later checks
16189          will invalidate it if necessary.  */
16190       return unify_success (explain_p);
16191
16192       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16193       /* Type INTEGER_CST can come from ordinary constant template args.  */
16194     case INTEGER_CST:
16195       while (TREE_CODE (arg) == NOP_EXPR)
16196         arg = TREE_OPERAND (arg, 0);
16197
16198       if (TREE_CODE (arg) != INTEGER_CST)
16199         return unify_template_argument_mismatch (explain_p, parm, arg);
16200       return (tree_int_cst_equal (parm, arg)
16201               ? unify_success (explain_p)
16202               : unify_template_argument_mismatch (explain_p, parm, arg));
16203
16204     case TREE_VEC:
16205       {
16206         int i;
16207         if (TREE_CODE (arg) != TREE_VEC)
16208           return unify_template_argument_mismatch (explain_p, parm, arg);
16209         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
16210           return unify_arity (explain_p, TREE_VEC_LENGTH (arg),
16211                               TREE_VEC_LENGTH (parm));
16212         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
16213           RECUR_AND_CHECK_FAILURE (tparms, targs,
16214                                    TREE_VEC_ELT (parm, i),
16215                                    TREE_VEC_ELT (arg, i),
16216                                    UNIFY_ALLOW_NONE, explain_p);
16217         return unify_success (explain_p);
16218       }
16219
16220     case RECORD_TYPE:
16221     case UNION_TYPE:
16222       if (TREE_CODE (arg) != TREE_CODE (parm))
16223         return unify_type_mismatch (explain_p, parm, arg);
16224
16225       if (TYPE_PTRMEMFUNC_P (parm))
16226         {
16227           if (!TYPE_PTRMEMFUNC_P (arg))
16228             return unify_type_mismatch (explain_p, parm, arg);
16229
16230           return unify (tparms, targs,
16231                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16232                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16233                         strict, explain_p);
16234         }
16235
16236       if (CLASSTYPE_TEMPLATE_INFO (parm))
16237         {
16238           tree t = NULL_TREE;
16239
16240           if (strict_in & UNIFY_ALLOW_DERIVED)
16241             {
16242               /* First, we try to unify the PARM and ARG directly.  */
16243               t = try_class_unification (tparms, targs,
16244                                          parm, arg, explain_p);
16245
16246               if (!t)
16247                 {
16248                   /* Fallback to the special case allowed in
16249                      [temp.deduct.call]:
16250
16251                        If P is a class, and P has the form
16252                        template-id, then A can be a derived class of
16253                        the deduced A.  Likewise, if P is a pointer to
16254                        a class of the form template-id, A can be a
16255                        pointer to a derived class pointed to by the
16256                        deduced A.  */
16257                   enum template_base_result r;
16258                   r = get_template_base (tparms, targs, parm, arg,
16259                                          explain_p, &t);
16260
16261                   if (!t)
16262                     return unify_no_common_base (explain_p, r, parm, arg);
16263                 }
16264             }
16265           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16266                    && (CLASSTYPE_TI_TEMPLATE (parm)
16267                        == CLASSTYPE_TI_TEMPLATE (arg)))
16268             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16269                Then, we should unify `int' and `U'.  */
16270             t = arg;
16271           else
16272             /* There's no chance of unification succeeding.  */
16273             return unify_type_mismatch (explain_p, parm, arg);
16274
16275           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16276                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16277         }
16278       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16279         return unify_type_mismatch (explain_p, parm, arg);
16280       return unify_success (explain_p);
16281
16282     case METHOD_TYPE:
16283     case FUNCTION_TYPE:
16284       {
16285         unsigned int nargs;
16286         tree *args;
16287         tree a;
16288         unsigned int i;
16289
16290         if (TREE_CODE (arg) != TREE_CODE (parm))
16291           return unify_type_mismatch (explain_p, parm, arg);
16292
16293         /* CV qualifications for methods can never be deduced, they must
16294            match exactly.  We need to check them explicitly here,
16295            because type_unification_real treats them as any other
16296            cv-qualified parameter.  */
16297         if (TREE_CODE (parm) == METHOD_TYPE
16298             && (!check_cv_quals_for_unify
16299                 (UNIFY_ALLOW_NONE,
16300                  class_of_this_parm (arg),
16301                  class_of_this_parm (parm))))
16302           return unify_cv_qual_mismatch (explain_p, parm, arg);
16303
16304         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16305                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16306
16307         nargs = list_length (TYPE_ARG_TYPES (arg));
16308         args = XALLOCAVEC (tree, nargs);
16309         for (a = TYPE_ARG_TYPES (arg), i = 0;
16310              a != NULL_TREE && a != void_list_node;
16311              a = TREE_CHAIN (a), ++i)
16312           args[i] = TREE_VALUE (a);
16313         nargs = i;
16314
16315         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16316                                       args, nargs, 1, DEDUCE_EXACT,
16317                                       LOOKUP_NORMAL, explain_p);
16318       }
16319
16320     case OFFSET_TYPE:
16321       /* Unify a pointer to member with a pointer to member function, which
16322          deduces the type of the member as a function type. */
16323       if (TYPE_PTRMEMFUNC_P (arg))
16324         {
16325           tree method_type;
16326           tree fntype;
16327
16328           /* Check top-level cv qualifiers */
16329           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16330             return unify_cv_qual_mismatch (explain_p, parm, arg);
16331
16332           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16333                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16334                                    UNIFY_ALLOW_NONE, explain_p);
16335
16336           /* Determine the type of the function we are unifying against. */
16337           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16338           fntype =
16339             build_function_type (TREE_TYPE (method_type),
16340                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16341
16342           /* Extract the cv-qualifiers of the member function from the
16343              implicit object parameter and place them on the function
16344              type to be restored later. */
16345           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16346           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16347         }
16348
16349       if (TREE_CODE (arg) != OFFSET_TYPE)
16350         return unify_type_mismatch (explain_p, parm, arg);
16351       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16352                                TYPE_OFFSET_BASETYPE (arg),
16353                                UNIFY_ALLOW_NONE, explain_p);
16354       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16355                     strict, explain_p);
16356
16357     case CONST_DECL:
16358       if (DECL_TEMPLATE_PARM_P (parm))
16359         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16360       if (arg != integral_constant_value (parm))
16361         return unify_template_argument_mismatch (explain_p, parm, arg);
16362       return unify_success (explain_p);
16363
16364     case FIELD_DECL:
16365     case TEMPLATE_DECL:
16366       /* Matched cases are handled by the ARG == PARM test above.  */
16367       return unify_template_argument_mismatch (explain_p, parm, arg);
16368
16369     case VAR_DECL:
16370       /* A non-type template parameter that is a variable should be a
16371          an integral constant, in which case, it whould have been
16372          folded into its (constant) value. So we should not be getting
16373          a variable here.  */
16374       gcc_unreachable ();
16375
16376     case TYPE_ARGUMENT_PACK:
16377     case NONTYPE_ARGUMENT_PACK:
16378       {
16379         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
16380         tree packed_args = ARGUMENT_PACK_ARGS (arg);
16381         int i, len = TREE_VEC_LENGTH (packed_parms);
16382         int argslen = TREE_VEC_LENGTH (packed_args);
16383         int parm_variadic_p = 0;
16384
16385         for (i = 0; i < len; ++i)
16386           {
16387             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
16388               {
16389                 if (i == len - 1)
16390                   /* We can unify against something with a trailing
16391                      parameter pack.  */
16392                   parm_variadic_p = 1;
16393                 else
16394                   /* Since there is something following the pack
16395                      expansion, we cannot unify this template argument
16396                      list.  */
16397                   return unify_success (explain_p);
16398               }
16399           }
16400           
16401
16402         /* If we don't have enough arguments to satisfy the parameters
16403            (not counting the pack expression at the end), or we have
16404            too many arguments for a parameter list that doesn't end in
16405            a pack expression, we can't unify.  */
16406         if (argslen < (len - parm_variadic_p))
16407           return unify_too_few_arguments (explain_p, argslen, len);
16408         if (argslen > len && !parm_variadic_p)
16409           return unify_too_many_arguments (explain_p, argslen, len);
16410
16411         /* Unify all of the parameters that precede the (optional)
16412            pack expression.  */
16413         for (i = 0; i < len - parm_variadic_p; ++i)
16414           {
16415             RECUR_AND_CHECK_FAILURE (tparms, targs,
16416                                      TREE_VEC_ELT (packed_parms, i),
16417                                      TREE_VEC_ELT (packed_args, i),
16418                                      strict, explain_p);
16419           }
16420
16421         if (parm_variadic_p)
16422           return unify_pack_expansion (tparms, targs, 
16423                                        packed_parms, packed_args,
16424                                        strict, /*call_args_p=*/false,
16425                                        /*subr=*/false, explain_p);
16426         return unify_success (explain_p);
16427       }
16428
16429       break;
16430
16431     case TYPEOF_TYPE:
16432     case DECLTYPE_TYPE:
16433     case UNDERLYING_TYPE:
16434       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16435          or UNDERLYING_TYPE nodes.  */
16436       return unify_success (explain_p);
16437
16438     case ERROR_MARK:
16439       /* Unification fails if we hit an error node.  */
16440       return unify_invalid (explain_p);
16441
16442     default:
16443       /* An unresolved overload is a nondeduced context.  */
16444       if (type_unknown_p (parm))
16445         return unify_success (explain_p);
16446       gcc_assert (EXPR_P (parm));
16447
16448       /* We must be looking at an expression.  This can happen with
16449          something like:
16450
16451            template <int I>
16452            void foo(S<I>, S<I + 2>);
16453
16454          This is a "nondeduced context":
16455
16456            [deduct.type]
16457
16458            The nondeduced contexts are:
16459
16460            --A type that is a template-id in which one or more of
16461              the template-arguments is an expression that references
16462              a template-parameter.
16463
16464          In these cases, we assume deduction succeeded, but don't
16465          actually infer any unifications.  */
16466
16467       if (!uses_template_parms (parm)
16468           && !template_args_equal (parm, arg))
16469         return unify_expression_unequal (explain_p, parm, arg);
16470       else
16471         return unify_success (explain_p);
16472     }
16473 }
16474 #undef RECUR_AND_CHECK_FAILURE
16475 \f
16476 /* Note that DECL can be defined in this translation unit, if
16477    required.  */
16478
16479 static void
16480 mark_definable (tree decl)
16481 {
16482   tree clone;
16483   DECL_NOT_REALLY_EXTERN (decl) = 1;
16484   FOR_EACH_CLONE (clone, decl)
16485     DECL_NOT_REALLY_EXTERN (clone) = 1;
16486 }
16487
16488 /* Called if RESULT is explicitly instantiated, or is a member of an
16489    explicitly instantiated class.  */
16490
16491 void
16492 mark_decl_instantiated (tree result, int extern_p)
16493 {
16494   SET_DECL_EXPLICIT_INSTANTIATION (result);
16495
16496   /* If this entity has already been written out, it's too late to
16497      make any modifications.  */
16498   if (TREE_ASM_WRITTEN (result))
16499     return;
16500
16501   if (TREE_CODE (result) != FUNCTION_DECL)
16502     /* The TREE_PUBLIC flag for function declarations will have been
16503        set correctly by tsubst.  */
16504     TREE_PUBLIC (result) = 1;
16505
16506   /* This might have been set by an earlier implicit instantiation.  */
16507   DECL_COMDAT (result) = 0;
16508
16509   if (extern_p)
16510     DECL_NOT_REALLY_EXTERN (result) = 0;
16511   else
16512     {
16513       mark_definable (result);
16514       /* Always make artificials weak.  */
16515       if (DECL_ARTIFICIAL (result) && flag_weak)
16516         comdat_linkage (result);
16517       /* For WIN32 we also want to put explicit instantiations in
16518          linkonce sections.  */
16519       else if (TREE_PUBLIC (result))
16520         maybe_make_one_only (result);
16521     }
16522
16523   /* If EXTERN_P, then this function will not be emitted -- unless
16524      followed by an explicit instantiation, at which point its linkage
16525      will be adjusted.  If !EXTERN_P, then this function will be
16526      emitted here.  In neither circumstance do we want
16527      import_export_decl to adjust the linkage.  */
16528   DECL_INTERFACE_KNOWN (result) = 1;
16529 }
16530
16531 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16532    important template arguments.  If any are missing, we check whether
16533    they're important by using error_mark_node for substituting into any
16534    args that were used for partial ordering (the ones between ARGS and END)
16535    and seeing if it bubbles up.  */
16536
16537 static bool
16538 check_undeduced_parms (tree targs, tree args, tree end)
16539 {
16540   bool found = false;
16541   int i;
16542   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16543     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16544       {
16545         found = true;
16546         TREE_VEC_ELT (targs, i) = error_mark_node;
16547       }
16548   if (found)
16549     {
16550       for (; args != end; args = TREE_CHAIN (args))
16551         {
16552           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
16553           if (substed == error_mark_node)
16554             return true;
16555         }
16556     }
16557   return false;
16558 }
16559
16560 /* Given two function templates PAT1 and PAT2, return:
16561
16562    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16563    -1 if PAT2 is more specialized than PAT1.
16564    0 if neither is more specialized.
16565
16566    LEN indicates the number of parameters we should consider
16567    (defaulted parameters should not be considered).
16568
16569    The 1998 std underspecified function template partial ordering, and
16570    DR214 addresses the issue.  We take pairs of arguments, one from
16571    each of the templates, and deduce them against each other.  One of
16572    the templates will be more specialized if all the *other*
16573    template's arguments deduce against its arguments and at least one
16574    of its arguments *does* *not* deduce against the other template's
16575    corresponding argument.  Deduction is done as for class templates.
16576    The arguments used in deduction have reference and top level cv
16577    qualifiers removed.  Iff both arguments were originally reference
16578    types *and* deduction succeeds in both directions, the template
16579    with the more cv-qualified argument wins for that pairing (if
16580    neither is more cv-qualified, they both are equal).  Unlike regular
16581    deduction, after all the arguments have been deduced in this way,
16582    we do *not* verify the deduced template argument values can be
16583    substituted into non-deduced contexts.
16584
16585    The logic can be a bit confusing here, because we look at deduce1 and
16586    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16587    can find template arguments for pat1 to make arg1 look like arg2, that
16588    means that arg2 is at least as specialized as arg1.  */
16589
16590 int
16591 more_specialized_fn (tree pat1, tree pat2, int len)
16592 {
16593   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16594   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16595   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16596   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16597   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16598   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16599   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16600   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16601   tree origs1, origs2;
16602   bool lose1 = false;
16603   bool lose2 = false;
16604
16605   /* Remove the this parameter from non-static member functions.  If
16606      one is a non-static member function and the other is not a static
16607      member function, remove the first parameter from that function
16608      also.  This situation occurs for operator functions where we
16609      locate both a member function (with this pointer) and non-member
16610      operator (with explicit first operand).  */
16611   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16612     {
16613       len--; /* LEN is the number of significant arguments for DECL1 */
16614       args1 = TREE_CHAIN (args1);
16615       if (!DECL_STATIC_FUNCTION_P (decl2))
16616         args2 = TREE_CHAIN (args2);
16617     }
16618   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16619     {
16620       args2 = TREE_CHAIN (args2);
16621       if (!DECL_STATIC_FUNCTION_P (decl1))
16622         {
16623           len--;
16624           args1 = TREE_CHAIN (args1);
16625         }
16626     }
16627
16628   /* If only one is a conversion operator, they are unordered.  */
16629   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16630     return 0;
16631
16632   /* Consider the return type for a conversion function */
16633   if (DECL_CONV_FN_P (decl1))
16634     {
16635       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16636       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16637       len++;
16638     }
16639
16640   processing_template_decl++;
16641
16642   origs1 = args1;
16643   origs2 = args2;
16644
16645   while (len--
16646          /* Stop when an ellipsis is seen.  */
16647          && args1 != NULL_TREE && args2 != NULL_TREE)
16648     {
16649       tree arg1 = TREE_VALUE (args1);
16650       tree arg2 = TREE_VALUE (args2);
16651       int deduce1, deduce2;
16652       int quals1 = -1;
16653       int quals2 = -1;
16654
16655       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16656           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16657         {
16658           /* When both arguments are pack expansions, we need only
16659              unify the patterns themselves.  */
16660           arg1 = PACK_EXPANSION_PATTERN (arg1);
16661           arg2 = PACK_EXPANSION_PATTERN (arg2);
16662
16663           /* This is the last comparison we need to do.  */
16664           len = 0;
16665         }
16666
16667       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16668         {
16669           arg1 = TREE_TYPE (arg1);
16670           quals1 = cp_type_quals (arg1);
16671         }
16672
16673       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16674         {
16675           arg2 = TREE_TYPE (arg2);
16676           quals2 = cp_type_quals (arg2);
16677         }
16678
16679       if ((quals1 < 0) != (quals2 < 0))
16680         {
16681           /* Only of the args is a reference, see if we should apply
16682              array/function pointer decay to it.  This is not part of
16683              DR214, but is, IMHO, consistent with the deduction rules
16684              for the function call itself, and with our earlier
16685              implementation of the underspecified partial ordering
16686              rules.  (nathan).  */
16687           if (quals1 >= 0)
16688             {
16689               switch (TREE_CODE (arg1))
16690                 {
16691                 case ARRAY_TYPE:
16692                   arg1 = TREE_TYPE (arg1);
16693                   /* FALLTHROUGH. */
16694                 case FUNCTION_TYPE:
16695                   arg1 = build_pointer_type (arg1);
16696                   break;
16697
16698                 default:
16699                   break;
16700                 }
16701             }
16702           else
16703             {
16704               switch (TREE_CODE (arg2))
16705                 {
16706                 case ARRAY_TYPE:
16707                   arg2 = TREE_TYPE (arg2);
16708                   /* FALLTHROUGH. */
16709                 case FUNCTION_TYPE:
16710                   arg2 = build_pointer_type (arg2);
16711                   break;
16712
16713                 default:
16714                   break;
16715                 }
16716             }
16717         }
16718
16719       arg1 = TYPE_MAIN_VARIANT (arg1);
16720       arg2 = TYPE_MAIN_VARIANT (arg2);
16721
16722       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16723         {
16724           int i, len2 = list_length (args2);
16725           tree parmvec = make_tree_vec (1);
16726           tree argvec = make_tree_vec (len2);
16727           tree ta = args2;
16728
16729           /* Setup the parameter vector, which contains only ARG1.  */
16730           TREE_VEC_ELT (parmvec, 0) = arg1;
16731
16732           /* Setup the argument vector, which contains the remaining
16733              arguments.  */
16734           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16735             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16736
16737           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16738                                            argvec, UNIFY_ALLOW_NONE, 
16739                                            /*call_args_p=*/false, 
16740                                            /*subr=*/0, /*explain_p=*/false)
16741                      == 0);
16742
16743           /* We cannot deduce in the other direction, because ARG1 is
16744              a pack expansion but ARG2 is not.  */
16745           deduce2 = 0;
16746         }
16747       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16748         {
16749           int i, len1 = list_length (args1);
16750           tree parmvec = make_tree_vec (1);
16751           tree argvec = make_tree_vec (len1);
16752           tree ta = args1;
16753
16754           /* Setup the parameter vector, which contains only ARG1.  */
16755           TREE_VEC_ELT (parmvec, 0) = arg2;
16756
16757           /* Setup the argument vector, which contains the remaining
16758              arguments.  */
16759           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16760             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16761
16762           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16763                                            argvec, UNIFY_ALLOW_NONE, 
16764                                            /*call_args_p=*/false, 
16765                                            /*subr=*/0, /*explain_p=*/false)
16766                      == 0);
16767
16768           /* We cannot deduce in the other direction, because ARG2 is
16769              a pack expansion but ARG1 is not.*/
16770           deduce1 = 0;
16771         }
16772
16773       else
16774         {
16775           /* The normal case, where neither argument is a pack
16776              expansion.  */
16777           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16778                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16779                      == 0);
16780           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16781                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16782                      == 0);
16783         }
16784
16785       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16786          arg2, then arg2 is not as specialized as arg1.  */
16787       if (!deduce1)
16788         lose2 = true;
16789       if (!deduce2)
16790         lose1 = true;
16791
16792       /* "If, for a given type, deduction succeeds in both directions
16793          (i.e., the types are identical after the transformations above)
16794          and if the type from the argument template is more cv-qualified
16795          than the type from the parameter template (as described above)
16796          that type is considered to be more specialized than the other. If
16797          neither type is more cv-qualified than the other then neither type
16798          is more specialized than the other."  */
16799
16800       if (deduce1 && deduce2
16801           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
16802         {
16803           if ((quals1 & quals2) == quals2)
16804             lose2 = true;
16805           if ((quals1 & quals2) == quals1)
16806             lose1 = true;
16807         }
16808
16809       if (lose1 && lose2)
16810         /* We've failed to deduce something in either direction.
16811            These must be unordered.  */
16812         break;
16813
16814       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16815           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16816         /* We have already processed all of the arguments in our
16817            handing of the pack expansion type.  */
16818         len = 0;
16819
16820       args1 = TREE_CHAIN (args1);
16821       args2 = TREE_CHAIN (args2);
16822     }
16823
16824   /* "In most cases, all template parameters must have values in order for
16825      deduction to succeed, but for partial ordering purposes a template
16826      parameter may remain without a value provided it is not used in the
16827      types being used for partial ordering."
16828
16829      Thus, if we are missing any of the targs1 we need to substitute into
16830      origs1, then pat2 is not as specialized as pat1.  This can happen when
16831      there is a nondeduced context.  */
16832   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16833     lose2 = true;
16834   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16835     lose1 = true;
16836
16837   processing_template_decl--;
16838
16839   /* All things being equal, if the next argument is a pack expansion
16840      for one function but not for the other, prefer the
16841      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16842   if (lose1 == lose2
16843       && args1 && TREE_VALUE (args1)
16844       && args2 && TREE_VALUE (args2))
16845     {
16846       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16847       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16848     }
16849
16850   if (lose1 == lose2)
16851     return 0;
16852   else if (!lose1)
16853     return 1;
16854   else
16855     return -1;
16856 }
16857
16858 /* Determine which of two partial specializations is more specialized.
16859
16860    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16861    to the first partial specialization.  The TREE_VALUE is the
16862    innermost set of template parameters for the partial
16863    specialization.  PAT2 is similar, but for the second template.
16864
16865    Return 1 if the first partial specialization is more specialized;
16866    -1 if the second is more specialized; 0 if neither is more
16867    specialized.
16868
16869    See [temp.class.order] for information about determining which of
16870    two templates is more specialized.  */
16871
16872 static int
16873 more_specialized_class (tree pat1, tree pat2)
16874 {
16875   tree targs;
16876   tree tmpl1, tmpl2;
16877   int winner = 0;
16878   bool any_deductions = false;
16879
16880   tmpl1 = TREE_TYPE (pat1);
16881   tmpl2 = TREE_TYPE (pat2);
16882
16883   /* Just like what happens for functions, if we are ordering between
16884      different class template specializations, we may encounter dependent
16885      types in the arguments, and we need our dependency check functions
16886      to behave correctly.  */
16887   ++processing_template_decl;
16888   targs = get_class_bindings (TREE_VALUE (pat1),
16889                               CLASSTYPE_TI_ARGS (tmpl1),
16890                               CLASSTYPE_TI_ARGS (tmpl2));
16891   if (targs)
16892     {
16893       --winner;
16894       any_deductions = true;
16895     }
16896
16897   targs = get_class_bindings (TREE_VALUE (pat2),
16898                               CLASSTYPE_TI_ARGS (tmpl2),
16899                               CLASSTYPE_TI_ARGS (tmpl1));
16900   if (targs)
16901     {
16902       ++winner;
16903       any_deductions = true;
16904     }
16905   --processing_template_decl;
16906
16907   /* In the case of a tie where at least one of the class templates
16908      has a parameter pack at the end, the template with the most
16909      non-packed parameters wins.  */
16910   if (winner == 0
16911       && any_deductions
16912       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16913           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16914     {
16915       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16916       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16917       int len1 = TREE_VEC_LENGTH (args1);
16918       int len2 = TREE_VEC_LENGTH (args2);
16919
16920       /* We don't count the pack expansion at the end.  */
16921       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16922         --len1;
16923       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16924         --len2;
16925
16926       if (len1 > len2)
16927         return 1;
16928       else if (len1 < len2)
16929         return -1;
16930     }
16931
16932   return winner;
16933 }
16934
16935 /* Return the template arguments that will produce the function signature
16936    DECL from the function template FN, with the explicit template
16937    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16938    also match.  Return NULL_TREE if no satisfactory arguments could be
16939    found.  */
16940
16941 static tree
16942 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16943 {
16944   int ntparms = DECL_NTPARMS (fn);
16945   tree targs = make_tree_vec (ntparms);
16946   tree decl_type;
16947   tree decl_arg_types;
16948   tree *args;
16949   unsigned int nargs, ix;
16950   tree arg;
16951
16952   /* Substitute the explicit template arguments into the type of DECL.
16953      The call to fn_type_unification will handle substitution into the
16954      FN.  */
16955   decl_type = TREE_TYPE (decl);
16956   if (explicit_args && uses_template_parms (decl_type))
16957     {
16958       tree tmpl;
16959       tree converted_args;
16960
16961       if (DECL_TEMPLATE_INFO (decl))
16962         tmpl = DECL_TI_TEMPLATE (decl);
16963       else
16964         /* We can get here for some invalid specializations.  */
16965         return NULL_TREE;
16966
16967       converted_args
16968         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16969                                  explicit_args, NULL_TREE,
16970                                  tf_none,
16971                                  /*require_all_args=*/false,
16972                                  /*use_default_args=*/false);
16973       if (converted_args == error_mark_node)
16974         return NULL_TREE;
16975
16976       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16977       if (decl_type == error_mark_node)
16978         return NULL_TREE;
16979     }
16980
16981   /* Never do unification on the 'this' parameter.  */
16982   decl_arg_types = skip_artificial_parms_for (decl, 
16983                                               TYPE_ARG_TYPES (decl_type));
16984
16985   nargs = list_length (decl_arg_types);
16986   args = XALLOCAVEC (tree, nargs);
16987   for (arg = decl_arg_types, ix = 0;
16988        arg != NULL_TREE && arg != void_list_node;
16989        arg = TREE_CHAIN (arg), ++ix)
16990     args[ix] = TREE_VALUE (arg);
16991
16992   if (fn_type_unification (fn, explicit_args, targs,
16993                            args, ix,
16994                            (check_rettype || DECL_CONV_FN_P (fn)
16995                             ? TREE_TYPE (decl_type) : NULL_TREE),
16996                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
16997     return NULL_TREE;
16998
16999   return targs;
17000 }
17001
17002 /* Return the innermost template arguments that, when applied to a
17003    template specialization whose innermost template parameters are
17004    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17005    ARGS.
17006
17007    For example, suppose we have:
17008
17009      template <class T, class U> struct S {};
17010      template <class T> struct S<T*, int> {};
17011
17012    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17013    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17014    int}.  The resulting vector will be {double}, indicating that `T'
17015    is bound to `double'.  */
17016
17017 static tree
17018 get_class_bindings (tree tparms, tree spec_args, tree args)
17019 {
17020   int i, ntparms = TREE_VEC_LENGTH (tparms);
17021   tree deduced_args;
17022   tree innermost_deduced_args;
17023
17024   innermost_deduced_args = make_tree_vec (ntparms);
17025   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17026     {
17027       deduced_args = copy_node (args);
17028       SET_TMPL_ARGS_LEVEL (deduced_args,
17029                            TMPL_ARGS_DEPTH (deduced_args),
17030                            innermost_deduced_args);
17031     }
17032   else
17033     deduced_args = innermost_deduced_args;
17034
17035   if (unify (tparms, deduced_args,
17036              INNERMOST_TEMPLATE_ARGS (spec_args),
17037              INNERMOST_TEMPLATE_ARGS (args),
17038              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17039     return NULL_TREE;
17040
17041   for (i =  0; i < ntparms; ++i)
17042     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17043       return NULL_TREE;
17044
17045   /* Verify that nondeduced template arguments agree with the type
17046      obtained from argument deduction.
17047
17048      For example:
17049
17050        struct A { typedef int X; };
17051        template <class T, class U> struct C {};
17052        template <class T> struct C<T, typename T::X> {};
17053
17054      Then with the instantiation `C<A, int>', we can deduce that
17055      `T' is `A' but unify () does not check whether `typename T::X'
17056      is `int'.  */
17057   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17058   if (spec_args == error_mark_node
17059       /* We only need to check the innermost arguments; the other
17060          arguments will always agree.  */
17061       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17062                               INNERMOST_TEMPLATE_ARGS (args)))
17063     return NULL_TREE;
17064
17065   /* Now that we have bindings for all of the template arguments,
17066      ensure that the arguments deduced for the template template
17067      parameters have compatible template parameter lists.  See the use
17068      of template_template_parm_bindings_ok_p in fn_type_unification
17069      for more information.  */
17070   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17071     return NULL_TREE;
17072
17073   return deduced_args;
17074 }
17075
17076 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17077    Return the TREE_LIST node with the most specialized template, if
17078    any.  If there is no most specialized template, the error_mark_node
17079    is returned.
17080
17081    Note that this function does not look at, or modify, the
17082    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17083    returned is one of the elements of INSTANTIATIONS, callers may
17084    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17085    and retrieve it from the value returned.  */
17086
17087 tree
17088 most_specialized_instantiation (tree templates)
17089 {
17090   tree fn, champ;
17091
17092   ++processing_template_decl;
17093
17094   champ = templates;
17095   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17096     {
17097       int fate = 0;
17098
17099       if (get_bindings (TREE_VALUE (champ),
17100                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17101                         NULL_TREE, /*check_ret=*/true))
17102         fate--;
17103
17104       if (get_bindings (TREE_VALUE (fn),
17105                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17106                         NULL_TREE, /*check_ret=*/true))
17107         fate++;
17108
17109       if (fate == -1)
17110         champ = fn;
17111       else if (!fate)
17112         {
17113           /* Equally specialized, move to next function.  If there
17114              is no next function, nothing's most specialized.  */
17115           fn = TREE_CHAIN (fn);
17116           champ = fn;
17117           if (!fn)
17118             break;
17119         }
17120     }
17121
17122   if (champ)
17123     /* Now verify that champ is better than everything earlier in the
17124        instantiation list.  */
17125     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17126       if (get_bindings (TREE_VALUE (champ),
17127                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17128                         NULL_TREE, /*check_ret=*/true)
17129           || !get_bindings (TREE_VALUE (fn),
17130                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17131                             NULL_TREE, /*check_ret=*/true))
17132         {
17133           champ = NULL_TREE;
17134           break;
17135         }
17136
17137   processing_template_decl--;
17138
17139   if (!champ)
17140     return error_mark_node;
17141
17142   return champ;
17143 }
17144
17145 /* If DECL is a specialization of some template, return the most
17146    general such template.  Otherwise, returns NULL_TREE.
17147
17148    For example, given:
17149
17150      template <class T> struct S { template <class U> void f(U); };
17151
17152    if TMPL is `template <class U> void S<int>::f(U)' this will return
17153    the full template.  This function will not trace past partial
17154    specializations, however.  For example, given in addition:
17155
17156      template <class T> struct S<T*> { template <class U> void f(U); };
17157
17158    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17159    `template <class T> template <class U> S<T*>::f(U)'.  */
17160
17161 tree
17162 most_general_template (tree decl)
17163 {
17164   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17165      an immediate specialization.  */
17166   if (TREE_CODE (decl) == FUNCTION_DECL)
17167     {
17168       if (DECL_TEMPLATE_INFO (decl)) {
17169         decl = DECL_TI_TEMPLATE (decl);
17170
17171         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17172            template friend.  */
17173         if (TREE_CODE (decl) != TEMPLATE_DECL)
17174           return NULL_TREE;
17175       } else
17176         return NULL_TREE;
17177     }
17178
17179   /* Look for more and more general templates.  */
17180   while (DECL_TEMPLATE_INFO (decl))
17181     {
17182       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17183          (See cp-tree.h for details.)  */
17184       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17185         break;
17186
17187       if (CLASS_TYPE_P (TREE_TYPE (decl))
17188           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17189         break;
17190
17191       /* Stop if we run into an explicitly specialized class template.  */
17192       if (!DECL_NAMESPACE_SCOPE_P (decl)
17193           && DECL_CONTEXT (decl)
17194           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17195         break;
17196
17197       decl = DECL_TI_TEMPLATE (decl);
17198     }
17199
17200   return decl;
17201 }
17202
17203 /* Return the most specialized of the class template partial
17204    specializations of TMPL which can produce TYPE, a specialization of
17205    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17206    a _TYPE node corresponding to the partial specialization, while the
17207    TREE_PURPOSE is the set of template arguments that must be
17208    substituted into the TREE_TYPE in order to generate TYPE.
17209
17210    If the choice of partial specialization is ambiguous, a diagnostic
17211    is issued, and the error_mark_node is returned.  If there are no
17212    partial specializations of TMPL matching TYPE, then NULL_TREE is
17213    returned.  */
17214
17215 static tree
17216 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17217 {
17218   tree list = NULL_TREE;
17219   tree t;
17220   tree champ;
17221   int fate;
17222   bool ambiguous_p;
17223   tree args;
17224   tree outer_args = NULL_TREE;
17225
17226   tmpl = most_general_template (tmpl);
17227   args = CLASSTYPE_TI_ARGS (type);
17228
17229   /* For determining which partial specialization to use, only the
17230      innermost args are interesting.  */
17231   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17232     {
17233       outer_args = strip_innermost_template_args (args, 1);
17234       args = INNERMOST_TEMPLATE_ARGS (args);
17235     }
17236
17237   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17238     {
17239       tree partial_spec_args;
17240       tree spec_args;
17241       tree parms = TREE_VALUE (t);
17242
17243       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17244
17245       ++processing_template_decl;
17246
17247       if (outer_args)
17248         {
17249           int i;
17250
17251           /* Discard the outer levels of args, and then substitute in the
17252              template args from the enclosing class.  */
17253           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17254           partial_spec_args = tsubst_template_args
17255             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17256
17257           /* PARMS already refers to just the innermost parms, but the
17258              template parms in partial_spec_args had their levels lowered
17259              by tsubst, so we need to do the same for the parm list.  We
17260              can't just tsubst the TREE_VEC itself, as tsubst wants to
17261              treat a TREE_VEC as an argument vector.  */
17262           parms = copy_node (parms);
17263           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17264             TREE_VEC_ELT (parms, i) =
17265               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17266
17267         }
17268
17269       partial_spec_args =
17270           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17271                                  add_to_template_args (outer_args,
17272                                                        partial_spec_args),
17273                                  tmpl, tf_none,
17274                                  /*require_all_args=*/true,
17275                                  /*use_default_args=*/true);
17276
17277       --processing_template_decl;
17278
17279       if (partial_spec_args == error_mark_node)
17280         return error_mark_node;
17281
17282       spec_args = get_class_bindings (parms,
17283                                       partial_spec_args,
17284                                       args);
17285       if (spec_args)
17286         {
17287           if (outer_args)
17288             spec_args = add_to_template_args (outer_args, spec_args);
17289           list = tree_cons (spec_args, TREE_VALUE (t), list);
17290           TREE_TYPE (list) = TREE_TYPE (t);
17291         }
17292     }
17293
17294   if (! list)
17295     return NULL_TREE;
17296
17297   ambiguous_p = false;
17298   t = list;
17299   champ = t;
17300   t = TREE_CHAIN (t);
17301   for (; t; t = TREE_CHAIN (t))
17302     {
17303       fate = more_specialized_class (champ, t);
17304       if (fate == 1)
17305         ;
17306       else
17307         {
17308           if (fate == 0)
17309             {
17310               t = TREE_CHAIN (t);
17311               if (! t)
17312                 {
17313                   ambiguous_p = true;
17314                   break;
17315                 }
17316             }
17317           champ = t;
17318         }
17319     }
17320
17321   if (!ambiguous_p)
17322     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17323       {
17324         fate = more_specialized_class (champ, t);
17325         if (fate != 1)
17326           {
17327             ambiguous_p = true;
17328             break;
17329           }
17330       }
17331
17332   if (ambiguous_p)
17333     {
17334       const char *str;
17335       char *spaces = NULL;
17336       if (!(complain & tf_error))
17337         return error_mark_node;
17338       error ("ambiguous class template instantiation for %q#T", type);
17339       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17340       for (t = list; t; t = TREE_CHAIN (t))
17341         {
17342           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17343           spaces = spaces ? spaces : get_spaces (str);
17344         }
17345       free (spaces);
17346       return error_mark_node;
17347     }
17348
17349   return champ;
17350 }
17351
17352 /* Explicitly instantiate DECL.  */
17353
17354 void
17355 do_decl_instantiation (tree decl, tree storage)
17356 {
17357   tree result = NULL_TREE;
17358   int extern_p = 0;
17359
17360   if (!decl || decl == error_mark_node)
17361     /* An error occurred, for which grokdeclarator has already issued
17362        an appropriate message.  */
17363     return;
17364   else if (! DECL_LANG_SPECIFIC (decl))
17365     {
17366       error ("explicit instantiation of non-template %q#D", decl);
17367       return;
17368     }
17369   else if (TREE_CODE (decl) == VAR_DECL)
17370     {
17371       /* There is an asymmetry here in the way VAR_DECLs and
17372          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17373          the latter, the DECL we get back will be marked as a
17374          template instantiation, and the appropriate
17375          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17376          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17377          should handle VAR_DECLs as it currently handles
17378          FUNCTION_DECLs.  */
17379       if (!DECL_CLASS_SCOPE_P (decl))
17380         {
17381           error ("%qD is not a static data member of a class template", decl);
17382           return;
17383         }
17384       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17385       if (!result || TREE_CODE (result) != VAR_DECL)
17386         {
17387           error ("no matching template for %qD found", decl);
17388           return;
17389         }
17390       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17391         {
17392           error ("type %qT for explicit instantiation %qD does not match "
17393                  "declared type %qT", TREE_TYPE (result), decl,
17394                  TREE_TYPE (decl));
17395           return;
17396         }
17397     }
17398   else if (TREE_CODE (decl) != FUNCTION_DECL)
17399     {
17400       error ("explicit instantiation of %q#D", decl);
17401       return;
17402     }
17403   else
17404     result = decl;
17405
17406   /* Check for various error cases.  Note that if the explicit
17407      instantiation is valid the RESULT will currently be marked as an
17408      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17409      until we get here.  */
17410
17411   if (DECL_TEMPLATE_SPECIALIZATION (result))
17412     {
17413       /* DR 259 [temp.spec].
17414
17415          Both an explicit instantiation and a declaration of an explicit
17416          specialization shall not appear in a program unless the explicit
17417          instantiation follows a declaration of the explicit specialization.
17418
17419          For a given set of template parameters, if an explicit
17420          instantiation of a template appears after a declaration of an
17421          explicit specialization for that template, the explicit
17422          instantiation has no effect.  */
17423       return;
17424     }
17425   else if (DECL_EXPLICIT_INSTANTIATION (result))
17426     {
17427       /* [temp.spec]
17428
17429          No program shall explicitly instantiate any template more
17430          than once.
17431
17432          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17433          the first instantiation was `extern' and the second is not,
17434          and EXTERN_P for the opposite case.  */
17435       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17436         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17437       /* If an "extern" explicit instantiation follows an ordinary
17438          explicit instantiation, the template is instantiated.  */
17439       if (extern_p)
17440         return;
17441     }
17442   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17443     {
17444       error ("no matching template for %qD found", result);
17445       return;
17446     }
17447   else if (!DECL_TEMPLATE_INFO (result))
17448     {
17449       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17450       return;
17451     }
17452
17453   if (storage == NULL_TREE)
17454     ;
17455   else if (storage == ridpointers[(int) RID_EXTERN])
17456     {
17457       if (!in_system_header && (cxx_dialect == cxx98))
17458         pedwarn (input_location, OPT_pedantic, 
17459                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17460                  "instantiations");
17461       extern_p = 1;
17462     }
17463   else
17464     error ("storage class %qD applied to template instantiation", storage);
17465
17466   check_explicit_instantiation_namespace (result);
17467   mark_decl_instantiated (result, extern_p);
17468   if (! extern_p)
17469     instantiate_decl (result, /*defer_ok=*/1,
17470                       /*expl_inst_class_mem_p=*/false);
17471 }
17472
17473 static void
17474 mark_class_instantiated (tree t, int extern_p)
17475 {
17476   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17477   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17478   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17479   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17480   if (! extern_p)
17481     {
17482       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17483       rest_of_type_compilation (t, 1);
17484     }
17485 }
17486
17487 /* Called from do_type_instantiation through binding_table_foreach to
17488    do recursive instantiation for the type bound in ENTRY.  */
17489 static void
17490 bt_instantiate_type_proc (binding_entry entry, void *data)
17491 {
17492   tree storage = *(tree *) data;
17493
17494   if (MAYBE_CLASS_TYPE_P (entry->type)
17495       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17496     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17497 }
17498
17499 /* Called from do_type_instantiation to instantiate a member
17500    (a member function or a static member variable) of an
17501    explicitly instantiated class template.  */
17502 static void
17503 instantiate_class_member (tree decl, int extern_p)
17504 {
17505   mark_decl_instantiated (decl, extern_p);
17506   if (! extern_p)
17507     instantiate_decl (decl, /*defer_ok=*/1,
17508                       /*expl_inst_class_mem_p=*/true);
17509 }
17510
17511 /* Perform an explicit instantiation of template class T.  STORAGE, if
17512    non-null, is the RID for extern, inline or static.  COMPLAIN is
17513    nonzero if this is called from the parser, zero if called recursively,
17514    since the standard is unclear (as detailed below).  */
17515
17516 void
17517 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17518 {
17519   int extern_p = 0;
17520   int nomem_p = 0;
17521   int static_p = 0;
17522   int previous_instantiation_extern_p = 0;
17523
17524   if (TREE_CODE (t) == TYPE_DECL)
17525     t = TREE_TYPE (t);
17526
17527   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17528     {
17529       error ("explicit instantiation of non-template type %qT", t);
17530       return;
17531     }
17532
17533   complete_type (t);
17534
17535   if (!COMPLETE_TYPE_P (t))
17536     {
17537       if (complain & tf_error)
17538         error ("explicit instantiation of %q#T before definition of template",
17539                t);
17540       return;
17541     }
17542
17543   if (storage != NULL_TREE)
17544     {
17545       if (!in_system_header)
17546         {
17547           if (storage == ridpointers[(int) RID_EXTERN])
17548             {
17549               if (cxx_dialect == cxx98)
17550                 pedwarn (input_location, OPT_pedantic, 
17551                          "ISO C++ 1998 forbids the use of %<extern%> on "
17552                          "explicit instantiations");
17553             }
17554           else
17555             pedwarn (input_location, OPT_pedantic, 
17556                      "ISO C++ forbids the use of %qE"
17557                      " on explicit instantiations", storage);
17558         }
17559
17560       if (storage == ridpointers[(int) RID_INLINE])
17561         nomem_p = 1;
17562       else if (storage == ridpointers[(int) RID_EXTERN])
17563         extern_p = 1;
17564       else if (storage == ridpointers[(int) RID_STATIC])
17565         static_p = 1;
17566       else
17567         {
17568           error ("storage class %qD applied to template instantiation",
17569                  storage);
17570           extern_p = 0;
17571         }
17572     }
17573
17574   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17575     {
17576       /* DR 259 [temp.spec].
17577
17578          Both an explicit instantiation and a declaration of an explicit
17579          specialization shall not appear in a program unless the explicit
17580          instantiation follows a declaration of the explicit specialization.
17581
17582          For a given set of template parameters, if an explicit
17583          instantiation of a template appears after a declaration of an
17584          explicit specialization for that template, the explicit
17585          instantiation has no effect.  */
17586       return;
17587     }
17588   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17589     {
17590       /* [temp.spec]
17591
17592          No program shall explicitly instantiate any template more
17593          than once.
17594
17595          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17596          instantiation was `extern'.  If EXTERN_P then the second is.
17597          These cases are OK.  */
17598       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17599
17600       if (!previous_instantiation_extern_p && !extern_p
17601           && (complain & tf_error))
17602         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17603
17604       /* If we've already instantiated the template, just return now.  */
17605       if (!CLASSTYPE_INTERFACE_ONLY (t))
17606         return;
17607     }
17608
17609   check_explicit_instantiation_namespace (TYPE_NAME (t));
17610   mark_class_instantiated (t, extern_p);
17611
17612   if (nomem_p)
17613     return;
17614
17615   {
17616     tree tmp;
17617
17618     /* In contrast to implicit instantiation, where only the
17619        declarations, and not the definitions, of members are
17620        instantiated, we have here:
17621
17622          [temp.explicit]
17623
17624          The explicit instantiation of a class template specialization
17625          implies the instantiation of all of its members not
17626          previously explicitly specialized in the translation unit
17627          containing the explicit instantiation.
17628
17629        Of course, we can't instantiate member template classes, since
17630        we don't have any arguments for them.  Note that the standard
17631        is unclear on whether the instantiation of the members are
17632        *explicit* instantiations or not.  However, the most natural
17633        interpretation is that it should be an explicit instantiation.  */
17634
17635     if (! static_p)
17636       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17637         if (TREE_CODE (tmp) == FUNCTION_DECL
17638             && DECL_TEMPLATE_INSTANTIATION (tmp))
17639           instantiate_class_member (tmp, extern_p);
17640
17641     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17642       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17643         instantiate_class_member (tmp, extern_p);
17644
17645     if (CLASSTYPE_NESTED_UTDS (t))
17646       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17647                              bt_instantiate_type_proc, &storage);
17648   }
17649 }
17650
17651 /* Given a function DECL, which is a specialization of TMPL, modify
17652    DECL to be a re-instantiation of TMPL with the same template
17653    arguments.  TMPL should be the template into which tsubst'ing
17654    should occur for DECL, not the most general template.
17655
17656    One reason for doing this is a scenario like this:
17657
17658      template <class T>
17659      void f(const T&, int i);
17660
17661      void g() { f(3, 7); }
17662
17663      template <class T>
17664      void f(const T& t, const int i) { }
17665
17666    Note that when the template is first instantiated, with
17667    instantiate_template, the resulting DECL will have no name for the
17668    first parameter, and the wrong type for the second.  So, when we go
17669    to instantiate the DECL, we regenerate it.  */
17670
17671 static void
17672 regenerate_decl_from_template (tree decl, tree tmpl)
17673 {
17674   /* The arguments used to instantiate DECL, from the most general
17675      template.  */
17676   tree args;
17677   tree code_pattern;
17678
17679   args = DECL_TI_ARGS (decl);
17680   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17681
17682   /* Make sure that we can see identifiers, and compute access
17683      correctly.  */
17684   push_access_scope (decl);
17685
17686   if (TREE_CODE (decl) == FUNCTION_DECL)
17687     {
17688       tree decl_parm;
17689       tree pattern_parm;
17690       tree specs;
17691       int args_depth;
17692       int parms_depth;
17693
17694       args_depth = TMPL_ARGS_DEPTH (args);
17695       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17696       if (args_depth > parms_depth)
17697         args = get_innermost_template_args (args, parms_depth);
17698
17699       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17700                                               args, tf_error, NULL_TREE,
17701                                               /*defer_ok*/false);
17702       if (specs)
17703         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17704                                                     specs);
17705
17706       /* Merge parameter declarations.  */
17707       decl_parm = skip_artificial_parms_for (decl,
17708                                              DECL_ARGUMENTS (decl));
17709       pattern_parm
17710         = skip_artificial_parms_for (code_pattern,
17711                                      DECL_ARGUMENTS (code_pattern));
17712       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17713         {
17714           tree parm_type;
17715           tree attributes;
17716           
17717           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17718             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17719           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17720                               NULL_TREE);
17721           parm_type = type_decays_to (parm_type);
17722           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17723             TREE_TYPE (decl_parm) = parm_type;
17724           attributes = DECL_ATTRIBUTES (pattern_parm);
17725           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17726             {
17727               DECL_ATTRIBUTES (decl_parm) = attributes;
17728               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17729             }
17730           decl_parm = DECL_CHAIN (decl_parm);
17731           pattern_parm = DECL_CHAIN (pattern_parm);
17732         }
17733       /* Merge any parameters that match with the function parameter
17734          pack.  */
17735       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17736         {
17737           int i, len;
17738           tree expanded_types;
17739           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17740              the parameters in this function parameter pack.  */
17741           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17742                                                  args, tf_error, NULL_TREE);
17743           len = TREE_VEC_LENGTH (expanded_types);
17744           for (i = 0; i < len; i++)
17745             {
17746               tree parm_type;
17747               tree attributes;
17748           
17749               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17750                 /* Rename the parameter to include the index.  */
17751                 DECL_NAME (decl_parm) = 
17752                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17753               parm_type = TREE_VEC_ELT (expanded_types, i);
17754               parm_type = type_decays_to (parm_type);
17755               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17756                 TREE_TYPE (decl_parm) = parm_type;
17757               attributes = DECL_ATTRIBUTES (pattern_parm);
17758               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17759                 {
17760                   DECL_ATTRIBUTES (decl_parm) = attributes;
17761                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17762                 }
17763               decl_parm = DECL_CHAIN (decl_parm);
17764             }
17765         }
17766       /* Merge additional specifiers from the CODE_PATTERN.  */
17767       if (DECL_DECLARED_INLINE_P (code_pattern)
17768           && !DECL_DECLARED_INLINE_P (decl))
17769         DECL_DECLARED_INLINE_P (decl) = 1;
17770     }
17771   else if (TREE_CODE (decl) == VAR_DECL)
17772     {
17773       DECL_INITIAL (decl) =
17774         tsubst_expr (DECL_INITIAL (code_pattern), args,
17775                      tf_error, DECL_TI_TEMPLATE (decl),
17776                      /*integral_constant_expression_p=*/false);
17777       if (VAR_HAD_UNKNOWN_BOUND (decl))
17778         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17779                                    tf_error, DECL_TI_TEMPLATE (decl));
17780     }
17781   else
17782     gcc_unreachable ();
17783
17784   pop_access_scope (decl);
17785 }
17786
17787 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17788    substituted to get DECL.  */
17789
17790 tree
17791 template_for_substitution (tree decl)
17792 {
17793   tree tmpl = DECL_TI_TEMPLATE (decl);
17794
17795   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
17796      for the instantiation.  This is not always the most general
17797      template.  Consider, for example:
17798
17799         template <class T>
17800         struct S { template <class U> void f();
17801                    template <> void f<int>(); };
17802
17803      and an instantiation of S<double>::f<int>.  We want TD to be the
17804      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
17805   while (/* An instantiation cannot have a definition, so we need a
17806             more general template.  */
17807          DECL_TEMPLATE_INSTANTIATION (tmpl)
17808            /* We must also deal with friend templates.  Given:
17809
17810                 template <class T> struct S {
17811                   template <class U> friend void f() {};
17812                 };
17813
17814               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
17815               so far as the language is concerned, but that's still
17816               where we get the pattern for the instantiation from.  On
17817               other hand, if the definition comes outside the class, say:
17818
17819                 template <class T> struct S {
17820                   template <class U> friend void f();
17821                 };
17822                 template <class U> friend void f() {}
17823
17824               we don't need to look any further.  That's what the check for
17825               DECL_INITIAL is for.  */
17826           || (TREE_CODE (decl) == FUNCTION_DECL
17827               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17828               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17829     {
17830       /* The present template, TD, should not be a definition.  If it
17831          were a definition, we should be using it!  Note that we
17832          cannot restructure the loop to just keep going until we find
17833          a template with a definition, since that might go too far if
17834          a specialization was declared, but not defined.  */
17835       gcc_assert (TREE_CODE (decl) != VAR_DECL
17836                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17837
17838       /* Fetch the more general template.  */
17839       tmpl = DECL_TI_TEMPLATE (tmpl);
17840     }
17841
17842   return tmpl;
17843 }
17844
17845 /* Returns true if we need to instantiate this template instance even if we
17846    know we aren't going to emit it..  */
17847
17848 bool
17849 always_instantiate_p (tree decl)
17850 {
17851   /* We always instantiate inline functions so that we can inline them.  An
17852      explicit instantiation declaration prohibits implicit instantiation of
17853      non-inline functions.  With high levels of optimization, we would
17854      normally inline non-inline functions -- but we're not allowed to do
17855      that for "extern template" functions.  Therefore, we check
17856      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17857   return ((TREE_CODE (decl) == FUNCTION_DECL
17858            && DECL_DECLARED_INLINE_P (decl))
17859           /* And we need to instantiate static data members so that
17860              their initializers are available in integral constant
17861              expressions.  */
17862           || (TREE_CODE (decl) == VAR_DECL
17863               && decl_maybe_constant_var_p (decl)));
17864 }
17865
17866 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
17867    instantiate it now, modifying TREE_TYPE (fn).  */
17868
17869 void
17870 maybe_instantiate_noexcept (tree fn)
17871 {
17872   tree fntype, spec, noex, clone;
17873
17874   if (DECL_CLONED_FUNCTION_P (fn))
17875     fn = DECL_CLONED_FUNCTION (fn);
17876   fntype = TREE_TYPE (fn);
17877   spec = TYPE_RAISES_EXCEPTIONS (fntype);
17878
17879   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
17880     return;
17881
17882   noex = TREE_PURPOSE (spec);
17883
17884   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
17885     {
17886       push_tinst_level (fn);
17887       push_access_scope (fn);
17888       input_location = DECL_SOURCE_LOCATION (fn);
17889       noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
17890                                     DEFERRED_NOEXCEPT_ARGS (noex),
17891                                     tf_warning_or_error, fn, /*function_p=*/false,
17892                                     /*integral_constant_expression_p=*/true);
17893       pop_access_scope (fn);
17894       pop_tinst_level ();
17895       spec = build_noexcept_spec (noex, tf_warning_or_error);
17896       if (spec == error_mark_node)
17897         spec = noexcept_false_spec;
17898     }
17899   else
17900     {
17901       /* This is an implicitly declared function, so NOEX is a list of
17902          other functions to evaluate and merge.  */
17903       tree elt;
17904       spec = noexcept_true_spec;
17905       for (elt = noex; elt; elt = OVL_NEXT (elt))
17906         {
17907           tree fn = OVL_CURRENT (elt);
17908           tree subspec;
17909           maybe_instantiate_noexcept (fn);
17910           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
17911           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
17912         }
17913     }
17914
17915   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
17916
17917   FOR_EACH_CLONE (clone, fn)
17918     {
17919       if (TREE_TYPE (clone) == fntype)
17920         TREE_TYPE (clone) = TREE_TYPE (fn);
17921       else
17922         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
17923     }
17924 }
17925
17926 /* Produce the definition of D, a _DECL generated from a template.  If
17927    DEFER_OK is nonzero, then we don't have to actually do the
17928    instantiation now; we just have to do it sometime.  Normally it is
17929    an error if this is an explicit instantiation but D is undefined.
17930    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17931    explicitly instantiated class template.  */
17932
17933 tree
17934 instantiate_decl (tree d, int defer_ok,
17935                   bool expl_inst_class_mem_p)
17936 {
17937   tree tmpl = DECL_TI_TEMPLATE (d);
17938   tree gen_args;
17939   tree args;
17940   tree td;
17941   tree code_pattern;
17942   tree spec;
17943   tree gen_tmpl;
17944   bool pattern_defined;
17945   int need_push;
17946   location_t saved_loc = input_location;
17947   bool external_p;
17948
17949   /* This function should only be used to instantiate templates for
17950      functions and static member variables.  */
17951   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17952               || TREE_CODE (d) == VAR_DECL);
17953
17954   /* Variables are never deferred; if instantiation is required, they
17955      are instantiated right away.  That allows for better code in the
17956      case that an expression refers to the value of the variable --
17957      if the variable has a constant value the referring expression can
17958      take advantage of that fact.  */
17959   if (TREE_CODE (d) == VAR_DECL
17960       || DECL_DECLARED_CONSTEXPR_P (d))
17961     defer_ok = 0;
17962
17963   /* Don't instantiate cloned functions.  Instead, instantiate the
17964      functions they cloned.  */
17965   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17966     d = DECL_CLONED_FUNCTION (d);
17967
17968   if (DECL_TEMPLATE_INSTANTIATED (d)
17969       || DECL_TEMPLATE_SPECIALIZATION (d))
17970     /* D has already been instantiated or explicitly specialized, so
17971        there's nothing for us to do here.
17972
17973        It might seem reasonable to check whether or not D is an explicit
17974        instantiation, and, if so, stop here.  But when an explicit
17975        instantiation is deferred until the end of the compilation,
17976        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17977        the instantiation.  */
17978     return d;
17979
17980   /* Check to see whether we know that this template will be
17981      instantiated in some other file, as with "extern template"
17982      extension.  */
17983   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17984
17985   /* In general, we do not instantiate such templates.  */
17986   if (external_p && !always_instantiate_p (d))
17987     return d;
17988
17989   gen_tmpl = most_general_template (tmpl);
17990   gen_args = DECL_TI_ARGS (d);
17991
17992   if (tmpl != gen_tmpl)
17993     /* We should already have the extra args.  */
17994     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17995                 == TMPL_ARGS_DEPTH (gen_args));
17996   /* And what's in the hash table should match D.  */
17997   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17998               || spec == NULL_TREE);
17999
18000   /* This needs to happen before any tsubsting.  */
18001   if (! push_tinst_level (d))
18002     return d;
18003
18004   timevar_push (TV_TEMPLATE_INST);
18005
18006   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18007      for the instantiation.  */
18008   td = template_for_substitution (d);
18009   code_pattern = DECL_TEMPLATE_RESULT (td);
18010
18011   /* We should never be trying to instantiate a member of a class
18012      template or partial specialization.  */
18013   gcc_assert (d != code_pattern);
18014
18015   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18016       || DECL_TEMPLATE_SPECIALIZATION (td))
18017     /* In the case of a friend template whose definition is provided
18018        outside the class, we may have too many arguments.  Drop the
18019        ones we don't need.  The same is true for specializations.  */
18020     args = get_innermost_template_args
18021       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18022   else
18023     args = gen_args;
18024
18025   if (TREE_CODE (d) == FUNCTION_DECL)
18026     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18027                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18028   else
18029     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18030
18031   /* We may be in the middle of deferred access check.  Disable it now.  */
18032   push_deferring_access_checks (dk_no_deferred);
18033
18034   /* Unless an explicit instantiation directive has already determined
18035      the linkage of D, remember that a definition is available for
18036      this entity.  */
18037   if (pattern_defined
18038       && !DECL_INTERFACE_KNOWN (d)
18039       && !DECL_NOT_REALLY_EXTERN (d))
18040     mark_definable (d);
18041
18042   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18043   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18044   input_location = DECL_SOURCE_LOCATION (d);
18045
18046   /* If D is a member of an explicitly instantiated class template,
18047      and no definition is available, treat it like an implicit
18048      instantiation.  */
18049   if (!pattern_defined && expl_inst_class_mem_p
18050       && DECL_EXPLICIT_INSTANTIATION (d))
18051     {
18052       /* Leave linkage flags alone on instantiations with anonymous
18053          visibility.  */
18054       if (TREE_PUBLIC (d))
18055         {
18056           DECL_NOT_REALLY_EXTERN (d) = 0;
18057           DECL_INTERFACE_KNOWN (d) = 0;
18058         }
18059       SET_DECL_IMPLICIT_INSTANTIATION (d);
18060     }
18061
18062   if (TREE_CODE (d) == FUNCTION_DECL)
18063     maybe_instantiate_noexcept (d);
18064
18065   /* Recheck the substitutions to obtain any warning messages
18066      about ignoring cv qualifiers.  Don't do this for artificial decls,
18067      as it breaks the context-sensitive substitution for lambda op(). */
18068   if (!defer_ok && !DECL_ARTIFICIAL (d))
18069     {
18070       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18071       tree type = TREE_TYPE (gen);
18072
18073       /* Make sure that we can see identifiers, and compute access
18074          correctly.  D is already the target FUNCTION_DECL with the
18075          right context.  */
18076       push_access_scope (d);
18077
18078       if (TREE_CODE (gen) == FUNCTION_DECL)
18079         {
18080           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18081           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18082                                           d, /*defer_ok*/true);
18083           /* Don't simply tsubst the function type, as that will give
18084              duplicate warnings about poor parameter qualifications.
18085              The function arguments are the same as the decl_arguments
18086              without the top level cv qualifiers.  */
18087           type = TREE_TYPE (type);
18088         }
18089       tsubst (type, gen_args, tf_warning_or_error, d);
18090
18091       pop_access_scope (d);
18092     }
18093
18094   /* Defer all other templates, unless we have been explicitly
18095      forbidden from doing so.  */
18096   if (/* If there is no definition, we cannot instantiate the
18097          template.  */
18098       ! pattern_defined
18099       /* If it's OK to postpone instantiation, do so.  */
18100       || defer_ok
18101       /* If this is a static data member that will be defined
18102          elsewhere, we don't want to instantiate the entire data
18103          member, but we do want to instantiate the initializer so that
18104          we can substitute that elsewhere.  */
18105       || (external_p && TREE_CODE (d) == VAR_DECL))
18106     {
18107       /* The definition of the static data member is now required so
18108          we must substitute the initializer.  */
18109       if (TREE_CODE (d) == VAR_DECL
18110           && !DECL_INITIAL (d)
18111           && DECL_INITIAL (code_pattern))
18112         {
18113           tree ns;
18114           tree init;
18115           bool const_init = false;
18116
18117           ns = decl_namespace_context (d);
18118           push_nested_namespace (ns);
18119           push_nested_class (DECL_CONTEXT (d));
18120           init = tsubst_expr (DECL_INITIAL (code_pattern),
18121                               args,
18122                               tf_warning_or_error, NULL_TREE,
18123                               /*integral_constant_expression_p=*/false);
18124           /* Make sure the initializer is still constant, in case of
18125              circular dependency (template/instantiate6.C). */
18126           const_init
18127             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18128           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18129                           /*asmspec_tree=*/NULL_TREE,
18130                           LOOKUP_ONLYCONVERTING);
18131           pop_nested_class ();
18132           pop_nested_namespace (ns);
18133         }
18134
18135       /* We restore the source position here because it's used by
18136          add_pending_template.  */
18137       input_location = saved_loc;
18138
18139       if (at_eof && !pattern_defined
18140           && DECL_EXPLICIT_INSTANTIATION (d)
18141           && DECL_NOT_REALLY_EXTERN (d))
18142         /* [temp.explicit]
18143
18144            The definition of a non-exported function template, a
18145            non-exported member function template, or a non-exported
18146            member function or static data member of a class template
18147            shall be present in every translation unit in which it is
18148            explicitly instantiated.  */
18149         permerror (input_location,  "explicit instantiation of %qD "
18150                    "but no definition available", d);
18151
18152       /* If we're in unevaluated context, we just wanted to get the
18153          constant value; this isn't an odr use, so don't queue
18154          a full instantiation.  */
18155       if (cp_unevaluated_operand != 0)
18156         goto out;
18157       /* ??? Historically, we have instantiated inline functions, even
18158          when marked as "extern template".  */
18159       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18160         add_pending_template (d);
18161       goto out;
18162     }
18163   /* Tell the repository that D is available in this translation unit
18164      -- and see if it is supposed to be instantiated here.  */
18165   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18166     {
18167       /* In a PCH file, despite the fact that the repository hasn't
18168          requested instantiation in the PCH it is still possible that
18169          an instantiation will be required in a file that includes the
18170          PCH.  */
18171       if (pch_file)
18172         add_pending_template (d);
18173       /* Instantiate inline functions so that the inliner can do its
18174          job, even though we'll not be emitting a copy of this
18175          function.  */
18176       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18177         goto out;
18178     }
18179
18180   need_push = !cfun || !global_bindings_p ();
18181   if (need_push)
18182     push_to_top_level ();
18183
18184   /* Mark D as instantiated so that recursive calls to
18185      instantiate_decl do not try to instantiate it again.  */
18186   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18187
18188   /* Regenerate the declaration in case the template has been modified
18189      by a subsequent redeclaration.  */
18190   regenerate_decl_from_template (d, td);
18191
18192   /* We already set the file and line above.  Reset them now in case
18193      they changed as a result of calling regenerate_decl_from_template.  */
18194   input_location = DECL_SOURCE_LOCATION (d);
18195
18196   if (TREE_CODE (d) == VAR_DECL)
18197     {
18198       tree init;
18199       bool const_init = false;
18200
18201       /* Clear out DECL_RTL; whatever was there before may not be right
18202          since we've reset the type of the declaration.  */
18203       SET_DECL_RTL (d, NULL);
18204       DECL_IN_AGGR_P (d) = 0;
18205
18206       /* The initializer is placed in DECL_INITIAL by
18207          regenerate_decl_from_template so we don't need to
18208          push/pop_access_scope again here.  Pull it out so that
18209          cp_finish_decl can process it.  */
18210       init = DECL_INITIAL (d);
18211       DECL_INITIAL (d) = NULL_TREE;
18212       DECL_INITIALIZED_P (d) = 0;
18213
18214       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18215          initializer.  That function will defer actual emission until
18216          we have a chance to determine linkage.  */
18217       DECL_EXTERNAL (d) = 0;
18218
18219       /* Enter the scope of D so that access-checking works correctly.  */
18220       push_nested_class (DECL_CONTEXT (d));
18221       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18222       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18223       pop_nested_class ();
18224     }
18225   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18226     synthesize_method (d);
18227   else if (TREE_CODE (d) == FUNCTION_DECL)
18228     {
18229       htab_t saved_local_specializations;
18230       tree subst_decl;
18231       tree tmpl_parm;
18232       tree spec_parm;
18233
18234       /* Save away the current list, in case we are instantiating one
18235          template from within the body of another.  */
18236       saved_local_specializations = local_specializations;
18237
18238       /* Set up the list of local specializations.  */
18239       local_specializations = htab_create (37,
18240                                            hash_local_specialization,
18241                                            eq_local_specializations,
18242                                            NULL);
18243
18244       /* Set up context.  */
18245       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18246
18247       /* Create substitution entries for the parameters.  */
18248       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18249       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18250       spec_parm = DECL_ARGUMENTS (d);
18251       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18252         {
18253           register_local_specialization (spec_parm, tmpl_parm);
18254           spec_parm = skip_artificial_parms_for (d, spec_parm);
18255           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18256         }
18257       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18258         {
18259           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18260             {
18261               register_local_specialization (spec_parm, tmpl_parm);
18262               spec_parm = DECL_CHAIN (spec_parm);
18263             }
18264           else
18265             {
18266               /* Register the (value) argument pack as a specialization of
18267                  TMPL_PARM, then move on.  */
18268               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18269               register_local_specialization (argpack, tmpl_parm);
18270             }
18271         }
18272       gcc_assert (!spec_parm);
18273
18274       /* Substitute into the body of the function.  */
18275       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18276                    tf_warning_or_error, tmpl,
18277                    /*integral_constant_expression_p=*/false);
18278
18279       /* Set the current input_location to the end of the function
18280          so that finish_function knows where we are.  */
18281       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18282
18283       /* We don't need the local specializations any more.  */
18284       htab_delete (local_specializations);
18285       local_specializations = saved_local_specializations;
18286
18287       /* Finish the function.  */
18288       d = finish_function (0);
18289       expand_or_defer_fn (d);
18290     }
18291
18292   /* We're not deferring instantiation any more.  */
18293   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18294
18295   if (need_push)
18296     pop_from_top_level ();
18297
18298 out:
18299   input_location = saved_loc;
18300   pop_deferring_access_checks ();
18301   pop_tinst_level ();
18302
18303   timevar_pop (TV_TEMPLATE_INST);
18304
18305   return d;
18306 }
18307
18308 /* Run through the list of templates that we wish we could
18309    instantiate, and instantiate any we can.  RETRIES is the
18310    number of times we retry pending template instantiation.  */
18311
18312 void
18313 instantiate_pending_templates (int retries)
18314 {
18315   int reconsider;
18316   location_t saved_loc = input_location;
18317
18318   /* Instantiating templates may trigger vtable generation.  This in turn
18319      may require further template instantiations.  We place a limit here
18320      to avoid infinite loop.  */
18321   if (pending_templates && retries >= max_tinst_depth)
18322     {
18323       tree decl = pending_templates->tinst->decl;
18324
18325       error ("template instantiation depth exceeds maximum of %d"
18326              " instantiating %q+D, possibly from virtual table generation"
18327              " (use -ftemplate-depth= to increase the maximum)",
18328              max_tinst_depth, decl);
18329       if (TREE_CODE (decl) == FUNCTION_DECL)
18330         /* Pretend that we defined it.  */
18331         DECL_INITIAL (decl) = error_mark_node;
18332       return;
18333     }
18334
18335   do
18336     {
18337       struct pending_template **t = &pending_templates;
18338       struct pending_template *last = NULL;
18339       reconsider = 0;
18340       while (*t)
18341         {
18342           tree instantiation = reopen_tinst_level ((*t)->tinst);
18343           bool complete = false;
18344
18345           if (TYPE_P (instantiation))
18346             {
18347               tree fn;
18348
18349               if (!COMPLETE_TYPE_P (instantiation))
18350                 {
18351                   instantiate_class_template (instantiation);
18352                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18353                     for (fn = TYPE_METHODS (instantiation);
18354                          fn;
18355                          fn = TREE_CHAIN (fn))
18356                       if (! DECL_ARTIFICIAL (fn))
18357                         instantiate_decl (fn,
18358                                           /*defer_ok=*/0,
18359                                           /*expl_inst_class_mem_p=*/false);
18360                   if (COMPLETE_TYPE_P (instantiation))
18361                     reconsider = 1;
18362                 }
18363
18364               complete = COMPLETE_TYPE_P (instantiation);
18365             }
18366           else
18367             {
18368               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18369                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18370                 {
18371                   instantiation
18372                     = instantiate_decl (instantiation,
18373                                         /*defer_ok=*/0,
18374                                         /*expl_inst_class_mem_p=*/false);
18375                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18376                     reconsider = 1;
18377                 }
18378
18379               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18380                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18381             }
18382
18383           if (complete)
18384             /* If INSTANTIATION has been instantiated, then we don't
18385                need to consider it again in the future.  */
18386             *t = (*t)->next;
18387           else
18388             {
18389               last = *t;
18390               t = &(*t)->next;
18391             }
18392           tinst_depth = 0;
18393           current_tinst_level = NULL;
18394         }
18395       last_pending_template = last;
18396     }
18397   while (reconsider);
18398
18399   input_location = saved_loc;
18400 }
18401
18402 /* Substitute ARGVEC into T, which is a list of initializers for
18403    either base class or a non-static data member.  The TREE_PURPOSEs
18404    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18405    instantiate_decl.  */
18406
18407 static tree
18408 tsubst_initializer_list (tree t, tree argvec)
18409 {
18410   tree inits = NULL_TREE;
18411
18412   for (; t; t = TREE_CHAIN (t))
18413     {
18414       tree decl;
18415       tree init;
18416       tree expanded_bases = NULL_TREE;
18417       tree expanded_arguments = NULL_TREE;
18418       int i, len = 1;
18419
18420       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18421         {
18422           tree expr;
18423           tree arg;
18424
18425           /* Expand the base class expansion type into separate base
18426              classes.  */
18427           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18428                                                  tf_warning_or_error,
18429                                                  NULL_TREE);
18430           if (expanded_bases == error_mark_node)
18431             continue;
18432           
18433           /* We'll be building separate TREE_LISTs of arguments for
18434              each base.  */
18435           len = TREE_VEC_LENGTH (expanded_bases);
18436           expanded_arguments = make_tree_vec (len);
18437           for (i = 0; i < len; i++)
18438             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18439
18440           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18441              expand each argument in the TREE_VALUE of t.  */
18442           expr = make_node (EXPR_PACK_EXPANSION);
18443           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18444             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18445
18446           if (TREE_VALUE (t) == void_type_node)
18447             /* VOID_TYPE_NODE is used to indicate
18448                value-initialization.  */
18449             {
18450               for (i = 0; i < len; i++)
18451                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18452             }
18453           else
18454             {
18455               /* Substitute parameter packs into each argument in the
18456                  TREE_LIST.  */
18457               in_base_initializer = 1;
18458               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18459                 {
18460                   tree expanded_exprs;
18461
18462                   /* Expand the argument.  */
18463                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18464                   expanded_exprs 
18465                     = tsubst_pack_expansion (expr, argvec,
18466                                              tf_warning_or_error,
18467                                              NULL_TREE);
18468                   if (expanded_exprs == error_mark_node)
18469                     continue;
18470
18471                   /* Prepend each of the expanded expressions to the
18472                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18473                   for (i = 0; i < len; i++)
18474                     {
18475                       TREE_VEC_ELT (expanded_arguments, i) = 
18476                         tree_cons (NULL_TREE, 
18477                                    TREE_VEC_ELT (expanded_exprs, i),
18478                                    TREE_VEC_ELT (expanded_arguments, i));
18479                     }
18480                 }
18481               in_base_initializer = 0;
18482
18483               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18484                  since we built them backwards.  */
18485               for (i = 0; i < len; i++)
18486                 {
18487                   TREE_VEC_ELT (expanded_arguments, i) = 
18488                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18489                 }
18490             }
18491         }
18492
18493       for (i = 0; i < len; ++i)
18494         {
18495           if (expanded_bases)
18496             {
18497               decl = TREE_VEC_ELT (expanded_bases, i);
18498               decl = expand_member_init (decl);
18499               init = TREE_VEC_ELT (expanded_arguments, i);
18500             }
18501           else
18502             {
18503               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18504                                   tf_warning_or_error, NULL_TREE);
18505
18506               decl = expand_member_init (decl);
18507               if (decl && !DECL_P (decl))
18508                 in_base_initializer = 1;
18509
18510               init = TREE_VALUE (t);
18511               if (init != void_type_node)
18512                 init = tsubst_expr (init, argvec,
18513                                     tf_warning_or_error, NULL_TREE,
18514                                     /*integral_constant_expression_p=*/false);
18515               in_base_initializer = 0;
18516             }
18517
18518           if (decl)
18519             {
18520               init = build_tree_list (decl, init);
18521               TREE_CHAIN (init) = inits;
18522               inits = init;
18523             }
18524         }
18525     }
18526   return inits;
18527 }
18528
18529 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18530
18531 static void
18532 set_current_access_from_decl (tree decl)
18533 {
18534   if (TREE_PRIVATE (decl))
18535     current_access_specifier = access_private_node;
18536   else if (TREE_PROTECTED (decl))
18537     current_access_specifier = access_protected_node;
18538   else
18539     current_access_specifier = access_public_node;
18540 }
18541
18542 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18543    is the instantiation (which should have been created with
18544    start_enum) and ARGS are the template arguments to use.  */
18545
18546 static void
18547 tsubst_enum (tree tag, tree newtag, tree args)
18548 {
18549   tree e;
18550
18551   if (SCOPED_ENUM_P (newtag))
18552     begin_scope (sk_scoped_enum, newtag);
18553
18554   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18555     {
18556       tree value;
18557       tree decl;
18558
18559       decl = TREE_VALUE (e);
18560       /* Note that in a template enum, the TREE_VALUE is the
18561          CONST_DECL, not the corresponding INTEGER_CST.  */
18562       value = tsubst_expr (DECL_INITIAL (decl),
18563                            args, tf_warning_or_error, NULL_TREE,
18564                            /*integral_constant_expression_p=*/true);
18565
18566       /* Give this enumeration constant the correct access.  */
18567       set_current_access_from_decl (decl);
18568
18569       /* Actually build the enumerator itself.  */
18570       build_enumerator
18571         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18572     }
18573
18574   if (SCOPED_ENUM_P (newtag))
18575     finish_scope ();
18576
18577   finish_enum_value_list (newtag);
18578   finish_enum (newtag);
18579
18580   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18581     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18582 }
18583
18584 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18585    its type -- but without substituting the innermost set of template
18586    arguments.  So, innermost set of template parameters will appear in
18587    the type.  */
18588
18589 tree
18590 get_mostly_instantiated_function_type (tree decl)
18591 {
18592   tree fn_type;
18593   tree tmpl;
18594   tree targs;
18595   tree tparms;
18596   int parm_depth;
18597
18598   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18599   targs = DECL_TI_ARGS (decl);
18600   tparms = DECL_TEMPLATE_PARMS (tmpl);
18601   parm_depth = TMPL_PARMS_DEPTH (tparms);
18602
18603   /* There should be as many levels of arguments as there are levels
18604      of parameters.  */
18605   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18606
18607   fn_type = TREE_TYPE (tmpl);
18608
18609   if (parm_depth == 1)
18610     /* No substitution is necessary.  */
18611     ;
18612   else
18613     {
18614       int i;
18615       tree partial_args;
18616
18617       /* Replace the innermost level of the TARGS with NULL_TREEs to
18618          let tsubst know not to substitute for those parameters.  */
18619       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18620       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18621         SET_TMPL_ARGS_LEVEL (partial_args, i,
18622                              TMPL_ARGS_LEVEL (targs, i));
18623       SET_TMPL_ARGS_LEVEL (partial_args,
18624                            TMPL_ARGS_DEPTH (targs),
18625                            make_tree_vec (DECL_NTPARMS (tmpl)));
18626
18627       /* Make sure that we can see identifiers, and compute access
18628          correctly.  */
18629       push_access_scope (decl);
18630
18631       ++processing_template_decl;
18632       /* Now, do the (partial) substitution to figure out the
18633          appropriate function type.  */
18634       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18635       --processing_template_decl;
18636
18637       /* Substitute into the template parameters to obtain the real
18638          innermost set of parameters.  This step is important if the
18639          innermost set of template parameters contains value
18640          parameters whose types depend on outer template parameters.  */
18641       TREE_VEC_LENGTH (partial_args)--;
18642       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18643
18644       pop_access_scope (decl);
18645     }
18646
18647   return fn_type;
18648 }
18649
18650 /* Return truthvalue if we're processing a template different from
18651    the last one involved in diagnostics.  */
18652 int
18653 problematic_instantiation_changed (void)
18654 {
18655   return current_tinst_level != last_error_tinst_level;
18656 }
18657
18658 /* Remember current template involved in diagnostics.  */
18659 void
18660 record_last_problematic_instantiation (void)
18661 {
18662   last_error_tinst_level = current_tinst_level;
18663 }
18664
18665 struct tinst_level *
18666 current_instantiation (void)
18667 {
18668   return current_tinst_level;
18669 }
18670
18671 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18672    type. Return zero for ok, nonzero for disallowed. Issue error and
18673    warning messages under control of COMPLAIN.  */
18674
18675 static int
18676 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18677 {
18678   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18679     return 0;
18680   else if (POINTER_TYPE_P (type))
18681     return 0;
18682   else if (TYPE_PTR_TO_MEMBER_P (type))
18683     return 0;
18684   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18685     return 0;
18686   else if (TREE_CODE (type) == TYPENAME_TYPE)
18687     return 0;
18688   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18689     return 0;
18690
18691   if (complain & tf_error)
18692     error ("%q#T is not a valid type for a template constant parameter", type);
18693   return 1;
18694 }
18695
18696 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18697    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18698
18699 static bool
18700 dependent_type_p_r (tree type)
18701 {
18702   tree scope;
18703
18704   /* [temp.dep.type]
18705
18706      A type is dependent if it is:
18707
18708      -- a template parameter. Template template parameters are types
18709         for us (since TYPE_P holds true for them) so we handle
18710         them here.  */
18711   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18712       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18713     return true;
18714   /* -- a qualified-id with a nested-name-specifier which contains a
18715         class-name that names a dependent type or whose unqualified-id
18716         names a dependent type.  */
18717   if (TREE_CODE (type) == TYPENAME_TYPE)
18718     return true;
18719   /* -- a cv-qualified type where the cv-unqualified type is
18720         dependent.  */
18721   type = TYPE_MAIN_VARIANT (type);
18722   /* -- a compound type constructed from any dependent type.  */
18723   if (TYPE_PTR_TO_MEMBER_P (type))
18724     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18725             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18726                                            (type)));
18727   else if (TREE_CODE (type) == POINTER_TYPE
18728            || TREE_CODE (type) == REFERENCE_TYPE)
18729     return dependent_type_p (TREE_TYPE (type));
18730   else if (TREE_CODE (type) == FUNCTION_TYPE
18731            || TREE_CODE (type) == METHOD_TYPE)
18732     {
18733       tree arg_type;
18734
18735       if (dependent_type_p (TREE_TYPE (type)))
18736         return true;
18737       for (arg_type = TYPE_ARG_TYPES (type);
18738            arg_type;
18739            arg_type = TREE_CHAIN (arg_type))
18740         if (dependent_type_p (TREE_VALUE (arg_type)))
18741           return true;
18742       return false;
18743     }
18744   /* -- an array type constructed from any dependent type or whose
18745         size is specified by a constant expression that is
18746         value-dependent.
18747
18748         We checked for type- and value-dependence of the bounds in
18749         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18750   if (TREE_CODE (type) == ARRAY_TYPE)
18751     {
18752       if (TYPE_DOMAIN (type)
18753           && dependent_type_p (TYPE_DOMAIN (type)))
18754         return true;
18755       return dependent_type_p (TREE_TYPE (type));
18756     }
18757
18758   /* -- a template-id in which either the template name is a template
18759      parameter ...  */
18760   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18761     return true;
18762   /* ... or any of the template arguments is a dependent type or
18763         an expression that is type-dependent or value-dependent.  */
18764   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
18765            && (any_dependent_template_arguments_p
18766                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
18767     return true;
18768
18769   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
18770      dependent; if the argument of the `typeof' expression is not
18771      type-dependent, then it should already been have resolved.  */
18772   if (TREE_CODE (type) == TYPEOF_TYPE
18773       || TREE_CODE (type) == DECLTYPE_TYPE
18774       || TREE_CODE (type) == UNDERLYING_TYPE)
18775     return true;
18776
18777   /* A template argument pack is dependent if any of its packed
18778      arguments are.  */
18779   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
18780     {
18781       tree args = ARGUMENT_PACK_ARGS (type);
18782       int i, len = TREE_VEC_LENGTH (args);
18783       for (i = 0; i < len; ++i)
18784         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18785           return true;
18786     }
18787
18788   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
18789      be template parameters.  */
18790   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
18791     return true;
18792
18793   /* The standard does not specifically mention types that are local
18794      to template functions or local classes, but they should be
18795      considered dependent too.  For example:
18796
18797        template <int I> void f() {
18798          enum E { a = I };
18799          S<sizeof (E)> s;
18800        }
18801
18802      The size of `E' cannot be known until the value of `I' has been
18803      determined.  Therefore, `E' must be considered dependent.  */
18804   scope = TYPE_CONTEXT (type);
18805   if (scope && TYPE_P (scope))
18806     return dependent_type_p (scope);
18807   /* Don't use type_dependent_expression_p here, as it can lead
18808      to infinite recursion trying to determine whether a lambda
18809      nested in a lambda is dependent (c++/47687).  */
18810   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
18811            && DECL_LANG_SPECIFIC (scope)
18812            && DECL_TEMPLATE_INFO (scope)
18813            && (any_dependent_template_arguments_p
18814                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
18815     return true;
18816
18817   /* Other types are non-dependent.  */
18818   return false;
18819 }
18820
18821 /* Returns TRUE if TYPE is dependent, in the sense of
18822    [temp.dep.type].  Note that a NULL type is considered dependent.  */
18823
18824 bool
18825 dependent_type_p (tree type)
18826 {
18827   /* If there are no template parameters in scope, then there can't be
18828      any dependent types.  */
18829   if (!processing_template_decl)
18830     {
18831       /* If we are not processing a template, then nobody should be
18832          providing us with a dependent type.  */
18833       gcc_assert (type);
18834       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
18835       return false;
18836     }
18837
18838   /* If the type is NULL, we have not computed a type for the entity
18839      in question; in that case, the type is dependent.  */
18840   if (!type)
18841     return true;
18842
18843   /* Erroneous types can be considered non-dependent.  */
18844   if (type == error_mark_node)
18845     return false;
18846
18847   /* If we have not already computed the appropriate value for TYPE,
18848      do so now.  */
18849   if (!TYPE_DEPENDENT_P_VALID (type))
18850     {
18851       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
18852       TYPE_DEPENDENT_P_VALID (type) = 1;
18853     }
18854
18855   return TYPE_DEPENDENT_P (type);
18856 }
18857
18858 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
18859    lookup.  In other words, a dependent type that is not the current
18860    instantiation.  */
18861
18862 bool
18863 dependent_scope_p (tree scope)
18864 {
18865   return (scope && TYPE_P (scope) && dependent_type_p (scope)
18866           && !currently_open_class (scope));
18867 }
18868
18869 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
18870    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
18871    expression.  */
18872
18873 /* Note that this predicate is not appropriate for general expressions;
18874    only constant expressions (that satisfy potential_constant_expression)
18875    can be tested for value dependence.
18876
18877    We should really also have a predicate for "instantiation-dependent".
18878
18879    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
18880      (what about instantiation-dependent constant-expressions?)
18881    is_late_template_attribute: defer if instantiation-dependent.
18882    compute_array_index_type: proceed if constant and not t- or v-dependent
18883      if instantiation-dependent, need to remember full expression
18884    uses_template_parms: FIXME - need to audit callers
18885    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
18886    dependent_type_p [array_type]: dependent if index type is dependent
18887      (or non-constant?)
18888    static_assert - instantiation-dependent */
18889
18890 bool
18891 value_dependent_expression_p (tree expression)
18892 {
18893   if (!processing_template_decl)
18894     return false;
18895
18896   /* A name declared with a dependent type.  */
18897   if (DECL_P (expression) && type_dependent_expression_p (expression))
18898     return true;
18899
18900   switch (TREE_CODE (expression))
18901     {
18902     case IDENTIFIER_NODE:
18903       /* A name that has not been looked up -- must be dependent.  */
18904       return true;
18905
18906     case TEMPLATE_PARM_INDEX:
18907       /* A non-type template parm.  */
18908       return true;
18909
18910     case CONST_DECL:
18911       /* A non-type template parm.  */
18912       if (DECL_TEMPLATE_PARM_P (expression))
18913         return true;
18914       return value_dependent_expression_p (DECL_INITIAL (expression));
18915
18916     case VAR_DECL:
18917        /* A constant with literal type and is initialized
18918           with an expression that is value-dependent.  */
18919       if (DECL_INITIAL (expression)
18920           && decl_constant_var_p (expression)
18921           && value_dependent_expression_p (DECL_INITIAL (expression)))
18922         return true;
18923       return false;
18924
18925     case DYNAMIC_CAST_EXPR:
18926     case STATIC_CAST_EXPR:
18927     case CONST_CAST_EXPR:
18928     case REINTERPRET_CAST_EXPR:
18929     case CAST_EXPR:
18930       /* These expressions are value-dependent if the type to which
18931          the cast occurs is dependent or the expression being casted
18932          is value-dependent.  */
18933       {
18934         tree type = TREE_TYPE (expression);
18935
18936         if (dependent_type_p (type))
18937           return true;
18938
18939         /* A functional cast has a list of operands.  */
18940         expression = TREE_OPERAND (expression, 0);
18941         if (!expression)
18942           {
18943             /* If there are no operands, it must be an expression such
18944                as "int()". This should not happen for aggregate types
18945                because it would form non-constant expressions.  */
18946             gcc_assert (cxx_dialect >= cxx0x
18947                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18948
18949             return false;
18950           }
18951
18952         if (TREE_CODE (expression) == TREE_LIST)
18953           return any_value_dependent_elements_p (expression);
18954
18955         return value_dependent_expression_p (expression);
18956       }
18957
18958     case SIZEOF_EXPR:
18959     case ALIGNOF_EXPR:
18960     case TYPEID_EXPR:
18961       /* A `sizeof' expression is value-dependent if the operand is
18962          type-dependent or is a pack expansion.  */
18963       expression = TREE_OPERAND (expression, 0);
18964       if (PACK_EXPANSION_P (expression))
18965         return true;
18966       else if (TYPE_P (expression))
18967         return dependent_type_p (expression);
18968       return type_dependent_expression_p (expression);
18969
18970     case AT_ENCODE_EXPR:
18971       /* An 'encode' expression is value-dependent if the operand is
18972          type-dependent.  */
18973       expression = TREE_OPERAND (expression, 0);
18974       return dependent_type_p (expression);
18975
18976     case NOEXCEPT_EXPR:
18977       expression = TREE_OPERAND (expression, 0);
18978       return type_dependent_expression_p (expression);
18979
18980     case SCOPE_REF:
18981       {
18982         tree name = TREE_OPERAND (expression, 1);
18983         return value_dependent_expression_p (name);
18984       }
18985
18986     case COMPONENT_REF:
18987       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18988               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18989
18990     case NONTYPE_ARGUMENT_PACK:
18991       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18992          is value-dependent.  */
18993       {
18994         tree values = ARGUMENT_PACK_ARGS (expression);
18995         int i, len = TREE_VEC_LENGTH (values);
18996         
18997         for (i = 0; i < len; ++i)
18998           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18999             return true;
19000         
19001         return false;
19002       }
19003
19004     case TRAIT_EXPR:
19005       {
19006         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19007         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19008                 || (type2 ? dependent_type_p (type2) : false));
19009       }
19010
19011     case MODOP_EXPR:
19012       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19013               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19014
19015     case ARRAY_REF:
19016       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19017               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19018
19019     case ADDR_EXPR:
19020       {
19021         tree op = TREE_OPERAND (expression, 0);
19022         return (value_dependent_expression_p (op)
19023                 || has_value_dependent_address (op));
19024       }
19025
19026     case CALL_EXPR:
19027       {
19028         tree fn = get_callee_fndecl (expression);
19029         int i, nargs;
19030         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19031           return true;
19032         nargs = call_expr_nargs (expression);
19033         for (i = 0; i < nargs; ++i)
19034           {
19035             tree op = CALL_EXPR_ARG (expression, i);
19036             /* In a call to a constexpr member function, look through the
19037                implicit ADDR_EXPR on the object argument so that it doesn't
19038                cause the call to be considered value-dependent.  We also
19039                look through it in potential_constant_expression.  */
19040             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19041                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19042                 && TREE_CODE (op) == ADDR_EXPR)
19043               op = TREE_OPERAND (op, 0);
19044             if (value_dependent_expression_p (op))
19045               return true;
19046           }
19047         return false;
19048       }
19049
19050     case TEMPLATE_ID_EXPR:
19051       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19052          type-dependent.  */
19053       return type_dependent_expression_p (expression);
19054
19055     case CONSTRUCTOR:
19056       {
19057         unsigned ix;
19058         tree val;
19059         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19060           if (value_dependent_expression_p (val))
19061             return true;
19062         return false;
19063       }
19064
19065     default:
19066       /* A constant expression is value-dependent if any subexpression is
19067          value-dependent.  */
19068       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19069         {
19070         case tcc_reference:
19071         case tcc_unary:
19072         case tcc_comparison:
19073         case tcc_binary:
19074         case tcc_expression:
19075         case tcc_vl_exp:
19076           {
19077             int i, len = cp_tree_operand_length (expression);
19078
19079             for (i = 0; i < len; i++)
19080               {
19081                 tree t = TREE_OPERAND (expression, i);
19082
19083                 /* In some cases, some of the operands may be missing.l
19084                    (For example, in the case of PREDECREMENT_EXPR, the
19085                    amount to increment by may be missing.)  That doesn't
19086                    make the expression dependent.  */
19087                 if (t && value_dependent_expression_p (t))
19088                   return true;
19089               }
19090           }
19091           break;
19092         default:
19093           break;
19094         }
19095       break;
19096     }
19097
19098   /* The expression is not value-dependent.  */
19099   return false;
19100 }
19101
19102 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19103    [temp.dep.expr].  Note that an expression with no type is
19104    considered dependent.  Other parts of the compiler arrange for an
19105    expression with type-dependent subexpressions to have no type, so
19106    this function doesn't have to be fully recursive.  */
19107
19108 bool
19109 type_dependent_expression_p (tree expression)
19110 {
19111   if (!processing_template_decl)
19112     return false;
19113
19114   if (expression == error_mark_node)
19115     return false;
19116
19117   /* An unresolved name is always dependent.  */
19118   if (TREE_CODE (expression) == IDENTIFIER_NODE
19119       || TREE_CODE (expression) == USING_DECL)
19120     return true;
19121
19122   /* Some expression forms are never type-dependent.  */
19123   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19124       || TREE_CODE (expression) == SIZEOF_EXPR
19125       || TREE_CODE (expression) == ALIGNOF_EXPR
19126       || TREE_CODE (expression) == AT_ENCODE_EXPR
19127       || TREE_CODE (expression) == NOEXCEPT_EXPR
19128       || TREE_CODE (expression) == TRAIT_EXPR
19129       || TREE_CODE (expression) == TYPEID_EXPR
19130       || TREE_CODE (expression) == DELETE_EXPR
19131       || TREE_CODE (expression) == VEC_DELETE_EXPR
19132       || TREE_CODE (expression) == THROW_EXPR)
19133     return false;
19134
19135   /* The types of these expressions depends only on the type to which
19136      the cast occurs.  */
19137   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19138       || TREE_CODE (expression) == STATIC_CAST_EXPR
19139       || TREE_CODE (expression) == CONST_CAST_EXPR
19140       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19141       || TREE_CODE (expression) == CAST_EXPR)
19142     return dependent_type_p (TREE_TYPE (expression));
19143
19144   /* The types of these expressions depends only on the type created
19145      by the expression.  */
19146   if (TREE_CODE (expression) == NEW_EXPR
19147       || TREE_CODE (expression) == VEC_NEW_EXPR)
19148     {
19149       /* For NEW_EXPR tree nodes created inside a template, either
19150          the object type itself or a TREE_LIST may appear as the
19151          operand 1.  */
19152       tree type = TREE_OPERAND (expression, 1);
19153       if (TREE_CODE (type) == TREE_LIST)
19154         /* This is an array type.  We need to check array dimensions
19155            as well.  */
19156         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19157                || value_dependent_expression_p
19158                     (TREE_OPERAND (TREE_VALUE (type), 1));
19159       else
19160         return dependent_type_p (type);
19161     }
19162
19163   if (TREE_CODE (expression) == SCOPE_REF)
19164     {
19165       tree scope = TREE_OPERAND (expression, 0);
19166       tree name = TREE_OPERAND (expression, 1);
19167
19168       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19169          contains an identifier associated by name lookup with one or more
19170          declarations declared with a dependent type, or...a
19171          nested-name-specifier or qualified-id that names a member of an
19172          unknown specialization.  */
19173       return (type_dependent_expression_p (name)
19174               || dependent_scope_p (scope));
19175     }
19176
19177   if (TREE_CODE (expression) == FUNCTION_DECL
19178       && DECL_LANG_SPECIFIC (expression)
19179       && DECL_TEMPLATE_INFO (expression)
19180       && (any_dependent_template_arguments_p
19181           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19182     return true;
19183
19184   if (TREE_CODE (expression) == TEMPLATE_DECL
19185       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19186     return false;
19187
19188   if (TREE_CODE (expression) == STMT_EXPR)
19189     expression = stmt_expr_value_expr (expression);
19190
19191   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19192     {
19193       tree elt;
19194       unsigned i;
19195
19196       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19197         {
19198           if (type_dependent_expression_p (elt))
19199             return true;
19200         }
19201       return false;
19202     }
19203
19204   /* A static data member of the current instantiation with incomplete
19205      array type is type-dependent, as the definition and specializations
19206      can have different bounds.  */
19207   if (TREE_CODE (expression) == VAR_DECL
19208       && DECL_CLASS_SCOPE_P (expression)
19209       && dependent_type_p (DECL_CONTEXT (expression))
19210       && VAR_HAD_UNKNOWN_BOUND (expression))
19211     return true;
19212
19213   if (TREE_TYPE (expression) == unknown_type_node)
19214     {
19215       if (TREE_CODE (expression) == ADDR_EXPR)
19216         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19217       if (TREE_CODE (expression) == COMPONENT_REF
19218           || TREE_CODE (expression) == OFFSET_REF)
19219         {
19220           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19221             return true;
19222           expression = TREE_OPERAND (expression, 1);
19223           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19224             return false;
19225         }
19226       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19227       if (TREE_CODE (expression) == SCOPE_REF)
19228         return false;
19229
19230       if (TREE_CODE (expression) == BASELINK)
19231         expression = BASELINK_FUNCTIONS (expression);
19232
19233       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19234         {
19235           if (any_dependent_template_arguments_p
19236               (TREE_OPERAND (expression, 1)))
19237             return true;
19238           expression = TREE_OPERAND (expression, 0);
19239         }
19240       gcc_assert (TREE_CODE (expression) == OVERLOAD
19241                   || TREE_CODE (expression) == FUNCTION_DECL);
19242
19243       while (expression)
19244         {
19245           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19246             return true;
19247           expression = OVL_NEXT (expression);
19248         }
19249       return false;
19250     }
19251
19252   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19253
19254   return (dependent_type_p (TREE_TYPE (expression)));
19255 }
19256
19257 /* Like type_dependent_expression_p, but it also works while not processing
19258    a template definition, i.e. during substitution or mangling.  */
19259
19260 bool
19261 type_dependent_expression_p_push (tree expr)
19262 {
19263   bool b;
19264   ++processing_template_decl;
19265   b = type_dependent_expression_p (expr);
19266   --processing_template_decl;
19267   return b;
19268 }
19269
19270 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19271
19272 bool
19273 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19274 {
19275   unsigned int i;
19276   tree arg;
19277
19278   FOR_EACH_VEC_ELT (tree, args, i, arg)
19279     {
19280       if (type_dependent_expression_p (arg))
19281         return true;
19282     }
19283   return false;
19284 }
19285
19286 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19287    expressions) contains any type-dependent expressions.  */
19288
19289 bool
19290 any_type_dependent_elements_p (const_tree list)
19291 {
19292   for (; list; list = TREE_CHAIN (list))
19293     if (value_dependent_expression_p (TREE_VALUE (list)))
19294       return true;
19295
19296   return false;
19297 }
19298
19299 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19300    expressions) contains any value-dependent expressions.  */
19301
19302 bool
19303 any_value_dependent_elements_p (const_tree list)
19304 {
19305   for (; list; list = TREE_CHAIN (list))
19306     if (value_dependent_expression_p (TREE_VALUE (list)))
19307       return true;
19308
19309   return false;
19310 }
19311
19312 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19313
19314 bool
19315 dependent_template_arg_p (tree arg)
19316 {
19317   if (!processing_template_decl)
19318     return false;
19319
19320   /* Assume a template argument that was wrongly written by the user
19321      is dependent. This is consistent with what
19322      any_dependent_template_arguments_p [that calls this function]
19323      does.  */
19324   if (!arg || arg == error_mark_node)
19325     return true;
19326
19327   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19328     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19329
19330   if (TREE_CODE (arg) == TEMPLATE_DECL
19331       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19332     return dependent_template_p (arg);
19333   else if (ARGUMENT_PACK_P (arg))
19334     {
19335       tree args = ARGUMENT_PACK_ARGS (arg);
19336       int i, len = TREE_VEC_LENGTH (args);
19337       for (i = 0; i < len; ++i)
19338         {
19339           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19340             return true;
19341         }
19342
19343       return false;
19344     }
19345   else if (TYPE_P (arg))
19346     return dependent_type_p (arg);
19347   else
19348     return (type_dependent_expression_p (arg)
19349             || value_dependent_expression_p (arg));
19350 }
19351
19352 /* Returns true if ARGS (a collection of template arguments) contains
19353    any types that require structural equality testing.  */
19354
19355 bool
19356 any_template_arguments_need_structural_equality_p (tree args)
19357 {
19358   int i;
19359   int j;
19360
19361   if (!args)
19362     return false;
19363   if (args == error_mark_node)
19364     return true;
19365
19366   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19367     {
19368       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19369       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19370         {
19371           tree arg = TREE_VEC_ELT (level, j);
19372           tree packed_args = NULL_TREE;
19373           int k, len = 1;
19374
19375           if (ARGUMENT_PACK_P (arg))
19376             {
19377               /* Look inside the argument pack.  */
19378               packed_args = ARGUMENT_PACK_ARGS (arg);
19379               len = TREE_VEC_LENGTH (packed_args);
19380             }
19381
19382           for (k = 0; k < len; ++k)
19383             {
19384               if (packed_args)
19385                 arg = TREE_VEC_ELT (packed_args, k);
19386
19387               if (error_operand_p (arg))
19388                 return true;
19389               else if (TREE_CODE (arg) == TEMPLATE_DECL
19390                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19391                 continue;
19392               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19393                 return true;
19394               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19395                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19396                 return true;
19397             }
19398         }
19399     }
19400
19401   return false;
19402 }
19403
19404 /* Returns true if ARGS (a collection of template arguments) contains
19405    any dependent arguments.  */
19406
19407 bool
19408 any_dependent_template_arguments_p (const_tree args)
19409 {
19410   int i;
19411   int j;
19412
19413   if (!args)
19414     return false;
19415   if (args == error_mark_node)
19416     return true;
19417
19418   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19419     {
19420       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19421       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19422         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19423           return true;
19424     }
19425
19426   return false;
19427 }
19428
19429 /* Returns TRUE if the template TMPL is dependent.  */
19430
19431 bool
19432 dependent_template_p (tree tmpl)
19433 {
19434   if (TREE_CODE (tmpl) == OVERLOAD)
19435     {
19436       while (tmpl)
19437         {
19438           if (dependent_template_p (OVL_CURRENT (tmpl)))
19439             return true;
19440           tmpl = OVL_NEXT (tmpl);
19441         }
19442       return false;
19443     }
19444
19445   /* Template template parameters are dependent.  */
19446   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19447       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19448     return true;
19449   /* So are names that have not been looked up.  */
19450   if (TREE_CODE (tmpl) == SCOPE_REF
19451       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19452     return true;
19453   /* So are member templates of dependent classes.  */
19454   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19455     return dependent_type_p (DECL_CONTEXT (tmpl));
19456   return false;
19457 }
19458
19459 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19460
19461 bool
19462 dependent_template_id_p (tree tmpl, tree args)
19463 {
19464   return (dependent_template_p (tmpl)
19465           || any_dependent_template_arguments_p (args));
19466 }
19467
19468 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19469    is dependent.  */
19470
19471 bool
19472 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19473 {
19474   int i;
19475
19476   if (!processing_template_decl)
19477     return false;
19478
19479   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19480     {
19481       tree decl = TREE_VEC_ELT (declv, i);
19482       tree init = TREE_VEC_ELT (initv, i);
19483       tree cond = TREE_VEC_ELT (condv, i);
19484       tree incr = TREE_VEC_ELT (incrv, i);
19485
19486       if (type_dependent_expression_p (decl))
19487         return true;
19488
19489       if (init && type_dependent_expression_p (init))
19490         return true;
19491
19492       if (type_dependent_expression_p (cond))
19493         return true;
19494
19495       if (COMPARISON_CLASS_P (cond)
19496           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19497               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19498         return true;
19499
19500       if (TREE_CODE (incr) == MODOP_EXPR)
19501         {
19502           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19503               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19504             return true;
19505         }
19506       else if (type_dependent_expression_p (incr))
19507         return true;
19508       else if (TREE_CODE (incr) == MODIFY_EXPR)
19509         {
19510           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19511             return true;
19512           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19513             {
19514               tree t = TREE_OPERAND (incr, 1);
19515               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19516                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19517                 return true;
19518             }
19519         }
19520     }
19521
19522   return false;
19523 }
19524
19525 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19526    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19527    no such TYPE can be found.  Note that this function peers inside
19528    uninstantiated templates and therefore should be used only in
19529    extremely limited situations.  ONLY_CURRENT_P restricts this
19530    peering to the currently open classes hierarchy (which is required
19531    when comparing types).  */
19532
19533 tree
19534 resolve_typename_type (tree type, bool only_current_p)
19535 {
19536   tree scope;
19537   tree name;
19538   tree decl;
19539   int quals;
19540   tree pushed_scope;
19541   tree result;
19542
19543   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19544
19545   scope = TYPE_CONTEXT (type);
19546   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19547      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19548      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19549      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19550      identifier  of the TYPENAME_TYPE anymore.
19551      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19552      TYPENAME_TYPE instead, we avoid messing up with a possible
19553      typedef variant case.  */
19554   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19555
19556   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19557      it first before we can figure out what NAME refers to.  */
19558   if (TREE_CODE (scope) == TYPENAME_TYPE)
19559     scope = resolve_typename_type (scope, only_current_p);
19560   /* If we don't know what SCOPE refers to, then we cannot resolve the
19561      TYPENAME_TYPE.  */
19562   if (TREE_CODE (scope) == TYPENAME_TYPE)
19563     return type;
19564   /* If the SCOPE is a template type parameter, we have no way of
19565      resolving the name.  */
19566   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19567     return type;
19568   /* If the SCOPE is not the current instantiation, there's no reason
19569      to look inside it.  */
19570   if (only_current_p && !currently_open_class (scope))
19571     return type;
19572   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19573   if (typedef_variant_p (type))
19574     return type;
19575   /* If SCOPE isn't the template itself, it will not have a valid
19576      TYPE_FIELDS list.  */
19577   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19578     /* scope is either the template itself or a compatible instantiation
19579        like X<T>, so look up the name in the original template.  */
19580     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19581   else
19582     /* scope is a partial instantiation, so we can't do the lookup or we
19583        will lose the template arguments.  */
19584     return type;
19585   /* Enter the SCOPE so that name lookup will be resolved as if we
19586      were in the class definition.  In particular, SCOPE will no
19587      longer be considered a dependent type.  */
19588   pushed_scope = push_scope (scope);
19589   /* Look up the declaration.  */
19590   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
19591
19592   result = NULL_TREE;
19593   
19594   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19595      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19596   if (!decl)
19597     /*nop*/;
19598   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19599            && TREE_CODE (decl) == TYPE_DECL)
19600     {
19601       result = TREE_TYPE (decl);
19602       if (result == error_mark_node)
19603         result = NULL_TREE;
19604     }
19605   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19606            && DECL_CLASS_TEMPLATE_P (decl))
19607     {
19608       tree tmpl;
19609       tree args;
19610       /* Obtain the template and the arguments.  */
19611       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19612       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19613       /* Instantiate the template.  */
19614       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19615                                       /*entering_scope=*/0,
19616                                       tf_error | tf_user);
19617       if (result == error_mark_node)
19618         result = NULL_TREE;
19619     }
19620   
19621   /* Leave the SCOPE.  */
19622   if (pushed_scope)
19623     pop_scope (pushed_scope);
19624
19625   /* If we failed to resolve it, return the original typename.  */
19626   if (!result)
19627     return type;
19628   
19629   /* If lookup found a typename type, resolve that too.  */
19630   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19631     {
19632       /* Ill-formed programs can cause infinite recursion here, so we
19633          must catch that.  */
19634       TYPENAME_IS_RESOLVING_P (type) = 1;
19635       result = resolve_typename_type (result, only_current_p);
19636       TYPENAME_IS_RESOLVING_P (type) = 0;
19637     }
19638   
19639   /* Qualify the resulting type.  */
19640   quals = cp_type_quals (type);
19641   if (quals)
19642     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19643
19644   return result;
19645 }
19646
19647 /* EXPR is an expression which is not type-dependent.  Return a proxy
19648    for EXPR that can be used to compute the types of larger
19649    expressions containing EXPR.  */
19650
19651 tree
19652 build_non_dependent_expr (tree expr)
19653 {
19654   tree inner_expr;
19655
19656 #ifdef ENABLE_CHECKING
19657   /* Try to get a constant value for all non-type-dependent expressions in
19658       order to expose bugs in *_dependent_expression_p and constexpr.  */
19659   if (cxx_dialect >= cxx0x)
19660     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19661 #endif
19662
19663   /* Preserve OVERLOADs; the functions must be available to resolve
19664      types.  */
19665   inner_expr = expr;
19666   if (TREE_CODE (inner_expr) == STMT_EXPR)
19667     inner_expr = stmt_expr_value_expr (inner_expr);
19668   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19669     inner_expr = TREE_OPERAND (inner_expr, 0);
19670   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19671     inner_expr = TREE_OPERAND (inner_expr, 1);
19672   if (is_overloaded_fn (inner_expr)
19673       || TREE_CODE (inner_expr) == OFFSET_REF)
19674     return expr;
19675   /* There is no need to return a proxy for a variable.  */
19676   if (TREE_CODE (expr) == VAR_DECL)
19677     return expr;
19678   /* Preserve string constants; conversions from string constants to
19679      "char *" are allowed, even though normally a "const char *"
19680      cannot be used to initialize a "char *".  */
19681   if (TREE_CODE (expr) == STRING_CST)
19682     return expr;
19683   /* Preserve arithmetic constants, as an optimization -- there is no
19684      reason to create a new node.  */
19685   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19686     return expr;
19687   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19688      There is at least one place where we want to know that a
19689      particular expression is a throw-expression: when checking a ?:
19690      expression, there are special rules if the second or third
19691      argument is a throw-expression.  */
19692   if (TREE_CODE (expr) == THROW_EXPR)
19693     return expr;
19694
19695   /* Don't wrap an initializer list, we need to be able to look inside.  */
19696   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19697     return expr;
19698
19699   if (TREE_CODE (expr) == COND_EXPR)
19700     return build3 (COND_EXPR,
19701                    TREE_TYPE (expr),
19702                    TREE_OPERAND (expr, 0),
19703                    (TREE_OPERAND (expr, 1)
19704                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19705                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19706                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19707   if (TREE_CODE (expr) == COMPOUND_EXPR
19708       && !COMPOUND_EXPR_OVERLOADED (expr))
19709     return build2 (COMPOUND_EXPR,
19710                    TREE_TYPE (expr),
19711                    TREE_OPERAND (expr, 0),
19712                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19713
19714   /* If the type is unknown, it can't really be non-dependent */
19715   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19716
19717   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19718   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19719 }
19720
19721 /* ARGS is a vector of expressions as arguments to a function call.
19722    Replace the arguments with equivalent non-dependent expressions.
19723    This modifies ARGS in place.  */
19724
19725 void
19726 make_args_non_dependent (VEC(tree,gc) *args)
19727 {
19728   unsigned int ix;
19729   tree arg;
19730
19731   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19732     {
19733       tree newarg = build_non_dependent_expr (arg);
19734       if (newarg != arg)
19735         VEC_replace (tree, args, ix, newarg);
19736     }
19737 }
19738
19739 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19740    with a level one deeper than the actual template parms.  */
19741
19742 tree
19743 make_auto (void)
19744 {
19745   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19746   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19747                                TYPE_DECL, get_identifier ("auto"), au);
19748   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19749   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19750     (0, processing_template_decl + 1, processing_template_decl + 1,
19751      0, TYPE_NAME (au), NULL_TREE);
19752   TYPE_CANONICAL (au) = canonical_type_parameter (au);
19753   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
19754   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
19755
19756   return au;
19757 }
19758
19759 /* Given type ARG, return std::initializer_list<ARG>.  */
19760
19761 static tree
19762 listify (tree arg)
19763 {
19764   tree std_init_list = namespace_binding
19765     (get_identifier ("initializer_list"), std_node);
19766   tree argvec;
19767   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
19768     {    
19769       error ("deducing from brace-enclosed initializer list requires "
19770              "#include <initializer_list>");
19771       return error_mark_node;
19772     }
19773   argvec = make_tree_vec (1);
19774   TREE_VEC_ELT (argvec, 0) = arg;
19775   return lookup_template_class (std_init_list, argvec, NULL_TREE,
19776                                 NULL_TREE, 0, tf_warning_or_error);
19777 }
19778
19779 /* Replace auto in TYPE with std::initializer_list<auto>.  */
19780
19781 static tree
19782 listify_autos (tree type, tree auto_node)
19783 {
19784   tree init_auto = listify (auto_node);
19785   tree argvec = make_tree_vec (1);
19786   TREE_VEC_ELT (argvec, 0) = init_auto;
19787   if (processing_template_decl)
19788     argvec = add_to_template_args (current_template_args (), argvec);
19789   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19790 }
19791
19792 /* walk_tree helper for do_auto_deduction.  */
19793
19794 static tree
19795 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
19796                  void *type)
19797 {
19798   /* Is this a variable with the type we're looking for?  */
19799   if (DECL_P (*tp)
19800       && TREE_TYPE (*tp) == type)
19801     return *tp;
19802   else
19803     return NULL_TREE;
19804 }
19805
19806 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
19807    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
19808
19809 tree
19810 do_auto_deduction (tree type, tree init, tree auto_node)
19811 {
19812   tree parms, tparms, targs;
19813   tree args[1];
19814   tree decl;
19815   int val;
19816
19817   if (processing_template_decl
19818       && (TREE_TYPE (init) == NULL_TREE
19819           || BRACE_ENCLOSED_INITIALIZER_P (init)))
19820     /* Not enough information to try this yet.  */
19821     return type;
19822
19823   /* The name of the object being declared shall not appear in the
19824      initializer expression.  */
19825   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
19826   if (decl)
19827     {
19828       error ("variable %q#D with %<auto%> type used in its own "
19829              "initializer", decl);
19830       return error_mark_node;
19831     }
19832
19833   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
19834      with either a new invented type template parameter U or, if the
19835      initializer is a braced-init-list (8.5.4), with
19836      std::initializer_list<U>.  */
19837   if (BRACE_ENCLOSED_INITIALIZER_P (init))
19838     type = listify_autos (type, auto_node);
19839
19840   init = resolve_nondeduced_context (init);
19841
19842   parms = build_tree_list (NULL_TREE, type);
19843   args[0] = init;
19844   tparms = make_tree_vec (1);
19845   targs = make_tree_vec (1);
19846   TREE_VEC_ELT (tparms, 0)
19847     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
19848   val = type_unification_real (tparms, targs, parms, args, 1, 0,
19849                                DEDUCE_CALL, LOOKUP_NORMAL,
19850                                /*explain_p=*/false);
19851   if (val > 0)
19852     {
19853       if (processing_template_decl)
19854         /* Try again at instantiation time.  */
19855         return type;
19856       if (type && type != error_mark_node)
19857         /* If type is error_mark_node a diagnostic must have been
19858            emitted by now.  Also, having a mention to '<type error>'
19859            in the diagnostic is not really useful to the user.  */
19860         error ("unable to deduce %qT from %qE", type, init);
19861       return error_mark_node;
19862     }
19863
19864   /* If the list of declarators contains more than one declarator, the type
19865      of each declared variable is determined as described above. If the
19866      type deduced for the template parameter U is not the same in each
19867      deduction, the program is ill-formed.  */
19868   if (TREE_TYPE (auto_node)
19869       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
19870     {
19871       error ("inconsistent deduction for %qT: %qT and then %qT",
19872              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
19873       return error_mark_node;
19874     }
19875   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
19876
19877   if (processing_template_decl)
19878     targs = add_to_template_args (current_template_args (), targs);
19879   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
19880 }
19881
19882 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
19883    result.  */
19884
19885 tree
19886 splice_late_return_type (tree type, tree late_return_type)
19887 {
19888   tree argvec;
19889
19890   if (late_return_type == NULL_TREE)
19891     return type;
19892   argvec = make_tree_vec (1);
19893   TREE_VEC_ELT (argvec, 0) = late_return_type;
19894   if (processing_template_parmlist)
19895     /* For a late-specified return type in a template type-parameter, we
19896        need to add a dummy argument level for its parmlist.  */
19897     argvec = add_to_template_args
19898       (make_tree_vec (processing_template_parmlist), argvec);
19899   if (current_template_parms)
19900     argvec = add_to_template_args (current_template_args (), argvec);
19901   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
19902 }
19903
19904 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
19905
19906 bool
19907 is_auto (const_tree type)
19908 {
19909   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19910       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
19911     return true;
19912   else
19913     return false;
19914 }
19915
19916 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
19917    appear as a type-specifier for the declaration in question, we don't
19918    have to look through the whole type.  */
19919
19920 tree
19921 type_uses_auto (tree type)
19922 {
19923   enum tree_code code;
19924   if (is_auto (type))
19925     return type;
19926
19927   code = TREE_CODE (type);
19928
19929   if (code == POINTER_TYPE || code == REFERENCE_TYPE
19930       || code == OFFSET_TYPE || code == FUNCTION_TYPE
19931       || code == METHOD_TYPE || code == ARRAY_TYPE)
19932     return type_uses_auto (TREE_TYPE (type));
19933
19934   if (TYPE_PTRMEMFUNC_P (type))
19935     return type_uses_auto (TREE_TYPE (TREE_TYPE
19936                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19937
19938   return NULL_TREE;
19939 }
19940
19941 /* For a given template T, return the vector of typedefs referenced
19942    in T for which access check is needed at T instantiation time.
19943    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19944    Those typedefs were added to T by the function
19945    append_type_to_template_for_access_check.  */
19946
19947 VEC(qualified_typedef_usage_t,gc)*
19948 get_types_needing_access_check (tree t)
19949 {
19950   tree ti;
19951   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19952
19953   if (!t || t == error_mark_node)
19954     return NULL;
19955
19956   if (!(ti = get_template_info (t)))
19957     return NULL;
19958
19959   if (CLASS_TYPE_P (t)
19960       || TREE_CODE (t) == FUNCTION_DECL)
19961     {
19962       if (!TI_TEMPLATE (ti))
19963         return NULL;
19964
19965       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19966     }
19967
19968   return result;
19969 }
19970
19971 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19972    tied to T. That list of typedefs will be access checked at
19973    T instantiation time.
19974    T is either a FUNCTION_DECL or a RECORD_TYPE.
19975    TYPE_DECL is a TYPE_DECL node representing a typedef.
19976    SCOPE is the scope through which TYPE_DECL is accessed.
19977    LOCATION is the location of the usage point of TYPE_DECL.
19978
19979    This function is a subroutine of
19980    append_type_to_template_for_access_check.  */
19981
19982 static void
19983 append_type_to_template_for_access_check_1 (tree t,
19984                                             tree type_decl,
19985                                             tree scope,
19986                                             location_t location)
19987 {
19988   qualified_typedef_usage_t typedef_usage;
19989   tree ti;
19990
19991   if (!t || t == error_mark_node)
19992     return;
19993
19994   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19995                || CLASS_TYPE_P (t))
19996               && type_decl
19997               && TREE_CODE (type_decl) == TYPE_DECL
19998               && scope);
19999
20000   if (!(ti = get_template_info (t)))
20001     return;
20002
20003   gcc_assert (TI_TEMPLATE (ti));
20004
20005   typedef_usage.typedef_decl = type_decl;
20006   typedef_usage.context = scope;
20007   typedef_usage.locus = location;
20008
20009   VEC_safe_push (qualified_typedef_usage_t, gc,
20010                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20011                  &typedef_usage);
20012 }
20013
20014 /* Append TYPE_DECL to the template TEMPL.
20015    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20016    At TEMPL instanciation time, TYPE_DECL will be checked to see
20017    if it can be accessed through SCOPE.
20018    LOCATION is the location of the usage point of TYPE_DECL.
20019
20020    e.g. consider the following code snippet:
20021
20022      class C
20023      {
20024        typedef int myint;
20025      };
20026
20027      template<class U> struct S
20028      {
20029        C::myint mi; // <-- usage point of the typedef C::myint
20030      };
20031
20032      S<char> s;
20033
20034    At S<char> instantiation time, we need to check the access of C::myint
20035    In other words, we need to check the access of the myint typedef through
20036    the C scope. For that purpose, this function will add the myint typedef
20037    and the scope C through which its being accessed to a list of typedefs
20038    tied to the template S. That list will be walked at template instantiation
20039    time and access check performed on each typedefs it contains.
20040    Note that this particular code snippet should yield an error because
20041    myint is private to C.  */
20042
20043 void
20044 append_type_to_template_for_access_check (tree templ,
20045                                           tree type_decl,
20046                                           tree scope,
20047                                           location_t location)
20048 {
20049   qualified_typedef_usage_t *iter;
20050   int i;
20051
20052   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20053
20054   /* Make sure we don't append the type to the template twice.  */
20055   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20056                     get_types_needing_access_check (templ),
20057                     i, iter)
20058     if (iter->typedef_decl == type_decl && scope == iter->context)
20059       return;
20060
20061   append_type_to_template_for_access_check_1 (templ, type_decl,
20062                                               scope, location);
20063 }
20064
20065 /* Set up the hash tables for template instantiations.  */
20066
20067 void
20068 init_template_processing (void)
20069 {
20070   decl_specializations = htab_create_ggc (37,
20071                                           hash_specialization,
20072                                           eq_specializations,
20073                                           ggc_free);
20074   type_specializations = htab_create_ggc (37,
20075                                           hash_specialization,
20076                                           eq_specializations,
20077                                           ggc_free);
20078 }
20079
20080 /* Print stats about the template hash tables for -fstats.  */
20081
20082 void
20083 print_template_statistics (void)
20084 {
20085   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20086            "%f collisions\n", (long) htab_size (decl_specializations),
20087            (long) htab_elements (decl_specializations),
20088            htab_collisions (decl_specializations));
20089   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20090            "%f collisions\n", (long) htab_size (type_specializations),
20091            (long) htab_elements (type_specializations),
20092            htab_collisions (type_specializations));
20093 }
20094
20095 #include "gt-cp-pt.h"