OSDN Git Service

PR c++/53862
[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, 2012
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, tree, tree);
152 static bool inline_needs_template_parms (tree);
153 static void push_inline_template_parms_recursive (tree, int);
154 static tree retrieve_local_specialization (tree);
155 static void register_local_specialization (tree, tree);
156 static hashval_t hash_specialization (const void *p);
157 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
158 static int mark_template_parm (tree, void *);
159 static int template_parm_this_level_p (tree, void *);
160 static tree tsubst_friend_function (tree, tree);
161 static tree tsubst_friend_class (tree, tree);
162 static int can_complete_type_without_circularity (tree);
163 static tree get_bindings (tree, tree, tree, bool);
164 static int template_decl_level (tree);
165 static int check_cv_quals_for_unify (int, tree, tree);
166 static void template_parm_level_and_index (tree, int*, int*);
167 static int unify_pack_expansion (tree, tree, tree,
168                                  tree, unification_kind_t, bool, bool);
169 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
171 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
172 static void regenerate_decl_from_template (tree, tree);
173 static tree most_specialized_class (tree, tree, tsubst_flags_t);
174 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
175 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
177 static bool check_specialization_scope (void);
178 static tree process_partial_specialization (tree);
179 static void set_current_access_from_decl (tree);
180 static enum template_base_result get_template_base (tree, tree, tree, tree,
181                                                     bool , tree *);
182 static tree try_class_unification (tree, tree, tree, tree, bool);
183 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
184                                            tree, tree);
185 static bool template_template_parm_bindings_ok_p (tree, tree);
186 static int template_args_equal (tree, tree);
187 static void tsubst_default_arguments (tree);
188 static tree for_each_template_parm_r (tree *, int *, void *);
189 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
190 static void copy_default_args_to_explicit_spec (tree);
191 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
192 static int eq_local_specializations (const void *, const void *);
193 static bool dependent_template_arg_p (tree);
194 static bool any_template_arguments_need_structural_equality_p (tree);
195 static bool dependent_type_p_r (tree);
196 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
197 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
198 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
199 static tree tsubst_decl (tree, tree, tsubst_flags_t);
200 static void perform_typedefs_access_check (tree tmpl, tree targs);
201 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
202                                                         location_t);
203 static tree listify (tree);
204 static tree listify_autos (tree, tree);
205 static tree template_parm_to_arg (tree t);
206 static bool arg_from_parm_pack_p (tree, tree);
207 static tree current_template_args (void);
208 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
209
210 /* Make the current scope suitable for access checking when we are
211    processing T.  T can be FUNCTION_DECL for instantiated function
212    template, or VAR_DECL for static member variable (need by
213    instantiate_decl).  */
214
215 static void
216 push_access_scope (tree t)
217 {
218   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
219               || TREE_CODE (t) == VAR_DECL);
220
221   if (DECL_FRIEND_CONTEXT (t))
222     push_nested_class (DECL_FRIEND_CONTEXT (t));
223   else if (DECL_CLASS_SCOPE_P (t))
224     push_nested_class (DECL_CONTEXT (t));
225   else
226     push_to_top_level ();
227
228   if (TREE_CODE (t) == FUNCTION_DECL)
229     {
230       saved_access_scope = tree_cons
231         (NULL_TREE, current_function_decl, saved_access_scope);
232       current_function_decl = t;
233     }
234 }
235
236 /* Restore the scope set up by push_access_scope.  T is the node we
237    are processing.  */
238
239 static void
240 pop_access_scope (tree t)
241 {
242   if (TREE_CODE (t) == FUNCTION_DECL)
243     {
244       current_function_decl = TREE_VALUE (saved_access_scope);
245       saved_access_scope = TREE_CHAIN (saved_access_scope);
246     }
247
248   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
249     pop_nested_class ();
250   else
251     pop_from_top_level ();
252 }
253
254 /* Do any processing required when DECL (a member template
255    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
256    to DECL, unless it is a specialization, in which case the DECL
257    itself is returned.  */
258
259 tree
260 finish_member_template_decl (tree decl)
261 {
262   if (decl == error_mark_node)
263     return error_mark_node;
264
265   gcc_assert (DECL_P (decl));
266
267   if (TREE_CODE (decl) == TYPE_DECL)
268     {
269       tree type;
270
271       type = TREE_TYPE (decl);
272       if (type == error_mark_node)
273         return error_mark_node;
274       if (MAYBE_CLASS_TYPE_P (type)
275           && CLASSTYPE_TEMPLATE_INFO (type)
276           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
277         {
278           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
279           check_member_template (tmpl);
280           return tmpl;
281         }
282       return NULL_TREE;
283     }
284   else if (TREE_CODE (decl) == FIELD_DECL)
285     error ("data member %qD cannot be a member template", decl);
286   else if (DECL_TEMPLATE_INFO (decl))
287     {
288       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
289         {
290           check_member_template (DECL_TI_TEMPLATE (decl));
291           return DECL_TI_TEMPLATE (decl);
292         }
293       else
294         return decl;
295     }
296   else
297     error ("invalid member template declaration %qD", decl);
298
299   return error_mark_node;
300 }
301
302 /* Create a template info node.  */
303
304 tree
305 build_template_info (tree template_decl, tree template_args)
306 {
307   tree result = make_node (TEMPLATE_INFO);
308   TI_TEMPLATE (result) = template_decl;
309   TI_ARGS (result) = template_args;
310   return result;
311 }
312
313 /* Return the template info node corresponding to T, whatever T is.  */
314
315 tree
316 get_template_info (const_tree t)
317 {
318   tree tinfo = NULL_TREE;
319
320   if (!t || t == error_mark_node)
321     return NULL;
322
323   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
324     tinfo = DECL_TEMPLATE_INFO (t);
325
326   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
327     t = TREE_TYPE (t);
328
329   if (TAGGED_TYPE_P (t))
330     tinfo = TYPE_TEMPLATE_INFO (t);
331   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
332     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
333
334   return tinfo;
335 }
336
337 /* Returns the template nesting level of the indicated class TYPE.
338
339    For example, in:
340      template <class T>
341      struct A
342      {
343        template <class U>
344        struct B {};
345      };
346
347    A<T>::B<U> has depth two, while A<T> has depth one.
348    Both A<T>::B<int> and A<int>::B<U> have depth one, if
349    they are instantiations, not specializations.
350
351    This function is guaranteed to return 0 if passed NULL_TREE so
352    that, for example, `template_class_depth (current_class_type)' is
353    always safe.  */
354
355 int
356 template_class_depth (tree type)
357 {
358   int depth;
359
360   for (depth = 0;
361        type && TREE_CODE (type) != NAMESPACE_DECL;
362        type = (TREE_CODE (type) == FUNCTION_DECL)
363          ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
364     {
365       tree tinfo = get_template_info (type);
366
367       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
368           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
369         ++depth;
370     }
371
372   return depth;
373 }
374
375 /* Subroutine of maybe_begin_member_template_processing.
376    Returns true if processing DECL needs us to push template parms.  */
377
378 static bool
379 inline_needs_template_parms (tree decl)
380 {
381   if (! DECL_TEMPLATE_INFO (decl))
382     return false;
383
384   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
385           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
386 }
387
388 /* Subroutine of maybe_begin_member_template_processing.
389    Push the template parms in PARMS, starting from LEVELS steps into the
390    chain, and ending at the beginning, since template parms are listed
391    innermost first.  */
392
393 static void
394 push_inline_template_parms_recursive (tree parmlist, int levels)
395 {
396   tree parms = TREE_VALUE (parmlist);
397   int i;
398
399   if (levels > 1)
400     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
401
402   ++processing_template_decl;
403   current_template_parms
404     = tree_cons (size_int (processing_template_decl),
405                  parms, current_template_parms);
406   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
407
408   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
409                NULL);
410   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
411     {
412       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
413
414       if (parm == error_mark_node)
415         continue;
416
417       gcc_assert (DECL_P (parm));
418
419       switch (TREE_CODE (parm))
420         {
421         case TYPE_DECL:
422         case TEMPLATE_DECL:
423           pushdecl (parm);
424           break;
425
426         case PARM_DECL:
427           {
428             /* Make a CONST_DECL as is done in process_template_parm.
429                It is ugly that we recreate this here; the original
430                version built in process_template_parm is no longer
431                available.  */
432             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
433                                     CONST_DECL, DECL_NAME (parm),
434                                     TREE_TYPE (parm));
435             DECL_ARTIFICIAL (decl) = 1;
436             TREE_CONSTANT (decl) = 1;
437             TREE_READONLY (decl) = 1;
438             DECL_INITIAL (decl) = DECL_INITIAL (parm);
439             SET_DECL_TEMPLATE_PARM_P (decl);
440             pushdecl (decl);
441           }
442           break;
443
444         default:
445           gcc_unreachable ();
446         }
447     }
448 }
449
450 /* Restore the template parameter context for a member template or
451    a friend template defined in a class definition.  */
452
453 void
454 maybe_begin_member_template_processing (tree decl)
455 {
456   tree parms;
457   int levels = 0;
458
459   if (inline_needs_template_parms (decl))
460     {
461       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
462       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
463
464       if (DECL_TEMPLATE_SPECIALIZATION (decl))
465         {
466           --levels;
467           parms = TREE_CHAIN (parms);
468         }
469
470       push_inline_template_parms_recursive (parms, levels);
471     }
472
473   /* Remember how many levels of template parameters we pushed so that
474      we can pop them later.  */
475   VEC_safe_push (int, heap, inline_parm_levels, levels);
476 }
477
478 /* Undo the effects of maybe_begin_member_template_processing.  */
479
480 void
481 maybe_end_member_template_processing (void)
482 {
483   int i;
484   int last;
485
486   if (VEC_length (int, inline_parm_levels) == 0)
487     return;
488
489   last = VEC_pop (int, inline_parm_levels);
490   for (i = 0; i < last; ++i)
491     {
492       --processing_template_decl;
493       current_template_parms = TREE_CHAIN (current_template_parms);
494       poplevel (0, 0, 0);
495     }
496 }
497
498 /* Return a new template argument vector which contains all of ARGS,
499    but has as its innermost set of arguments the EXTRA_ARGS.  */
500
501 static tree
502 add_to_template_args (tree args, tree extra_args)
503 {
504   tree new_args;
505   int extra_depth;
506   int i;
507   int j;
508
509   if (args == NULL_TREE || extra_args == error_mark_node)
510     return extra_args;
511
512   extra_depth = TMPL_ARGS_DEPTH (extra_args);
513   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
514
515   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
516     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
517
518   for (j = 1; j <= extra_depth; ++j, ++i)
519     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
520
521   return new_args;
522 }
523
524 /* Like add_to_template_args, but only the outermost ARGS are added to
525    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
526    (EXTRA_ARGS) levels are added.  This function is used to combine
527    the template arguments from a partial instantiation with the
528    template arguments used to attain the full instantiation from the
529    partial instantiation.  */
530
531 static tree
532 add_outermost_template_args (tree args, tree extra_args)
533 {
534   tree new_args;
535
536   /* If there are more levels of EXTRA_ARGS than there are ARGS,
537      something very fishy is going on.  */
538   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
539
540   /* If *all* the new arguments will be the EXTRA_ARGS, just return
541      them.  */
542   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
543     return extra_args;
544
545   /* For the moment, we make ARGS look like it contains fewer levels.  */
546   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
547
548   new_args = add_to_template_args (args, extra_args);
549
550   /* Now, we restore ARGS to its full dimensions.  */
551   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
552
553   return new_args;
554 }
555
556 /* Return the N levels of innermost template arguments from the ARGS.  */
557
558 tree
559 get_innermost_template_args (tree args, int n)
560 {
561   tree new_args;
562   int extra_levels;
563   int i;
564
565   gcc_assert (n >= 0);
566
567   /* If N is 1, just return the innermost set of template arguments.  */
568   if (n == 1)
569     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
570
571   /* If we're not removing anything, just return the arguments we were
572      given.  */
573   extra_levels = TMPL_ARGS_DEPTH (args) - n;
574   gcc_assert (extra_levels >= 0);
575   if (extra_levels == 0)
576     return args;
577
578   /* Make a new set of arguments, not containing the outer arguments.  */
579   new_args = make_tree_vec (n);
580   for (i = 1; i <= n; ++i)
581     SET_TMPL_ARGS_LEVEL (new_args, i,
582                          TMPL_ARGS_LEVEL (args, i + extra_levels));
583
584   return new_args;
585 }
586
587 /* The inverse of get_innermost_template_args: Return all but the innermost
588    EXTRA_LEVELS levels of template arguments from the ARGS.  */
589
590 static tree
591 strip_innermost_template_args (tree args, int extra_levels)
592 {
593   tree new_args;
594   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
595   int i;
596
597   gcc_assert (n >= 0);
598
599   /* If N is 1, just return the outermost set of template arguments.  */
600   if (n == 1)
601     return TMPL_ARGS_LEVEL (args, 1);
602
603   /* If we're not removing anything, just return the arguments we were
604      given.  */
605   gcc_assert (extra_levels >= 0);
606   if (extra_levels == 0)
607     return args;
608
609   /* Make a new set of arguments, not containing the inner arguments.  */
610   new_args = make_tree_vec (n);
611   for (i = 1; i <= n; ++i)
612     SET_TMPL_ARGS_LEVEL (new_args, i,
613                          TMPL_ARGS_LEVEL (args, i));
614
615   return new_args;
616 }
617
618 /* We've got a template header coming up; push to a new level for storing
619    the parms.  */
620
621 void
622 begin_template_parm_list (void)
623 {
624   /* We use a non-tag-transparent scope here, which causes pushtag to
625      put tags in this scope, rather than in the enclosing class or
626      namespace scope.  This is the right thing, since we want
627      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
628      global template class, push_template_decl handles putting the
629      TEMPLATE_DECL into top-level scope.  For a nested template class,
630      e.g.:
631
632        template <class T> struct S1 {
633          template <class T> struct S2 {};
634        };
635
636      pushtag contains special code to call pushdecl_with_scope on the
637      TEMPLATE_DECL for S2.  */
638   begin_scope (sk_template_parms, NULL);
639   ++processing_template_decl;
640   ++processing_template_parmlist;
641   note_template_header (0);
642 }
643
644 /* This routine is called when a specialization is declared.  If it is
645    invalid to declare a specialization here, an error is reported and
646    false is returned, otherwise this routine will return true.  */
647
648 static bool
649 check_specialization_scope (void)
650 {
651   tree scope = current_scope ();
652
653   /* [temp.expl.spec]
654
655      An explicit specialization shall be declared in the namespace of
656      which the template is a member, or, for member templates, in the
657      namespace of which the enclosing class or enclosing class
658      template is a member.  An explicit specialization of a member
659      function, member class or static data member of a class template
660      shall be declared in the namespace of which the class template
661      is a member.  */
662   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
663     {
664       error ("explicit specialization in non-namespace scope %qD", scope);
665       return false;
666     }
667
668   /* [temp.expl.spec]
669
670      In an explicit specialization declaration for a member of a class
671      template or a member template that appears in namespace scope,
672      the member template and some of its enclosing class templates may
673      remain unspecialized, except that the declaration shall not
674      explicitly specialize a class member template if its enclosing
675      class templates are not explicitly specialized as well.  */
676   if (current_template_parms)
677     {
678       error ("enclosing class templates are not explicitly specialized");
679       return false;
680     }
681
682   return true;
683 }
684
685 /* We've just seen template <>.  */
686
687 bool
688 begin_specialization (void)
689 {
690   begin_scope (sk_template_spec, NULL);
691   note_template_header (1);
692   return check_specialization_scope ();
693 }
694
695 /* Called at then end of processing a declaration preceded by
696    template<>.  */
697
698 void
699 end_specialization (void)
700 {
701   finish_scope ();
702   reset_specialization ();
703 }
704
705 /* Any template <>'s that we have seen thus far are not referring to a
706    function specialization.  */
707
708 void
709 reset_specialization (void)
710 {
711   processing_specialization = 0;
712   template_header_count = 0;
713 }
714
715 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
716    it was of the form template <>.  */
717
718 static void
719 note_template_header (int specialization)
720 {
721   processing_specialization = specialization;
722   template_header_count++;
723 }
724
725 /* We're beginning an explicit instantiation.  */
726
727 void
728 begin_explicit_instantiation (void)
729 {
730   gcc_assert (!processing_explicit_instantiation);
731   processing_explicit_instantiation = true;
732 }
733
734
735 void
736 end_explicit_instantiation (void)
737 {
738   gcc_assert (processing_explicit_instantiation);
739   processing_explicit_instantiation = false;
740 }
741
742 /* An explicit specialization or partial specialization TMPL is being
743    declared.  Check that the namespace in which the specialization is
744    occurring is permissible.  Returns false iff it is invalid to
745    specialize TMPL in the current namespace.  */
746
747 static bool
748 check_specialization_namespace (tree tmpl)
749 {
750   tree tpl_ns = decl_namespace_context (tmpl);
751
752   /* [tmpl.expl.spec]
753
754      An explicit specialization shall be declared in the namespace of
755      which the template is a member, or, for member templates, in the
756      namespace of which the enclosing class or enclosing class
757      template is a member.  An explicit specialization of a member
758      function, member class or static data member of a class template
759      shall be declared in the namespace of which the class template is
760      a member.  */
761   if (current_scope() != DECL_CONTEXT (tmpl)
762       && !at_namespace_scope_p ())
763     {
764       error ("specialization of %qD must appear at namespace scope", tmpl);
765       return false;
766     }
767   if (is_associated_namespace (current_namespace, tpl_ns))
768     /* Same or super-using namespace.  */
769     return true;
770   else
771     {
772       permerror (input_location, "specialization of %qD in different namespace", tmpl);
773       permerror (input_location, "  from definition of %q+#D", tmpl);
774       return false;
775     }
776 }
777
778 /* SPEC is an explicit instantiation.  Check that it is valid to
779    perform this explicit instantiation in the current namespace.  */
780
781 static void
782 check_explicit_instantiation_namespace (tree spec)
783 {
784   tree ns;
785
786   /* DR 275: An explicit instantiation shall appear in an enclosing
787      namespace of its template.  */
788   ns = decl_namespace_context (spec);
789   if (!is_ancestor (current_namespace, ns))
790     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
791                "(which does not enclose namespace %qD)",
792                spec, current_namespace, ns);
793 }
794
795 /* The TYPE is being declared.  If it is a template type, that means it
796    is a partial specialization.  Do appropriate error-checking.  */
797
798 tree
799 maybe_process_partial_specialization (tree type)
800 {
801   tree context;
802
803   if (type == error_mark_node)
804     return error_mark_node;
805
806   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
807     {
808       error ("name of class shadows template template parameter %qD",
809              TYPE_NAME (type));
810       return error_mark_node;
811     }
812
813   context = TYPE_CONTEXT (type);
814
815   if ((CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
816       /* Consider non-class instantiations of alias templates as
817          well.  */
818       || (TYPE_P (type)
819           && TYPE_TEMPLATE_INFO (type)
820           && DECL_LANG_SPECIFIC (TYPE_NAME (type))
821           && DECL_USE_TEMPLATE (TYPE_NAME (type))))
822     {
823       /* This is for ordinary explicit specialization and partial
824          specialization of a template class such as:
825
826            template <> class C<int>;
827
828          or:
829
830            template <class T> class C<T*>;
831
832          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
833
834       if (CLASS_TYPE_P (type)
835           && CLASSTYPE_IMPLICIT_INSTANTIATION (type)
836           && !COMPLETE_TYPE_P (type))
837         {
838           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
839           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
840           if (processing_template_decl)
841             {
842               if (push_template_decl (TYPE_MAIN_DECL (type))
843                   == error_mark_node)
844                 return error_mark_node;
845             }
846         }
847       else if (CLASS_TYPE_P (type)
848                && CLASSTYPE_TEMPLATE_INSTANTIATION (type))
849         error ("specialization of %qT after instantiation", type);
850
851       if (DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
852         {
853           error ("partial specialization of alias template %qD",
854                  TYPE_TI_TEMPLATE (type));
855           return error_mark_node;
856         }
857     }
858   else if (CLASS_TYPE_P (type)
859            && !CLASSTYPE_USE_TEMPLATE (type)
860            && CLASSTYPE_TEMPLATE_INFO (type)
861            && context && CLASS_TYPE_P (context)
862            && CLASSTYPE_TEMPLATE_INFO (context))
863     {
864       /* This is for an explicit specialization of member class
865          template according to [temp.expl.spec/18]:
866
867            template <> template <class U> class C<int>::D;
868
869          The context `C<int>' must be an implicit instantiation.
870          Otherwise this is just a member class template declared
871          earlier like:
872
873            template <> class C<int> { template <class U> class D; };
874            template <> template <class U> class C<int>::D;
875
876          In the first case, `C<int>::D' is a specialization of `C<T>::D'
877          while in the second case, `C<int>::D' is a primary template
878          and `C<T>::D' may not exist.  */
879
880       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
881           && !COMPLETE_TYPE_P (type))
882         {
883           tree t;
884           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
885
886           if (current_namespace
887               != decl_namespace_context (tmpl))
888             {
889               permerror (input_location, "specializing %q#T in different namespace", type);
890               permerror (input_location, "  from definition of %q+#D", tmpl);
891             }
892
893           /* Check for invalid specialization after instantiation:
894
895                template <> template <> class C<int>::D<int>;
896                template <> template <class U> class C<int>::D;  */
897
898           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
899                t; t = TREE_CHAIN (t))
900             {
901               tree inst = TREE_VALUE (t);
902               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
903                 {
904                   /* We already have a full specialization of this partial
905                      instantiation.  Reassign it to the new member
906                      specialization template.  */
907                   spec_entry elt;
908                   spec_entry *entry;
909                   void **slot;
910
911                   elt.tmpl = most_general_template (tmpl);
912                   elt.args = CLASSTYPE_TI_ARGS (inst);
913                   elt.spec = inst;
914
915                   htab_remove_elt (type_specializations, &elt);
916
917                   elt.tmpl = tmpl;
918                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
919
920                   slot = htab_find_slot (type_specializations, &elt, INSERT);
921                   entry = ggc_alloc_spec_entry ();
922                   *entry = elt;
923                   *slot = entry;
924                 }
925               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
926                 /* But if we've had an implicit instantiation, that's a
927                    problem ([temp.expl.spec]/6).  */
928                 error ("specialization %qT after instantiation %qT",
929                        type, inst);
930             }
931
932           /* Mark TYPE as a specialization.  And as a result, we only
933              have one level of template argument for the innermost
934              class template.  */
935           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
936           CLASSTYPE_TI_ARGS (type)
937             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
938         }
939     }
940   else if (processing_specialization)
941     {
942        /* Someday C++0x may allow for enum template specialization.  */
943       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
944           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
945         pedwarn (input_location, OPT_pedantic, "template specialization "
946                  "of %qD not allowed by ISO C++", type);
947       else
948         {
949           error ("explicit specialization of non-template %qT", type);
950           return error_mark_node;
951         }
952     }
953
954   return type;
955 }
956
957 /* Returns nonzero if we can optimize the retrieval of specializations
958    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
959    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
960
961 static inline bool
962 optimize_specialization_lookup_p (tree tmpl)
963 {
964   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
965           && DECL_CLASS_SCOPE_P (tmpl)
966           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
967              parameter.  */
968           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
969           /* The optimized lookup depends on the fact that the
970              template arguments for the member function template apply
971              purely to the containing class, which is not true if the
972              containing class is an explicit or partial
973              specialization.  */
974           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
975           && !DECL_MEMBER_TEMPLATE_P (tmpl)
976           && !DECL_CONV_FN_P (tmpl)
977           /* It is possible to have a template that is not a member
978              template and is not a member of a template class:
979
980              template <typename T>
981              struct S { friend A::f(); };
982
983              Here, the friend function is a template, but the context does
984              not have template information.  The optimized lookup relies
985              on having ARGS be the template arguments for both the class
986              and the function template.  */
987           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
988 }
989
990 /* Retrieve the specialization (in the sense of [temp.spec] - a
991    specialization is either an instantiation or an explicit
992    specialization) of TMPL for the given template ARGS.  If there is
993    no such specialization, return NULL_TREE.  The ARGS are a vector of
994    arguments, or a vector of vectors of arguments, in the case of
995    templates with more than one level of parameters.
996
997    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
998    then we search for a partial specialization matching ARGS.  This
999    parameter is ignored if TMPL is not a class template.  */
1000
1001 static tree
1002 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1003 {
1004   if (args == error_mark_node)
1005     return NULL_TREE;
1006
1007   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1008
1009   /* There should be as many levels of arguments as there are
1010      levels of parameters.  */
1011   gcc_assert (TMPL_ARGS_DEPTH (args)
1012               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
1013
1014   if (optimize_specialization_lookup_p (tmpl))
1015     {
1016       tree class_template;
1017       tree class_specialization;
1018       VEC(tree,gc) *methods;
1019       tree fns;
1020       int idx;
1021
1022       /* The template arguments actually apply to the containing
1023          class.  Find the class specialization with those
1024          arguments.  */
1025       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1026       class_specialization
1027         = retrieve_specialization (class_template, args, 0);
1028       if (!class_specialization)
1029         return NULL_TREE;
1030       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1031          for the specialization.  */
1032       idx = class_method_index_for_fn (class_specialization, tmpl);
1033       if (idx == -1)
1034         return NULL_TREE;
1035       /* Iterate through the methods with the indicated name, looking
1036          for the one that has an instance of TMPL.  */
1037       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1038       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1039         {
1040           tree fn = OVL_CURRENT (fns);
1041           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1042               /* using-declarations can add base methods to the method vec,
1043                  and we don't want those here.  */
1044               && DECL_CONTEXT (fn) == class_specialization)
1045             return fn;
1046         }
1047       return NULL_TREE;
1048     }
1049   else
1050     {
1051       spec_entry *found;
1052       spec_entry elt;
1053       htab_t specializations;
1054
1055       elt.tmpl = tmpl;
1056       elt.args = args;
1057       elt.spec = NULL_TREE;
1058
1059       if (DECL_CLASS_TEMPLATE_P (tmpl))
1060         specializations = type_specializations;
1061       else
1062         specializations = decl_specializations;
1063
1064       if (hash == 0)
1065         hash = hash_specialization (&elt);
1066       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1067       if (found)
1068         return found->spec;
1069     }
1070
1071   return NULL_TREE;
1072 }
1073
1074 /* Like retrieve_specialization, but for local declarations.  */
1075
1076 static tree
1077 retrieve_local_specialization (tree tmpl)
1078 {
1079   tree spec;
1080
1081   if (local_specializations == NULL)
1082     return NULL_TREE;
1083
1084   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1085                                      htab_hash_pointer (tmpl));
1086   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1087 }
1088
1089 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1090
1091 int
1092 is_specialization_of (tree decl, tree tmpl)
1093 {
1094   tree t;
1095
1096   if (TREE_CODE (decl) == FUNCTION_DECL)
1097     {
1098       for (t = decl;
1099            t != NULL_TREE;
1100            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1101         if (t == tmpl)
1102           return 1;
1103     }
1104   else
1105     {
1106       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1107
1108       for (t = TREE_TYPE (decl);
1109            t != NULL_TREE;
1110            t = CLASSTYPE_USE_TEMPLATE (t)
1111              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1112         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1113           return 1;
1114     }
1115
1116   return 0;
1117 }
1118
1119 /* Returns nonzero iff DECL is a specialization of friend declaration
1120    FRIEND_DECL according to [temp.friend].  */
1121
1122 bool
1123 is_specialization_of_friend (tree decl, tree friend_decl)
1124 {
1125   bool need_template = true;
1126   int template_depth;
1127
1128   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1129               || TREE_CODE (decl) == TYPE_DECL);
1130
1131   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1132      of a template class, we want to check if DECL is a specialization
1133      if this.  */
1134   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1135       && DECL_TEMPLATE_INFO (friend_decl)
1136       && !DECL_USE_TEMPLATE (friend_decl))
1137     {
1138       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1139       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1140       need_template = false;
1141     }
1142   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1143            && !PRIMARY_TEMPLATE_P (friend_decl))
1144     need_template = false;
1145
1146   /* There is nothing to do if this is not a template friend.  */
1147   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1148     return false;
1149
1150   if (is_specialization_of (decl, friend_decl))
1151     return true;
1152
1153   /* [temp.friend/6]
1154      A member of a class template may be declared to be a friend of a
1155      non-template class.  In this case, the corresponding member of
1156      every specialization of the class template is a friend of the
1157      class granting friendship.
1158
1159      For example, given a template friend declaration
1160
1161        template <class T> friend void A<T>::f();
1162
1163      the member function below is considered a friend
1164
1165        template <> struct A<int> {
1166          void f();
1167        };
1168
1169      For this type of template friend, TEMPLATE_DEPTH below will be
1170      nonzero.  To determine if DECL is a friend of FRIEND, we first
1171      check if the enclosing class is a specialization of another.  */
1172
1173   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1174   if (template_depth
1175       && DECL_CLASS_SCOPE_P (decl)
1176       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1177                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1178     {
1179       /* Next, we check the members themselves.  In order to handle
1180          a few tricky cases, such as when FRIEND_DECL's are
1181
1182            template <class T> friend void A<T>::g(T t);
1183            template <class T> template <T t> friend void A<T>::h();
1184
1185          and DECL's are
1186
1187            void A<int>::g(int);
1188            template <int> void A<int>::h();
1189
1190          we need to figure out ARGS, the template arguments from
1191          the context of DECL.  This is required for template substitution
1192          of `T' in the function parameter of `g' and template parameter
1193          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1194
1195       tree context = DECL_CONTEXT (decl);
1196       tree args = NULL_TREE;
1197       int current_depth = 0;
1198
1199       while (current_depth < template_depth)
1200         {
1201           if (CLASSTYPE_TEMPLATE_INFO (context))
1202             {
1203               if (current_depth == 0)
1204                 args = TYPE_TI_ARGS (context);
1205               else
1206                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1207               current_depth++;
1208             }
1209           context = TYPE_CONTEXT (context);
1210         }
1211
1212       if (TREE_CODE (decl) == FUNCTION_DECL)
1213         {
1214           bool is_template;
1215           tree friend_type;
1216           tree decl_type;
1217           tree friend_args_type;
1218           tree decl_args_type;
1219
1220           /* Make sure that both DECL and FRIEND_DECL are templates or
1221              non-templates.  */
1222           is_template = DECL_TEMPLATE_INFO (decl)
1223                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1224           if (need_template ^ is_template)
1225             return false;
1226           else if (is_template)
1227             {
1228               /* If both are templates, check template parameter list.  */
1229               tree friend_parms
1230                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1231                                          args, tf_none);
1232               if (!comp_template_parms
1233                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1234                       friend_parms))
1235                 return false;
1236
1237               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1238             }
1239           else
1240             decl_type = TREE_TYPE (decl);
1241
1242           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1243                                               tf_none, NULL_TREE);
1244           if (friend_type == error_mark_node)
1245             return false;
1246
1247           /* Check if return types match.  */
1248           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1249             return false;
1250
1251           /* Check if function parameter types match, ignoring the
1252              `this' parameter.  */
1253           friend_args_type = TYPE_ARG_TYPES (friend_type);
1254           decl_args_type = TYPE_ARG_TYPES (decl_type);
1255           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1256             friend_args_type = TREE_CHAIN (friend_args_type);
1257           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1258             decl_args_type = TREE_CHAIN (decl_args_type);
1259
1260           return compparms (decl_args_type, friend_args_type);
1261         }
1262       else
1263         {
1264           /* DECL is a TYPE_DECL */
1265           bool is_template;
1266           tree decl_type = TREE_TYPE (decl);
1267
1268           /* Make sure that both DECL and FRIEND_DECL are templates or
1269              non-templates.  */
1270           is_template
1271             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1272               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1273
1274           if (need_template ^ is_template)
1275             return false;
1276           else if (is_template)
1277             {
1278               tree friend_parms;
1279               /* If both are templates, check the name of the two
1280                  TEMPLATE_DECL's first because is_friend didn't.  */
1281               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1282                   != DECL_NAME (friend_decl))
1283                 return false;
1284
1285               /* Now check template parameter list.  */
1286               friend_parms
1287                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1288                                          args, tf_none);
1289               return comp_template_parms
1290                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1291                  friend_parms);
1292             }
1293           else
1294             return (DECL_NAME (decl)
1295                     == DECL_NAME (friend_decl));
1296         }
1297     }
1298   return false;
1299 }
1300
1301 /* Register the specialization SPEC as a specialization of TMPL with
1302    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1303    is actually just a friend declaration.  Returns SPEC, or an
1304    equivalent prior declaration, if available.  */
1305
1306 static tree
1307 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1308                          hashval_t hash)
1309 {
1310   tree fn;
1311   void **slot = NULL;
1312   spec_entry elt;
1313
1314   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1315
1316   if (TREE_CODE (spec) == FUNCTION_DECL
1317       && uses_template_parms (DECL_TI_ARGS (spec)))
1318     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1319        register it; we want the corresponding TEMPLATE_DECL instead.
1320        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1321        the more obvious `uses_template_parms (spec)' to avoid problems
1322        with default function arguments.  In particular, given
1323        something like this:
1324
1325           template <class T> void f(T t1, T t = T())
1326
1327        the default argument expression is not substituted for in an
1328        instantiation unless and until it is actually needed.  */
1329     return spec;
1330
1331   if (optimize_specialization_lookup_p (tmpl))
1332     /* We don't put these specializations in the hash table, but we might
1333        want to give an error about a mismatch.  */
1334     fn = retrieve_specialization (tmpl, args, 0);
1335   else
1336     {
1337       elt.tmpl = tmpl;
1338       elt.args = args;
1339       elt.spec = spec;
1340
1341       if (hash == 0)
1342         hash = hash_specialization (&elt);
1343
1344       slot =
1345         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1346       if (*slot)
1347         fn = ((spec_entry *) *slot)->spec;
1348       else
1349         fn = NULL_TREE;
1350     }
1351
1352   /* We can sometimes try to re-register a specialization that we've
1353      already got.  In particular, regenerate_decl_from_template calls
1354      duplicate_decls which will update the specialization list.  But,
1355      we'll still get called again here anyhow.  It's more convenient
1356      to simply allow this than to try to prevent it.  */
1357   if (fn == spec)
1358     return spec;
1359   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1360     {
1361       if (DECL_TEMPLATE_INSTANTIATION (fn))
1362         {
1363           if (DECL_ODR_USED (fn)
1364               || DECL_EXPLICIT_INSTANTIATION (fn))
1365             {
1366               error ("specialization of %qD after instantiation",
1367                      fn);
1368               return error_mark_node;
1369             }
1370           else
1371             {
1372               tree clone;
1373               /* This situation should occur only if the first
1374                  specialization is an implicit instantiation, the
1375                  second is an explicit specialization, and the
1376                  implicit instantiation has not yet been used.  That
1377                  situation can occur if we have implicitly
1378                  instantiated a member function and then specialized
1379                  it later.
1380
1381                  We can also wind up here if a friend declaration that
1382                  looked like an instantiation turns out to be a
1383                  specialization:
1384
1385                    template <class T> void foo(T);
1386                    class S { friend void foo<>(int) };
1387                    template <> void foo(int);
1388
1389                  We transform the existing DECL in place so that any
1390                  pointers to it become pointers to the updated
1391                  declaration.
1392
1393                  If there was a definition for the template, but not
1394                  for the specialization, we want this to look as if
1395                  there were no definition, and vice versa.  */
1396               DECL_INITIAL (fn) = NULL_TREE;
1397               duplicate_decls (spec, fn, is_friend);
1398               /* The call to duplicate_decls will have applied
1399                  [temp.expl.spec]:
1400
1401                    An explicit specialization of a function template
1402                    is inline only if it is explicitly declared to be,
1403                    and independently of whether its function template
1404                    is.
1405
1406                 to the primary function; now copy the inline bits to
1407                 the various clones.  */
1408               FOR_EACH_CLONE (clone, fn)
1409                 {
1410                   DECL_DECLARED_INLINE_P (clone)
1411                     = DECL_DECLARED_INLINE_P (fn);
1412                   DECL_SOURCE_LOCATION (clone)
1413                     = DECL_SOURCE_LOCATION (fn);
1414                 }
1415               check_specialization_namespace (fn);
1416
1417               return fn;
1418             }
1419         }
1420       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1421         {
1422           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1423             /* Dup decl failed, but this is a new definition. Set the
1424                line number so any errors match this new
1425                definition.  */
1426             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1427
1428           return fn;
1429         }
1430     }
1431   else if (fn)
1432     return duplicate_decls (spec, fn, is_friend);
1433
1434   /* A specialization must be declared in the same namespace as the
1435      template it is specializing.  */
1436   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1437       && !check_specialization_namespace (tmpl))
1438     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1439
1440   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1441     {
1442       spec_entry *entry = ggc_alloc_spec_entry ();
1443       gcc_assert (tmpl && args && spec);
1444       *entry = elt;
1445       *slot = entry;
1446       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1447           && PRIMARY_TEMPLATE_P (tmpl)
1448           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1449         /* TMPL is a forward declaration of a template function; keep a list
1450            of all specializations in case we need to reassign them to a friend
1451            template later in tsubst_friend_function.  */
1452         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1453           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1454     }
1455
1456   return spec;
1457 }
1458
1459 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1460    TMPL and ARGS members, ignores SPEC.  */
1461
1462 static int
1463 eq_specializations (const void *p1, const void *p2)
1464 {
1465   const spec_entry *e1 = (const spec_entry *)p1;
1466   const spec_entry *e2 = (const spec_entry *)p2;
1467
1468   return (e1->tmpl == e2->tmpl
1469           && comp_template_args (e1->args, e2->args));
1470 }
1471
1472 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1473
1474 static hashval_t
1475 hash_tmpl_and_args (tree tmpl, tree args)
1476 {
1477   hashval_t val = DECL_UID (tmpl);
1478   return iterative_hash_template_arg (args, val);
1479 }
1480
1481 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1482    ignoring SPEC.  */
1483
1484 static hashval_t
1485 hash_specialization (const void *p)
1486 {
1487   const spec_entry *e = (const spec_entry *)p;
1488   return hash_tmpl_and_args (e->tmpl, e->args);
1489 }
1490
1491 /* Recursively calculate a hash value for a template argument ARG, for use
1492    in the hash tables of template specializations.  */
1493
1494 hashval_t
1495 iterative_hash_template_arg (tree arg, hashval_t val)
1496 {
1497   unsigned HOST_WIDE_INT i;
1498   enum tree_code code;
1499   char tclass;
1500
1501   if (arg == NULL_TREE)
1502     return iterative_hash_object (arg, val);
1503
1504   if (!TYPE_P (arg))
1505     STRIP_NOPS (arg);
1506
1507   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1508     /* We can get one of these when re-hashing a previous entry in the middle
1509        of substituting into a pack expansion.  Just look through it.  */
1510     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1511
1512   code = TREE_CODE (arg);
1513   tclass = TREE_CODE_CLASS (code);
1514
1515   val = iterative_hash_object (code, val);
1516
1517   switch (code)
1518     {
1519     case ERROR_MARK:
1520       return val;
1521
1522     case IDENTIFIER_NODE:
1523       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1524
1525     case TREE_VEC:
1526       {
1527         int i, len = TREE_VEC_LENGTH (arg);
1528         for (i = 0; i < len; ++i)
1529           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1530         return val;
1531       }
1532
1533     case TYPE_PACK_EXPANSION:
1534     case EXPR_PACK_EXPANSION:
1535       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1536       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1537
1538     case TYPE_ARGUMENT_PACK:
1539     case NONTYPE_ARGUMENT_PACK:
1540       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1541
1542     case TREE_LIST:
1543       for (; arg; arg = TREE_CHAIN (arg))
1544         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1545       return val;
1546
1547     case OVERLOAD:
1548       for (; arg; arg = OVL_NEXT (arg))
1549         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1550       return val;
1551
1552     case CONSTRUCTOR:
1553       {
1554         tree field, value;
1555         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1556           {
1557             val = iterative_hash_template_arg (field, val);
1558             val = iterative_hash_template_arg (value, val);
1559           }
1560         return val;
1561       }
1562
1563     case PARM_DECL:
1564       if (!DECL_ARTIFICIAL (arg))
1565         {
1566           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1567           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1568         }
1569       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1570
1571     case TARGET_EXPR:
1572       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1573
1574     case PTRMEM_CST:
1575       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1576       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1577
1578     case TEMPLATE_PARM_INDEX:
1579       val = iterative_hash_template_arg
1580         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1581       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1582       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1583
1584     case TRAIT_EXPR:
1585       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1586       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1587       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1588
1589     case BASELINK:
1590       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1591                                          val);
1592       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1593                                           val);
1594
1595     case MODOP_EXPR:
1596       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1597       code = TREE_CODE (TREE_OPERAND (arg, 1));
1598       val = iterative_hash_object (code, val);
1599       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1600
1601     case LAMBDA_EXPR:
1602       /* A lambda can't appear in a template arg, but don't crash on
1603          erroneous input.  */
1604       gcc_assert (seen_error ());
1605       return val;
1606
1607     case CAST_EXPR:
1608     case IMPLICIT_CONV_EXPR:
1609     case STATIC_CAST_EXPR:
1610     case REINTERPRET_CAST_EXPR:
1611     case CONST_CAST_EXPR:
1612     case DYNAMIC_CAST_EXPR:
1613     case NEW_EXPR:
1614       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1615       /* Now hash operands as usual.  */
1616       break;
1617
1618     default:
1619       break;
1620     }
1621
1622   switch (tclass)
1623     {
1624     case tcc_type:
1625       if (TYPE_CANONICAL (arg))
1626         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1627                                       val);
1628       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1629         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1630       /* Otherwise just compare the types during lookup.  */
1631       return val;
1632
1633     case tcc_declaration:
1634     case tcc_constant:
1635       return iterative_hash_expr (arg, val);
1636
1637     default:
1638       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1639       {
1640         unsigned n = cp_tree_operand_length (arg);
1641         for (i = 0; i < n; ++i)
1642           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1643         return val;
1644       }
1645     }
1646   gcc_unreachable ();
1647   return 0;
1648 }
1649
1650 /* Unregister the specialization SPEC as a specialization of TMPL.
1651    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1652    if the SPEC was listed as a specialization of TMPL.
1653
1654    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1655
1656 bool
1657 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1658 {
1659   spec_entry *entry;
1660   spec_entry elt;
1661
1662   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1663   elt.args = TI_ARGS (tinfo);
1664   elt.spec = NULL_TREE;
1665
1666   entry = (spec_entry *) htab_find (decl_specializations, &elt);
1667   if (entry != NULL)
1668     {
1669       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1670       gcc_assert (new_spec != NULL_TREE);
1671       entry->spec = new_spec;
1672       return 1;
1673     }
1674
1675   return 0;
1676 }
1677
1678 /* Compare an entry in the local specializations hash table P1 (which
1679    is really a pointer to a TREE_LIST) with P2 (which is really a
1680    DECL).  */
1681
1682 static int
1683 eq_local_specializations (const void *p1, const void *p2)
1684 {
1685   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1686 }
1687
1688 /* Hash P1, an entry in the local specializations table.  */
1689
1690 static hashval_t
1691 hash_local_specialization (const void* p1)
1692 {
1693   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1694 }
1695
1696 /* Like register_specialization, but for local declarations.  We are
1697    registering SPEC, an instantiation of TMPL.  */
1698
1699 static void
1700 register_local_specialization (tree spec, tree tmpl)
1701 {
1702   void **slot;
1703
1704   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1705                                    htab_hash_pointer (tmpl), INSERT);
1706   *slot = build_tree_list (spec, tmpl);
1707 }
1708
1709 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1710    specialized class.  */
1711
1712 bool
1713 explicit_class_specialization_p (tree type)
1714 {
1715   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1716     return false;
1717   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1718 }
1719
1720 /* Print the list of functions at FNS, going through all the overloads
1721    for each element of the list.  Alternatively, FNS can not be a
1722    TREE_LIST, in which case it will be printed together with all the
1723    overloads.
1724
1725    MORE and *STR should respectively be FALSE and NULL when the function
1726    is called from the outside.  They are used internally on recursive
1727    calls.  print_candidates manages the two parameters and leaves NULL
1728    in *STR when it ends.  */
1729
1730 static void
1731 print_candidates_1 (tree fns, bool more, const char **str)
1732 {
1733   tree fn, fn2;
1734   char *spaces = NULL;
1735
1736   for (fn = fns; fn; fn = OVL_NEXT (fn))
1737     if (TREE_CODE (fn) == TREE_LIST)
1738       {
1739         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1740           print_candidates_1 (TREE_VALUE (fn2),
1741                               TREE_CHAIN (fn2) || more, str);
1742       }
1743     else
1744       {
1745         if (!*str)
1746           {
1747             /* Pick the prefix string.  */
1748             if (!more && !OVL_NEXT (fns))
1749               {
1750                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1751                 continue;
1752               }
1753
1754             *str = _("candidates are:");
1755             spaces = get_spaces (*str);
1756           }
1757         error ("%s %+#D", *str, OVL_CURRENT (fn));
1758         *str = spaces ? spaces : *str;
1759       }
1760
1761   if (!more)
1762     {
1763       free (spaces);
1764       *str = NULL;
1765     }
1766 }
1767
1768 /* Print the list of candidate FNS in an error message.  FNS can also
1769    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1770
1771 void
1772 print_candidates (tree fns)
1773 {
1774   const char *str = NULL;
1775   print_candidates_1 (fns, false, &str);
1776   gcc_assert (str == NULL);
1777 }
1778
1779 /* Returns the template (one of the functions given by TEMPLATE_ID)
1780    which can be specialized to match the indicated DECL with the
1781    explicit template args given in TEMPLATE_ID.  The DECL may be
1782    NULL_TREE if none is available.  In that case, the functions in
1783    TEMPLATE_ID are non-members.
1784
1785    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1786    specialization of a member template.
1787
1788    The TEMPLATE_COUNT is the number of references to qualifying
1789    template classes that appeared in the name of the function. See
1790    check_explicit_specialization for a more accurate description.
1791
1792    TSK indicates what kind of template declaration (if any) is being
1793    declared.  TSK_TEMPLATE indicates that the declaration given by
1794    DECL, though a FUNCTION_DECL, has template parameters, and is
1795    therefore a template function.
1796
1797    The template args (those explicitly specified and those deduced)
1798    are output in a newly created vector *TARGS_OUT.
1799
1800    If it is impossible to determine the result, an error message is
1801    issued.  The error_mark_node is returned to indicate failure.  */
1802
1803 static tree
1804 determine_specialization (tree template_id,
1805                           tree decl,
1806                           tree* targs_out,
1807                           int need_member_template,
1808                           int template_count,
1809                           tmpl_spec_kind tsk)
1810 {
1811   tree fns;
1812   tree targs;
1813   tree explicit_targs;
1814   tree candidates = NULL_TREE;
1815   /* A TREE_LIST of templates of which DECL may be a specialization.
1816      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1817      corresponding TREE_PURPOSE is the set of template arguments that,
1818      when used to instantiate the template, would produce a function
1819      with the signature of DECL.  */
1820   tree templates = NULL_TREE;
1821   int header_count;
1822   cp_binding_level *b;
1823
1824   *targs_out = NULL_TREE;
1825
1826   if (template_id == error_mark_node || decl == error_mark_node)
1827     return error_mark_node;
1828
1829   fns = TREE_OPERAND (template_id, 0);
1830   explicit_targs = TREE_OPERAND (template_id, 1);
1831
1832   if (fns == error_mark_node)
1833     return error_mark_node;
1834
1835   /* Check for baselinks.  */
1836   if (BASELINK_P (fns))
1837     fns = BASELINK_FUNCTIONS (fns);
1838
1839   if (!is_overloaded_fn (fns))
1840     {
1841       error ("%qD is not a function template", fns);
1842       return error_mark_node;
1843     }
1844
1845   /* Count the number of template headers specified for this
1846      specialization.  */
1847   header_count = 0;
1848   for (b = current_binding_level;
1849        b->kind == sk_template_parms;
1850        b = b->level_chain)
1851     ++header_count;
1852
1853   for (; fns; fns = OVL_NEXT (fns))
1854     {
1855       tree fn = OVL_CURRENT (fns);
1856
1857       if (TREE_CODE (fn) == TEMPLATE_DECL)
1858         {
1859           tree decl_arg_types;
1860           tree fn_arg_types;
1861           tree insttype;
1862
1863           /* In case of explicit specialization, we need to check if
1864              the number of template headers appearing in the specialization
1865              is correct. This is usually done in check_explicit_specialization,
1866              but the check done there cannot be exhaustive when specializing
1867              member functions. Consider the following code:
1868
1869              template <> void A<int>::f(int);
1870              template <> template <> void A<int>::f(int);
1871
1872              Assuming that A<int> is not itself an explicit specialization
1873              already, the first line specializes "f" which is a non-template
1874              member function, whilst the second line specializes "f" which
1875              is a template member function. So both lines are syntactically
1876              correct, and check_explicit_specialization does not reject
1877              them.
1878
1879              Here, we can do better, as we are matching the specialization
1880              against the declarations. We count the number of template
1881              headers, and we check if they match TEMPLATE_COUNT + 1
1882              (TEMPLATE_COUNT is the number of qualifying template classes,
1883              plus there must be another header for the member template
1884              itself).
1885
1886              Notice that if header_count is zero, this is not a
1887              specialization but rather a template instantiation, so there
1888              is no check we can perform here.  */
1889           if (header_count && header_count != template_count + 1)
1890             continue;
1891
1892           /* Check that the number of template arguments at the
1893              innermost level for DECL is the same as for FN.  */
1894           if (current_binding_level->kind == sk_template_parms
1895               && !current_binding_level->explicit_spec_p
1896               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1897                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1898                                       (current_template_parms))))
1899             continue;
1900
1901           /* DECL might be a specialization of FN.  */
1902           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1903           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1904
1905           /* For a non-static member function, we need to make sure
1906              that the const qualification is the same.  Since
1907              get_bindings does not try to merge the "this" parameter,
1908              we must do the comparison explicitly.  */
1909           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1910               && !same_type_p (TREE_VALUE (fn_arg_types),
1911                                TREE_VALUE (decl_arg_types)))
1912             continue;
1913
1914           /* Skip the "this" parameter and, for constructors of
1915              classes with virtual bases, the VTT parameter.  A
1916              full specialization of a constructor will have a VTT
1917              parameter, but a template never will.  */ 
1918           decl_arg_types 
1919             = skip_artificial_parms_for (decl, decl_arg_types);
1920           fn_arg_types 
1921             = skip_artificial_parms_for (fn, fn_arg_types);
1922
1923           /* Check that the number of function parameters matches.
1924              For example,
1925                template <class T> void f(int i = 0);
1926                template <> void f<int>();
1927              The specialization f<int> is invalid but is not caught
1928              by get_bindings below.  */
1929           if (cxx_dialect < cxx11
1930               && list_length (fn_arg_types) != list_length (decl_arg_types))
1931             continue;
1932
1933           /* Function templates cannot be specializations; there are
1934              no partial specializations of functions.  Therefore, if
1935              the type of DECL does not match FN, there is no
1936              match.  */
1937           if (tsk == tsk_template)
1938             {
1939               if (compparms (fn_arg_types, decl_arg_types))
1940                 candidates = tree_cons (NULL_TREE, fn, candidates);
1941               continue;
1942             }
1943
1944           /* See whether this function might be a specialization of this
1945              template.  */
1946           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1947
1948           if (!targs)
1949             /* We cannot deduce template arguments that when used to
1950                specialize TMPL will produce DECL.  */
1951             continue;
1952
1953           if (cxx_dialect >= cxx11)
1954             {
1955               /* Make sure that the deduced arguments actually work.  */
1956               insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
1957               if (insttype == error_mark_node)
1958                 continue;
1959               fn_arg_types
1960                 = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
1961               if (!compparms (fn_arg_types, decl_arg_types))
1962                 continue;
1963             }
1964
1965           /* Save this template, and the arguments deduced.  */
1966           templates = tree_cons (targs, fn, templates);
1967         }
1968       else if (need_member_template)
1969         /* FN is an ordinary member function, and we need a
1970            specialization of a member template.  */
1971         ;
1972       else if (TREE_CODE (fn) != FUNCTION_DECL)
1973         /* We can get IDENTIFIER_NODEs here in certain erroneous
1974            cases.  */
1975         ;
1976       else if (!DECL_FUNCTION_MEMBER_P (fn))
1977         /* This is just an ordinary non-member function.  Nothing can
1978            be a specialization of that.  */
1979         ;
1980       else if (DECL_ARTIFICIAL (fn))
1981         /* Cannot specialize functions that are created implicitly.  */
1982         ;
1983       else
1984         {
1985           tree decl_arg_types;
1986
1987           /* This is an ordinary member function.  However, since
1988              we're here, we can assume it's enclosing class is a
1989              template class.  For example,
1990
1991                template <typename T> struct S { void f(); };
1992                template <> void S<int>::f() {}
1993
1994              Here, S<int>::f is a non-template, but S<int> is a
1995              template class.  If FN has the same type as DECL, we
1996              might be in business.  */
1997
1998           if (!DECL_TEMPLATE_INFO (fn))
1999             /* Its enclosing class is an explicit specialization
2000                of a template class.  This is not a candidate.  */
2001             continue;
2002
2003           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2004                             TREE_TYPE (TREE_TYPE (fn))))
2005             /* The return types differ.  */
2006             continue;
2007
2008           /* Adjust the type of DECL in case FN is a static member.  */
2009           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2010           if (DECL_STATIC_FUNCTION_P (fn)
2011               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2012             decl_arg_types = TREE_CHAIN (decl_arg_types);
2013
2014           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2015                          decl_arg_types))
2016             /* They match!  */
2017             candidates = tree_cons (NULL_TREE, fn, candidates);
2018         }
2019     }
2020
2021   if (templates && TREE_CHAIN (templates))
2022     {
2023       /* We have:
2024
2025            [temp.expl.spec]
2026
2027            It is possible for a specialization with a given function
2028            signature to be instantiated from more than one function
2029            template.  In such cases, explicit specification of the
2030            template arguments must be used to uniquely identify the
2031            function template specialization being specialized.
2032
2033          Note that here, there's no suggestion that we're supposed to
2034          determine which of the candidate templates is most
2035          specialized.  However, we, also have:
2036
2037            [temp.func.order]
2038
2039            Partial ordering of overloaded function template
2040            declarations is used in the following contexts to select
2041            the function template to which a function template
2042            specialization refers:
2043
2044            -- when an explicit specialization refers to a function
2045               template.
2046
2047          So, we do use the partial ordering rules, at least for now.
2048          This extension can only serve to make invalid programs valid,
2049          so it's safe.  And, there is strong anecdotal evidence that
2050          the committee intended the partial ordering rules to apply;
2051          the EDG front end has that behavior, and John Spicer claims
2052          that the committee simply forgot to delete the wording in
2053          [temp.expl.spec].  */
2054       tree tmpl = most_specialized_instantiation (templates);
2055       if (tmpl != error_mark_node)
2056         {
2057           templates = tmpl;
2058           TREE_CHAIN (templates) = NULL_TREE;
2059         }
2060     }
2061
2062   if (templates == NULL_TREE && candidates == NULL_TREE)
2063     {
2064       error ("template-id %qD for %q+D does not match any template "
2065              "declaration", template_id, decl);
2066       if (header_count && header_count != template_count + 1)
2067         inform (input_location, "saw %d %<template<>%>, need %d for "
2068                 "specializing a member function template",
2069                 header_count, template_count + 1);
2070       return error_mark_node;
2071     }
2072   else if ((templates && TREE_CHAIN (templates))
2073            || (candidates && TREE_CHAIN (candidates))
2074            || (templates && candidates))
2075     {
2076       error ("ambiguous template specialization %qD for %q+D",
2077              template_id, decl);
2078       candidates = chainon (candidates, templates);
2079       print_candidates (candidates);
2080       return error_mark_node;
2081     }
2082
2083   /* We have one, and exactly one, match.  */
2084   if (candidates)
2085     {
2086       tree fn = TREE_VALUE (candidates);
2087       *targs_out = copy_node (DECL_TI_ARGS (fn));
2088       /* DECL is a re-declaration or partial instantiation of a template
2089          function.  */
2090       if (TREE_CODE (fn) == TEMPLATE_DECL)
2091         return fn;
2092       /* It was a specialization of an ordinary member function in a
2093          template class.  */
2094       return DECL_TI_TEMPLATE (fn);
2095     }
2096
2097   /* It was a specialization of a template.  */
2098   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2099   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2100     {
2101       *targs_out = copy_node (targs);
2102       SET_TMPL_ARGS_LEVEL (*targs_out,
2103                            TMPL_ARGS_DEPTH (*targs_out),
2104                            TREE_PURPOSE (templates));
2105     }
2106   else
2107     *targs_out = TREE_PURPOSE (templates);
2108   return TREE_VALUE (templates);
2109 }
2110
2111 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2112    but with the default argument values filled in from those in the
2113    TMPL_TYPES.  */
2114
2115 static tree
2116 copy_default_args_to_explicit_spec_1 (tree spec_types,
2117                                       tree tmpl_types)
2118 {
2119   tree new_spec_types;
2120
2121   if (!spec_types)
2122     return NULL_TREE;
2123
2124   if (spec_types == void_list_node)
2125     return void_list_node;
2126
2127   /* Substitute into the rest of the list.  */
2128   new_spec_types =
2129     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2130                                           TREE_CHAIN (tmpl_types));
2131
2132   /* Add the default argument for this parameter.  */
2133   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2134                          TREE_VALUE (spec_types),
2135                          new_spec_types);
2136 }
2137
2138 /* DECL is an explicit specialization.  Replicate default arguments
2139    from the template it specializes.  (That way, code like:
2140
2141      template <class T> void f(T = 3);
2142      template <> void f(double);
2143      void g () { f (); }
2144
2145    works, as required.)  An alternative approach would be to look up
2146    the correct default arguments at the call-site, but this approach
2147    is consistent with how implicit instantiations are handled.  */
2148
2149 static void
2150 copy_default_args_to_explicit_spec (tree decl)
2151 {
2152   tree tmpl;
2153   tree spec_types;
2154   tree tmpl_types;
2155   tree new_spec_types;
2156   tree old_type;
2157   tree new_type;
2158   tree t;
2159   tree object_type = NULL_TREE;
2160   tree in_charge = NULL_TREE;
2161   tree vtt = NULL_TREE;
2162
2163   /* See if there's anything we need to do.  */
2164   tmpl = DECL_TI_TEMPLATE (decl);
2165   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2166   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2167     if (TREE_PURPOSE (t))
2168       break;
2169   if (!t)
2170     return;
2171
2172   old_type = TREE_TYPE (decl);
2173   spec_types = TYPE_ARG_TYPES (old_type);
2174
2175   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2176     {
2177       /* Remove the this pointer, but remember the object's type for
2178          CV quals.  */
2179       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2180       spec_types = TREE_CHAIN (spec_types);
2181       tmpl_types = TREE_CHAIN (tmpl_types);
2182
2183       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2184         {
2185           /* DECL may contain more parameters than TMPL due to the extra
2186              in-charge parameter in constructors and destructors.  */
2187           in_charge = spec_types;
2188           spec_types = TREE_CHAIN (spec_types);
2189         }
2190       if (DECL_HAS_VTT_PARM_P (decl))
2191         {
2192           vtt = spec_types;
2193           spec_types = TREE_CHAIN (spec_types);
2194         }
2195     }
2196
2197   /* Compute the merged default arguments.  */
2198   new_spec_types =
2199     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2200
2201   /* Compute the new FUNCTION_TYPE.  */
2202   if (object_type)
2203     {
2204       if (vtt)
2205         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2206                                          TREE_VALUE (vtt),
2207                                          new_spec_types);
2208
2209       if (in_charge)
2210         /* Put the in-charge parameter back.  */
2211         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2212                                          TREE_VALUE (in_charge),
2213                                          new_spec_types);
2214
2215       new_type = build_method_type_directly (object_type,
2216                                              TREE_TYPE (old_type),
2217                                              new_spec_types);
2218     }
2219   else
2220     new_type = build_function_type (TREE_TYPE (old_type),
2221                                     new_spec_types);
2222   new_type = cp_build_type_attribute_variant (new_type,
2223                                               TYPE_ATTRIBUTES (old_type));
2224   new_type = build_exception_variant (new_type,
2225                                       TYPE_RAISES_EXCEPTIONS (old_type));
2226   TREE_TYPE (decl) = new_type;
2227 }
2228
2229 /* Check to see if the function just declared, as indicated in
2230    DECLARATOR, and in DECL, is a specialization of a function
2231    template.  We may also discover that the declaration is an explicit
2232    instantiation at this point.
2233
2234    Returns DECL, or an equivalent declaration that should be used
2235    instead if all goes well.  Issues an error message if something is
2236    amiss.  Returns error_mark_node if the error is not easily
2237    recoverable.
2238
2239    FLAGS is a bitmask consisting of the following flags:
2240
2241    2: The function has a definition.
2242    4: The function is a friend.
2243
2244    The TEMPLATE_COUNT is the number of references to qualifying
2245    template classes that appeared in the name of the function.  For
2246    example, in
2247
2248      template <class T> struct S { void f(); };
2249      void S<int>::f();
2250
2251    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2252    classes are not counted in the TEMPLATE_COUNT, so that in
2253
2254      template <class T> struct S {};
2255      template <> struct S<int> { void f(); }
2256      template <> void S<int>::f();
2257
2258    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2259    invalid; there should be no template <>.)
2260
2261    If the function is a specialization, it is marked as such via
2262    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2263    is set up correctly, and it is added to the list of specializations
2264    for that template.  */
2265
2266 tree
2267 check_explicit_specialization (tree declarator,
2268                                tree decl,
2269                                int template_count,
2270                                int flags)
2271 {
2272   int have_def = flags & 2;
2273   int is_friend = flags & 4;
2274   int specialization = 0;
2275   int explicit_instantiation = 0;
2276   int member_specialization = 0;
2277   tree ctype = DECL_CLASS_CONTEXT (decl);
2278   tree dname = DECL_NAME (decl);
2279   tmpl_spec_kind tsk;
2280
2281   if (is_friend)
2282     {
2283       if (!processing_specialization)
2284         tsk = tsk_none;
2285       else
2286         tsk = tsk_excessive_parms;
2287     }
2288   else
2289     tsk = current_tmpl_spec_kind (template_count);
2290
2291   switch (tsk)
2292     {
2293     case tsk_none:
2294       if (processing_specialization)
2295         {
2296           specialization = 1;
2297           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2298         }
2299       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2300         {
2301           if (is_friend)
2302             /* This could be something like:
2303
2304                template <class T> void f(T);
2305                class S { friend void f<>(int); }  */
2306             specialization = 1;
2307           else
2308             {
2309               /* This case handles bogus declarations like template <>
2310                  template <class T> void f<int>(); */
2311
2312               error ("template-id %qD in declaration of primary template",
2313                      declarator);
2314               return decl;
2315             }
2316         }
2317       break;
2318
2319     case tsk_invalid_member_spec:
2320       /* The error has already been reported in
2321          check_specialization_scope.  */
2322       return error_mark_node;
2323
2324     case tsk_invalid_expl_inst:
2325       error ("template parameter list used in explicit instantiation");
2326
2327       /* Fall through.  */
2328
2329     case tsk_expl_inst:
2330       if (have_def)
2331         error ("definition provided for explicit instantiation");
2332
2333       explicit_instantiation = 1;
2334       break;
2335
2336     case tsk_excessive_parms:
2337     case tsk_insufficient_parms:
2338       if (tsk == tsk_excessive_parms)
2339         error ("too many template parameter lists in declaration of %qD",
2340                decl);
2341       else if (template_header_count)
2342         error("too few template parameter lists in declaration of %qD", decl);
2343       else
2344         error("explicit specialization of %qD must be introduced by "
2345               "%<template <>%>", decl);
2346
2347       /* Fall through.  */
2348     case tsk_expl_spec:
2349       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2350       if (ctype)
2351         member_specialization = 1;
2352       else
2353         specialization = 1;
2354       break;
2355
2356     case tsk_template:
2357       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2358         {
2359           /* This case handles bogus declarations like template <>
2360              template <class T> void f<int>(); */
2361
2362           if (uses_template_parms (declarator))
2363             error ("function template partial specialization %qD "
2364                    "is not allowed", declarator);
2365           else
2366             error ("template-id %qD in declaration of primary template",
2367                    declarator);
2368           return decl;
2369         }
2370
2371       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2372         /* This is a specialization of a member template, without
2373            specialization the containing class.  Something like:
2374
2375              template <class T> struct S {
2376                template <class U> void f (U);
2377              };
2378              template <> template <class U> void S<int>::f(U) {}
2379
2380            That's a specialization -- but of the entire template.  */
2381         specialization = 1;
2382       break;
2383
2384     default:
2385       gcc_unreachable ();
2386     }
2387
2388   if (specialization || member_specialization)
2389     {
2390       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2391       for (; t; t = TREE_CHAIN (t))
2392         if (TREE_PURPOSE (t))
2393           {
2394             permerror (input_location, 
2395                        "default argument specified in explicit specialization");
2396             break;
2397           }
2398     }
2399
2400   if (specialization || member_specialization || explicit_instantiation)
2401     {
2402       tree tmpl = NULL_TREE;
2403       tree targs = NULL_TREE;
2404
2405       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2406       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2407         {
2408           tree fns;
2409
2410           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2411           if (ctype)
2412             fns = dname;
2413           else
2414             {
2415               /* If there is no class context, the explicit instantiation
2416                  must be at namespace scope.  */
2417               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2418
2419               /* Find the namespace binding, using the declaration
2420                  context.  */
2421               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2422                                            false, true);
2423               if (fns == error_mark_node || !is_overloaded_fn (fns))
2424                 {
2425                   error ("%qD is not a template function", dname);
2426                   fns = error_mark_node;
2427                 }
2428               else
2429                 {
2430                   tree fn = OVL_CURRENT (fns);
2431                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2432                                                 CP_DECL_CONTEXT (fn)))
2433                     error ("%qD is not declared in %qD",
2434                            decl, current_namespace);
2435                 }
2436             }
2437
2438           declarator = lookup_template_function (fns, NULL_TREE);
2439         }
2440
2441       if (declarator == error_mark_node)
2442         return error_mark_node;
2443
2444       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2445         {
2446           if (!explicit_instantiation)
2447             /* A specialization in class scope.  This is invalid,
2448                but the error will already have been flagged by
2449                check_specialization_scope.  */
2450             return error_mark_node;
2451           else
2452             {
2453               /* It's not valid to write an explicit instantiation in
2454                  class scope, e.g.:
2455
2456                    class C { template void f(); }
2457
2458                    This case is caught by the parser.  However, on
2459                    something like:
2460
2461                    template class C { void f(); };
2462
2463                    (which is invalid) we can get here.  The error will be
2464                    issued later.  */
2465               ;
2466             }
2467
2468           return decl;
2469         }
2470       else if (ctype != NULL_TREE
2471                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2472                    IDENTIFIER_NODE))
2473         {
2474           /* Find the list of functions in ctype that have the same
2475              name as the declared function.  */
2476           tree name = TREE_OPERAND (declarator, 0);
2477           tree fns = NULL_TREE;
2478           int idx;
2479
2480           if (constructor_name_p (name, ctype))
2481             {
2482               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2483
2484               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2485                   : !CLASSTYPE_DESTRUCTORS (ctype))
2486                 {
2487                   /* From [temp.expl.spec]:
2488
2489                      If such an explicit specialization for the member
2490                      of a class template names an implicitly-declared
2491                      special member function (clause _special_), the
2492                      program is ill-formed.
2493
2494                      Similar language is found in [temp.explicit].  */
2495                   error ("specialization of implicitly-declared special member function");
2496                   return error_mark_node;
2497                 }
2498
2499               name = is_constructor ? ctor_identifier : dtor_identifier;
2500             }
2501
2502           if (!DECL_CONV_FN_P (decl))
2503             {
2504               idx = lookup_fnfields_1 (ctype, name);
2505               if (idx >= 0)
2506                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2507             }
2508           else
2509             {
2510               VEC(tree,gc) *methods;
2511               tree ovl;
2512
2513               /* For a type-conversion operator, we cannot do a
2514                  name-based lookup.  We might be looking for `operator
2515                  int' which will be a specialization of `operator T'.
2516                  So, we find *all* the conversion operators, and then
2517                  select from them.  */
2518               fns = NULL_TREE;
2519
2520               methods = CLASSTYPE_METHOD_VEC (ctype);
2521               if (methods)
2522                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2523                      VEC_iterate (tree, methods, idx, ovl);
2524                      ++idx)
2525                   {
2526                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2527                       /* There are no more conversion functions.  */
2528                       break;
2529
2530                     /* Glue all these conversion functions together
2531                        with those we already have.  */
2532                     for (; ovl; ovl = OVL_NEXT (ovl))
2533                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2534                   }
2535             }
2536
2537           if (fns == NULL_TREE)
2538             {
2539               error ("no member function %qD declared in %qT", name, ctype);
2540               return error_mark_node;
2541             }
2542           else
2543             TREE_OPERAND (declarator, 0) = fns;
2544         }
2545
2546       /* Figure out what exactly is being specialized at this point.
2547          Note that for an explicit instantiation, even one for a
2548          member function, we cannot tell apriori whether the
2549          instantiation is for a member template, or just a member
2550          function of a template class.  Even if a member template is
2551          being instantiated, the member template arguments may be
2552          elided if they can be deduced from the rest of the
2553          declaration.  */
2554       tmpl = determine_specialization (declarator, decl,
2555                                        &targs,
2556                                        member_specialization,
2557                                        template_count,
2558                                        tsk);
2559
2560       if (!tmpl || tmpl == error_mark_node)
2561         /* We couldn't figure out what this declaration was
2562            specializing.  */
2563         return error_mark_node;
2564       else
2565         {
2566           tree gen_tmpl = most_general_template (tmpl);
2567
2568           if (explicit_instantiation)
2569             {
2570               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2571                  is done by do_decl_instantiation later.  */
2572
2573               int arg_depth = TMPL_ARGS_DEPTH (targs);
2574               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2575
2576               if (arg_depth > parm_depth)
2577                 {
2578                   /* If TMPL is not the most general template (for
2579                      example, if TMPL is a friend template that is
2580                      injected into namespace scope), then there will
2581                      be too many levels of TARGS.  Remove some of them
2582                      here.  */
2583                   int i;
2584                   tree new_targs;
2585
2586                   new_targs = make_tree_vec (parm_depth);
2587                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2588                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2589                       = TREE_VEC_ELT (targs, i);
2590                   targs = new_targs;
2591                 }
2592
2593               return instantiate_template (tmpl, targs, tf_error);
2594             }
2595
2596           /* If we thought that the DECL was a member function, but it
2597              turns out to be specializing a static member function,
2598              make DECL a static member function as well.  */
2599           if (DECL_STATIC_FUNCTION_P (tmpl)
2600               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2601             revert_static_member_fn (decl);
2602
2603           /* If this is a specialization of a member template of a
2604              template class, we want to return the TEMPLATE_DECL, not
2605              the specialization of it.  */
2606           if (tsk == tsk_template)
2607             {
2608               tree result = DECL_TEMPLATE_RESULT (tmpl);
2609               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2610               DECL_INITIAL (result) = NULL_TREE;
2611               if (have_def)
2612                 {
2613                   tree parm;
2614                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2615                   DECL_SOURCE_LOCATION (result)
2616                     = DECL_SOURCE_LOCATION (decl);
2617                   /* We want to use the argument list specified in the
2618                      definition, not in the original declaration.  */
2619                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2620                   for (parm = DECL_ARGUMENTS (result); parm;
2621                        parm = DECL_CHAIN (parm))
2622                     DECL_CONTEXT (parm) = result;
2623                 }
2624               return register_specialization (tmpl, gen_tmpl, targs,
2625                                               is_friend, 0);
2626             }
2627
2628           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2629           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2630
2631           /* Inherit default function arguments from the template
2632              DECL is specializing.  */
2633           copy_default_args_to_explicit_spec (decl);
2634
2635           /* This specialization has the same protection as the
2636              template it specializes.  */
2637           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2638           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2639
2640           /* 7.1.1-1 [dcl.stc]
2641
2642              A storage-class-specifier shall not be specified in an
2643              explicit specialization...
2644
2645              The parser rejects these, so unless action is taken here,
2646              explicit function specializations will always appear with
2647              global linkage.
2648
2649              The action recommended by the C++ CWG in response to C++
2650              defect report 605 is to make the storage class and linkage
2651              of the explicit specialization match the templated function:
2652
2653              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2654            */
2655           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2656             {
2657               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2658               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2659
2660               /* This specialization has the same linkage and visibility as
2661                  the function template it specializes.  */
2662               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2663               if (! TREE_PUBLIC (decl))
2664                 {
2665                   DECL_INTERFACE_KNOWN (decl) = 1;
2666                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2667                 }
2668               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2669               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2670                 {
2671                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2672                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2673                 }
2674             }
2675
2676           /* If DECL is a friend declaration, declared using an
2677              unqualified name, the namespace associated with DECL may
2678              have been set incorrectly.  For example, in:
2679
2680                template <typename T> void f(T);
2681                namespace N {
2682                  struct S { friend void f<int>(int); }
2683                }
2684
2685              we will have set the DECL_CONTEXT for the friend
2686              declaration to N, rather than to the global namespace.  */
2687           if (DECL_NAMESPACE_SCOPE_P (decl))
2688             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2689
2690           if (is_friend && !have_def)
2691             /* This is not really a declaration of a specialization.
2692                It's just the name of an instantiation.  But, it's not
2693                a request for an instantiation, either.  */
2694             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2695           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2696             /* This is indeed a specialization.  In case of constructors
2697                and destructors, we need in-charge and not-in-charge
2698                versions in V3 ABI.  */
2699             clone_function_decl (decl, /*update_method_vec_p=*/0);
2700
2701           /* Register this specialization so that we can find it
2702              again.  */
2703           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2704         }
2705     }
2706
2707   return decl;
2708 }
2709
2710 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2711    parameters.  These are represented in the same format used for
2712    DECL_TEMPLATE_PARMS.  */
2713
2714 int
2715 comp_template_parms (const_tree parms1, const_tree parms2)
2716 {
2717   const_tree p1;
2718   const_tree p2;
2719
2720   if (parms1 == parms2)
2721     return 1;
2722
2723   for (p1 = parms1, p2 = parms2;
2724        p1 != NULL_TREE && p2 != NULL_TREE;
2725        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2726     {
2727       tree t1 = TREE_VALUE (p1);
2728       tree t2 = TREE_VALUE (p2);
2729       int i;
2730
2731       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2732       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2733
2734       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2735         return 0;
2736
2737       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2738         {
2739           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2740           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2741
2742           /* If either of the template parameters are invalid, assume
2743              they match for the sake of error recovery. */
2744           if (parm1 == error_mark_node || parm2 == error_mark_node)
2745             return 1;
2746
2747           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2748             return 0;
2749
2750           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2751               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2752                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2753             continue;
2754           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2755             return 0;
2756         }
2757     }
2758
2759   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2760     /* One set of parameters has more parameters lists than the
2761        other.  */
2762     return 0;
2763
2764   return 1;
2765 }
2766
2767 /* Determine whether PARM is a parameter pack.  */
2768
2769 bool 
2770 template_parameter_pack_p (const_tree parm)
2771 {
2772   /* Determine if we have a non-type template parameter pack.  */
2773   if (TREE_CODE (parm) == PARM_DECL)
2774     return (DECL_TEMPLATE_PARM_P (parm) 
2775             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2776   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2777     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2778
2779   /* If this is a list of template parameters, we could get a
2780      TYPE_DECL or a TEMPLATE_DECL.  */ 
2781   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2782     parm = TREE_TYPE (parm);
2783
2784   /* Otherwise it must be a type template parameter.  */
2785   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2786            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2787           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2788 }
2789
2790 /* Determine if T is a function parameter pack.  */
2791
2792 bool
2793 function_parameter_pack_p (const_tree t)
2794 {
2795   if (t && TREE_CODE (t) == PARM_DECL)
2796     return FUNCTION_PARAMETER_PACK_P (t);
2797   return false;
2798 }
2799
2800 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2801    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2802
2803 tree
2804 get_function_template_decl (const_tree primary_func_tmpl_inst)
2805 {
2806   if (! primary_func_tmpl_inst
2807       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2808       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2809     return NULL;
2810
2811   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2812 }
2813
2814 /* Return true iff the function parameter PARAM_DECL was expanded
2815    from the function parameter pack PACK.  */
2816
2817 bool
2818 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2819 {
2820   if (DECL_ARTIFICIAL (param_decl)
2821       || !function_parameter_pack_p (pack))
2822     return false;
2823
2824   /* The parameter pack and its pack arguments have the same
2825      DECL_PARM_INDEX.  */
2826   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2827 }
2828
2829 /* Determine whether ARGS describes a variadic template args list,
2830    i.e., one that is terminated by a template argument pack.  */
2831
2832 static bool 
2833 template_args_variadic_p (tree args)
2834 {
2835   int nargs;
2836   tree last_parm;
2837
2838   if (args == NULL_TREE)
2839     return false;
2840
2841   args = INNERMOST_TEMPLATE_ARGS (args);
2842   nargs = TREE_VEC_LENGTH (args);
2843
2844   if (nargs == 0)
2845     return false;
2846
2847   last_parm = TREE_VEC_ELT (args, nargs - 1);
2848
2849   return ARGUMENT_PACK_P (last_parm);
2850 }
2851
2852 /* Generate a new name for the parameter pack name NAME (an
2853    IDENTIFIER_NODE) that incorporates its */
2854
2855 static tree
2856 make_ith_pack_parameter_name (tree name, int i)
2857 {
2858   /* Munge the name to include the parameter index.  */
2859 #define NUMBUF_LEN 128
2860   char numbuf[NUMBUF_LEN];
2861   char* newname;
2862   int newname_len;
2863
2864   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2865   newname_len = IDENTIFIER_LENGTH (name)
2866                 + strlen (numbuf) + 2;
2867   newname = (char*)alloca (newname_len);
2868   snprintf (newname, newname_len,
2869             "%s#%i", IDENTIFIER_POINTER (name), i);
2870   return get_identifier (newname);
2871 }
2872
2873 /* Return true if T is a primary function, class or alias template
2874    instantiation.  */
2875
2876 bool
2877 primary_template_instantiation_p (const_tree t)
2878 {
2879   if (!t)
2880     return false;
2881
2882   if (TREE_CODE (t) == FUNCTION_DECL)
2883     return DECL_LANG_SPECIFIC (t)
2884            && DECL_TEMPLATE_INSTANTIATION (t)
2885            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2886   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
2887     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2888            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2889   else if (TYPE_P (t)
2890            && TYPE_TEMPLATE_INFO (t)
2891            && PRIMARY_TEMPLATE_P (TYPE_TI_TEMPLATE (t))
2892            && DECL_TEMPLATE_INSTANTIATION (TYPE_NAME (t)))
2893     return true;
2894   return false;
2895 }
2896
2897 /* Return true if PARM is a template template parameter.  */
2898
2899 bool
2900 template_template_parameter_p (const_tree parm)
2901 {
2902   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2903 }
2904
2905 /* Return the template parameters of T if T is a
2906    primary template instantiation, NULL otherwise.  */
2907
2908 tree
2909 get_primary_template_innermost_parameters (const_tree t)
2910 {
2911   tree parms = NULL, template_info = NULL;
2912
2913   if ((template_info = get_template_info (t))
2914       && primary_template_instantiation_p (t))
2915     parms = INNERMOST_TEMPLATE_PARMS
2916         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2917
2918   return parms;
2919 }
2920
2921 /* Return the template parameters of the LEVELth level from the full list
2922    of template parameters PARMS.  */
2923
2924 tree
2925 get_template_parms_at_level (tree parms, int level)
2926 {
2927   tree p;
2928   if (!parms
2929       || TREE_CODE (parms) != TREE_LIST
2930       || level > TMPL_PARMS_DEPTH (parms))
2931     return NULL_TREE;
2932
2933   for (p = parms; p; p = TREE_CHAIN (p))
2934     if (TMPL_PARMS_DEPTH (p) == level)
2935       return p;
2936
2937   return NULL_TREE;
2938 }
2939
2940 /* Returns the template arguments of T if T is a template instantiation,
2941    NULL otherwise.  */
2942
2943 tree
2944 get_template_innermost_arguments (const_tree t)
2945 {
2946   tree args = NULL, template_info = NULL;
2947
2948   if ((template_info = get_template_info (t))
2949       && TI_ARGS (template_info))
2950     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2951
2952   return args;
2953 }
2954
2955 /* Return the argument pack elements of T if T is a template argument pack,
2956    NULL otherwise.  */
2957
2958 tree
2959 get_template_argument_pack_elems (const_tree t)
2960 {
2961   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2962       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2963     return NULL;
2964
2965   return ARGUMENT_PACK_ARGS (t);
2966 }
2967
2968 /* Structure used to track the progress of find_parameter_packs_r.  */
2969 struct find_parameter_pack_data 
2970 {
2971   /* TREE_LIST that will contain all of the parameter packs found by
2972      the traversal.  */
2973   tree* parameter_packs;
2974
2975   /* Set of AST nodes that have been visited by the traversal.  */
2976   struct pointer_set_t *visited;
2977 };
2978
2979 /* Identifies all of the argument packs that occur in a template
2980    argument and appends them to the TREE_LIST inside DATA, which is a
2981    find_parameter_pack_data structure. This is a subroutine of
2982    make_pack_expansion and uses_parameter_packs.  */
2983 static tree
2984 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2985 {
2986   tree t = *tp;
2987   struct find_parameter_pack_data* ppd = 
2988     (struct find_parameter_pack_data*)data;
2989   bool parameter_pack_p = false;
2990
2991   /* Handle type aliases/typedefs.  */
2992   if (TYPE_P (t)
2993       && TYPE_NAME (t)
2994       && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
2995       && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
2996     {
2997       if (TYPE_TEMPLATE_INFO (t))
2998         cp_walk_tree (&TYPE_TI_ARGS (t),
2999                       &find_parameter_packs_r,
3000                       ppd, ppd->visited);
3001       *walk_subtrees = 0;
3002       return NULL_TREE;
3003     }
3004
3005   /* Identify whether this is a parameter pack or not.  */
3006   switch (TREE_CODE (t))
3007     {
3008     case TEMPLATE_PARM_INDEX:
3009       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3010         parameter_pack_p = true;
3011       break;
3012
3013     case TEMPLATE_TYPE_PARM:
3014       t = TYPE_MAIN_VARIANT (t);
3015     case TEMPLATE_TEMPLATE_PARM:
3016       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3017         parameter_pack_p = true;
3018       break;
3019
3020     case PARM_DECL:
3021       if (FUNCTION_PARAMETER_PACK_P (t))
3022         {
3023           /* We don't want to walk into the type of a PARM_DECL,
3024              because we don't want to see the type parameter pack.  */
3025           *walk_subtrees = 0;
3026           parameter_pack_p = true;
3027         }
3028       break;
3029
3030     case BASES:
3031       parameter_pack_p = true;
3032       break;
3033     default:
3034       /* Not a parameter pack.  */
3035       break;
3036     }
3037
3038   if (parameter_pack_p)
3039     {
3040       /* Add this parameter pack to the list.  */
3041       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3042     }
3043
3044   if (TYPE_P (t))
3045     cp_walk_tree (&TYPE_CONTEXT (t), 
3046                   &find_parameter_packs_r, ppd, ppd->visited);
3047
3048   /* This switch statement will return immediately if we don't find a
3049      parameter pack.  */
3050   switch (TREE_CODE (t)) 
3051     {
3052     case TEMPLATE_PARM_INDEX:
3053       return NULL_TREE;
3054
3055     case BOUND_TEMPLATE_TEMPLATE_PARM:
3056       /* Check the template itself.  */
3057       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3058                     &find_parameter_packs_r, ppd, ppd->visited);
3059       /* Check the template arguments.  */
3060       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3061                     ppd->visited);
3062       *walk_subtrees = 0;
3063       return NULL_TREE;
3064
3065     case TEMPLATE_TYPE_PARM:
3066     case TEMPLATE_TEMPLATE_PARM:
3067       return NULL_TREE;
3068
3069     case PARM_DECL:
3070       return NULL_TREE;
3071
3072     case RECORD_TYPE:
3073       if (TYPE_PTRMEMFUNC_P (t))
3074         return NULL_TREE;
3075       /* Fall through.  */
3076
3077     case UNION_TYPE:
3078     case ENUMERAL_TYPE:
3079       if (TYPE_TEMPLATE_INFO (t))
3080         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3081                       &find_parameter_packs_r, ppd, ppd->visited);
3082
3083       *walk_subtrees = 0;
3084       return NULL_TREE;
3085
3086     case CONSTRUCTOR:
3087     case TEMPLATE_DECL:
3088       cp_walk_tree (&TREE_TYPE (t),
3089                     &find_parameter_packs_r, ppd, ppd->visited);
3090       return NULL_TREE;
3091  
3092     case TYPENAME_TYPE:
3093       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3094                    ppd, ppd->visited);
3095       *walk_subtrees = 0;
3096       return NULL_TREE;
3097       
3098     case TYPE_PACK_EXPANSION:
3099     case EXPR_PACK_EXPANSION:
3100       *walk_subtrees = 0;
3101       return NULL_TREE;
3102
3103     case INTEGER_TYPE:
3104       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3105                     ppd, ppd->visited);
3106       *walk_subtrees = 0;
3107       return NULL_TREE;
3108
3109     case IDENTIFIER_NODE:
3110       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3111                     ppd->visited);
3112       *walk_subtrees = 0;
3113       return NULL_TREE;
3114
3115     default:
3116       return NULL_TREE;
3117     }
3118
3119   return NULL_TREE;
3120 }
3121
3122 /* Determines if the expression or type T uses any parameter packs.  */
3123 bool
3124 uses_parameter_packs (tree t)
3125 {
3126   tree parameter_packs = NULL_TREE;
3127   struct find_parameter_pack_data ppd;
3128   ppd.parameter_packs = &parameter_packs;
3129   ppd.visited = pointer_set_create ();
3130   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3131   pointer_set_destroy (ppd.visited);
3132   return parameter_packs != NULL_TREE;
3133 }
3134
3135 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3136    representation a base-class initializer into a parameter pack
3137    expansion. If all goes well, the resulting node will be an
3138    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3139    respectively.  */
3140 tree 
3141 make_pack_expansion (tree arg)
3142 {
3143   tree result;
3144   tree parameter_packs = NULL_TREE;
3145   bool for_types = false;
3146   struct find_parameter_pack_data ppd;
3147
3148   if (!arg || arg == error_mark_node)
3149     return arg;
3150
3151   if (TREE_CODE (arg) == TREE_LIST)
3152     {
3153       /* The only time we will see a TREE_LIST here is for a base
3154          class initializer.  In this case, the TREE_PURPOSE will be a
3155          _TYPE node (representing the base class expansion we're
3156          initializing) and the TREE_VALUE will be a TREE_LIST
3157          containing the initialization arguments. 
3158
3159          The resulting expansion looks somewhat different from most
3160          expansions. Rather than returning just one _EXPANSION, we
3161          return a TREE_LIST whose TREE_PURPOSE is a
3162          TYPE_PACK_EXPANSION containing the bases that will be
3163          initialized.  The TREE_VALUE will be identical to the
3164          original TREE_VALUE, which is a list of arguments that will
3165          be passed to each base.  We do not introduce any new pack
3166          expansion nodes into the TREE_VALUE (although it is possible
3167          that some already exist), because the TREE_PURPOSE and
3168          TREE_VALUE all need to be expanded together with the same
3169          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3170          resulting TREE_PURPOSE will mention the parameter packs in
3171          both the bases and the arguments to the bases.  */
3172       tree purpose;
3173       tree value;
3174       tree parameter_packs = NULL_TREE;
3175
3176       /* Determine which parameter packs will be used by the base
3177          class expansion.  */
3178       ppd.visited = pointer_set_create ();
3179       ppd.parameter_packs = &parameter_packs;
3180       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3181                     &ppd, ppd.visited);
3182
3183       if (parameter_packs == NULL_TREE)
3184         {
3185           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3186           pointer_set_destroy (ppd.visited);
3187           return error_mark_node;
3188         }
3189
3190       if (TREE_VALUE (arg) != void_type_node)
3191         {
3192           /* Collect the sets of parameter packs used in each of the
3193              initialization arguments.  */
3194           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3195             {
3196               /* Determine which parameter packs will be expanded in this
3197                  argument.  */
3198               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3199                             &ppd, ppd.visited);
3200             }
3201         }
3202
3203       pointer_set_destroy (ppd.visited);
3204
3205       /* Create the pack expansion type for the base type.  */
3206       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3207       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3208       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3209
3210       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3211          they will rarely be compared to anything.  */
3212       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3213
3214       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3215     }
3216
3217   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3218     for_types = true;
3219
3220   /* Build the PACK_EXPANSION_* node.  */
3221   result = for_types
3222      ? cxx_make_type (TYPE_PACK_EXPANSION)
3223      : make_node (EXPR_PACK_EXPANSION);
3224   SET_PACK_EXPANSION_PATTERN (result, arg);
3225   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3226     {
3227       /* Propagate type and const-expression information.  */
3228       TREE_TYPE (result) = TREE_TYPE (arg);
3229       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3230     }
3231   else
3232     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3233        they will rarely be compared to anything.  */
3234     SET_TYPE_STRUCTURAL_EQUALITY (result);
3235
3236   /* Determine which parameter packs will be expanded.  */
3237   ppd.parameter_packs = &parameter_packs;
3238   ppd.visited = pointer_set_create ();
3239   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3240   pointer_set_destroy (ppd.visited);
3241
3242   /* Make sure we found some parameter packs.  */
3243   if (parameter_packs == NULL_TREE)
3244     {
3245       if (TYPE_P (arg))
3246         error ("expansion pattern %<%T%> contains no argument packs", arg);
3247       else
3248         error ("expansion pattern %<%E%> contains no argument packs", arg);
3249       return error_mark_node;
3250     }
3251   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3252
3253   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3254
3255   return result;
3256 }
3257
3258 /* Checks T for any "bare" parameter packs, which have not yet been
3259    expanded, and issues an error if any are found. This operation can
3260    only be done on full expressions or types (e.g., an expression
3261    statement, "if" condition, etc.), because we could have expressions like:
3262
3263      foo(f(g(h(args)))...)
3264
3265    where "args" is a parameter pack. check_for_bare_parameter_packs
3266    should not be called for the subexpressions args, h(args),
3267    g(h(args)), or f(g(h(args))), because we would produce erroneous
3268    error messages. 
3269
3270    Returns TRUE and emits an error if there were bare parameter packs,
3271    returns FALSE otherwise.  */
3272 bool 
3273 check_for_bare_parameter_packs (tree t)
3274 {
3275   tree parameter_packs = NULL_TREE;
3276   struct find_parameter_pack_data ppd;
3277
3278   if (!processing_template_decl || !t || t == error_mark_node)
3279     return false;
3280
3281   if (TREE_CODE (t) == TYPE_DECL)
3282     t = TREE_TYPE (t);
3283
3284   ppd.parameter_packs = &parameter_packs;
3285   ppd.visited = pointer_set_create ();
3286   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3287   pointer_set_destroy (ppd.visited);
3288
3289   if (parameter_packs) 
3290     {
3291       error ("parameter packs not expanded with %<...%>:");
3292       while (parameter_packs)
3293         {
3294           tree pack = TREE_VALUE (parameter_packs);
3295           tree name = NULL_TREE;
3296
3297           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3298               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3299             name = TYPE_NAME (pack);
3300           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3301             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3302           else
3303             name = DECL_NAME (pack);
3304
3305           if (name)
3306             inform (input_location, "        %qD", name);
3307           else
3308             inform (input_location, "        <anonymous>");
3309
3310           parameter_packs = TREE_CHAIN (parameter_packs);
3311         }
3312
3313       return true;
3314     }
3315
3316   return false;
3317 }
3318
3319 /* Expand any parameter packs that occur in the template arguments in
3320    ARGS.  */
3321 tree
3322 expand_template_argument_pack (tree args)
3323 {
3324   tree result_args = NULL_TREE;
3325   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3326   int num_result_args = -1;
3327   int non_default_args_count = -1;
3328
3329   /* First, determine if we need to expand anything, and the number of
3330      slots we'll need.  */
3331   for (in_arg = 0; in_arg < nargs; ++in_arg)
3332     {
3333       tree arg = TREE_VEC_ELT (args, in_arg);
3334       if (arg == NULL_TREE)
3335         return args;
3336       if (ARGUMENT_PACK_P (arg))
3337         {
3338           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3339           if (num_result_args < 0)
3340             num_result_args = in_arg + num_packed;
3341           else
3342             num_result_args += num_packed;
3343         }
3344       else
3345         {
3346           if (num_result_args >= 0)
3347             num_result_args++;
3348         }
3349     }
3350
3351   /* If no expansion is necessary, we're done.  */
3352   if (num_result_args < 0)
3353     return args;
3354
3355   /* Expand arguments.  */
3356   result_args = make_tree_vec (num_result_args);
3357   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3358     non_default_args_count =
3359       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3360   for (in_arg = 0; in_arg < nargs; ++in_arg)
3361     {
3362       tree arg = TREE_VEC_ELT (args, in_arg);
3363       if (ARGUMENT_PACK_P (arg))
3364         {
3365           tree packed = ARGUMENT_PACK_ARGS (arg);
3366           int i, num_packed = TREE_VEC_LENGTH (packed);
3367           for (i = 0; i < num_packed; ++i, ++out_arg)
3368             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3369           if (non_default_args_count > 0)
3370             non_default_args_count += num_packed;
3371         }
3372       else
3373         {
3374           TREE_VEC_ELT (result_args, out_arg) = arg;
3375           ++out_arg;
3376         }
3377     }
3378   if (non_default_args_count >= 0)
3379     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3380   return result_args;
3381 }
3382
3383 /* Checks if DECL shadows a template parameter.
3384
3385    [temp.local]: A template-parameter shall not be redeclared within its
3386    scope (including nested scopes).
3387
3388    Emits an error and returns TRUE if the DECL shadows a parameter,
3389    returns FALSE otherwise.  */
3390
3391 bool
3392 check_template_shadow (tree decl)
3393 {
3394   tree olddecl;
3395
3396   /* If we're not in a template, we can't possibly shadow a template
3397      parameter.  */
3398   if (!current_template_parms)
3399     return true;
3400
3401   /* Figure out what we're shadowing.  */
3402   if (TREE_CODE (decl) == OVERLOAD)
3403     decl = OVL_CURRENT (decl);
3404   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3405
3406   /* If there's no previous binding for this name, we're not shadowing
3407      anything, let alone a template parameter.  */
3408   if (!olddecl)
3409     return true;
3410
3411   /* If we're not shadowing a template parameter, we're done.  Note
3412      that OLDDECL might be an OVERLOAD (or perhaps even an
3413      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3414      node.  */
3415   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3416     return true;
3417
3418   /* We check for decl != olddecl to avoid bogus errors for using a
3419      name inside a class.  We check TPFI to avoid duplicate errors for
3420      inline member templates.  */
3421   if (decl == olddecl
3422       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3423     return true;
3424
3425   error ("declaration of %q+#D", decl);
3426   error (" shadows template parm %q+#D", olddecl);
3427   return false;
3428 }
3429
3430 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3431    ORIG_LEVEL, DECL, and TYPE.  */
3432
3433 static tree
3434 build_template_parm_index (int index,
3435                            int level,
3436                            int orig_level,
3437                            tree decl,
3438                            tree type)
3439 {
3440   tree t = make_node (TEMPLATE_PARM_INDEX);
3441   TEMPLATE_PARM_IDX (t) = index;
3442   TEMPLATE_PARM_LEVEL (t) = level;
3443   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3444   TEMPLATE_PARM_DECL (t) = decl;
3445   TREE_TYPE (t) = type;
3446   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3447   TREE_READONLY (t) = TREE_READONLY (decl);
3448
3449   return t;
3450 }
3451
3452 /* Find the canonical type parameter for the given template type
3453    parameter.  Returns the canonical type parameter, which may be TYPE
3454    if no such parameter existed.  */
3455
3456 static tree
3457 canonical_type_parameter (tree type)
3458 {
3459   tree list;
3460   int idx = TEMPLATE_TYPE_IDX (type);
3461   if (!canonical_template_parms)
3462     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3463
3464   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3465     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3466
3467   list = VEC_index (tree, canonical_template_parms, idx);
3468   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3469     list = TREE_CHAIN (list);
3470
3471   if (list)
3472     return TREE_VALUE (list);
3473   else
3474     {
3475       VEC_replace(tree, canonical_template_parms, idx,
3476                   tree_cons (NULL_TREE, type, 
3477                              VEC_index (tree, canonical_template_parms, idx)));
3478       return type;
3479     }
3480 }
3481
3482 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3483    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3484    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3485    new one is created.  */
3486
3487 static tree
3488 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3489                             tsubst_flags_t complain)
3490 {
3491   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3492       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3493           != TEMPLATE_PARM_LEVEL (index) - levels)
3494       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3495     {
3496       tree orig_decl = TEMPLATE_PARM_DECL (index);
3497       tree decl, t;
3498
3499       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3500                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3501       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3502       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3503       DECL_ARTIFICIAL (decl) = 1;
3504       SET_DECL_TEMPLATE_PARM_P (decl);
3505
3506       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3507                                      TEMPLATE_PARM_LEVEL (index) - levels,
3508                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3509                                      decl, type);
3510       TEMPLATE_PARM_DESCENDANTS (index) = t;
3511       TEMPLATE_PARM_PARAMETER_PACK (t) 
3512         = TEMPLATE_PARM_PARAMETER_PACK (index);
3513
3514         /* Template template parameters need this.  */
3515       if (TREE_CODE (decl) == TEMPLATE_DECL)
3516         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3517           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3518            args, complain);
3519     }
3520
3521   return TEMPLATE_PARM_DESCENDANTS (index);
3522 }
3523
3524 /* Process information from new template parameter PARM and append it
3525    to the LIST being built.  This new parameter is a non-type
3526    parameter iff IS_NON_TYPE is true. This new parameter is a
3527    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3528    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3529    parameter list PARM belongs to. This is used used to create a
3530    proper canonical type for the type of PARM that is to be created,
3531    iff PARM is a type.  If the size is not known, this parameter shall
3532    be set to 0.  */
3533
3534 tree
3535 process_template_parm (tree list, location_t parm_loc, tree parm,
3536                        bool is_non_type, bool is_parameter_pack)
3537 {
3538   tree decl = 0;
3539   tree defval;
3540   tree err_parm_list;
3541   int idx = 0;
3542
3543   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3544   defval = TREE_PURPOSE (parm);
3545
3546   if (list)
3547     {
3548       tree p = tree_last (list);
3549
3550       if (p && TREE_VALUE (p) != error_mark_node)
3551         {
3552           p = TREE_VALUE (p);
3553           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3554             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3555           else
3556             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3557         }
3558
3559       ++idx;
3560     }
3561   else
3562     idx = 0;
3563
3564   if (is_non_type)
3565     {
3566       parm = TREE_VALUE (parm);
3567
3568       SET_DECL_TEMPLATE_PARM_P (parm);
3569
3570       if (TREE_TYPE (parm) == error_mark_node)
3571         {
3572           err_parm_list = build_tree_list (defval, parm);
3573           TREE_VALUE (err_parm_list) = error_mark_node;
3574            return chainon (list, err_parm_list);
3575         }
3576       else
3577       {
3578         /* [temp.param]
3579
3580            The top-level cv-qualifiers on the template-parameter are
3581            ignored when determining its type.  */
3582         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3583         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3584           {
3585             err_parm_list = build_tree_list (defval, parm);
3586             TREE_VALUE (err_parm_list) = error_mark_node;
3587              return chainon (list, err_parm_list);
3588           }
3589
3590         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3591           {
3592             /* This template parameter is not a parameter pack, but it
3593                should be. Complain about "bare" parameter packs.  */
3594             check_for_bare_parameter_packs (TREE_TYPE (parm));
3595             
3596             /* Recover by calling this a parameter pack.  */
3597             is_parameter_pack = true;
3598           }
3599       }
3600
3601       /* A template parameter is not modifiable.  */
3602       TREE_CONSTANT (parm) = 1;
3603       TREE_READONLY (parm) = 1;
3604       decl = build_decl (parm_loc,
3605                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3606       TREE_CONSTANT (decl) = 1;
3607       TREE_READONLY (decl) = 1;
3608       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3609         = build_template_parm_index (idx, processing_template_decl,
3610                                      processing_template_decl,
3611                                      decl, TREE_TYPE (parm));
3612
3613       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3614         = is_parameter_pack;
3615     }
3616   else
3617     {
3618       tree t;
3619       parm = TREE_VALUE (TREE_VALUE (parm));
3620
3621       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3622         {
3623           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3624           /* This is for distinguishing between real templates and template
3625              template parameters */
3626           TREE_TYPE (parm) = t;
3627           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3628           decl = parm;
3629         }
3630       else
3631         {
3632           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3633           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3634           decl = build_decl (parm_loc,
3635                              TYPE_DECL, parm, t);
3636         }
3637
3638       TYPE_NAME (t) = decl;
3639       TYPE_STUB_DECL (t) = decl;
3640       parm = decl;
3641       TEMPLATE_TYPE_PARM_INDEX (t)
3642         = build_template_parm_index (idx, processing_template_decl,
3643                                      processing_template_decl,
3644                                      decl, TREE_TYPE (parm));
3645       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3646       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3647     }
3648   DECL_ARTIFICIAL (decl) = 1;
3649   SET_DECL_TEMPLATE_PARM_P (decl);
3650   pushdecl (decl);
3651   parm = build_tree_list (defval, parm);
3652   return chainon (list, parm);
3653 }
3654
3655 /* The end of a template parameter list has been reached.  Process the
3656    tree list into a parameter vector, converting each parameter into a more
3657    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3658    as PARM_DECLs.  */
3659
3660 tree
3661 end_template_parm_list (tree parms)
3662 {
3663   int nparms;
3664   tree parm, next;
3665   tree saved_parmlist = make_tree_vec (list_length (parms));
3666
3667   current_template_parms
3668     = tree_cons (size_int (processing_template_decl),
3669                  saved_parmlist, current_template_parms);
3670
3671   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3672     {
3673       next = TREE_CHAIN (parm);
3674       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3675       TREE_CHAIN (parm) = NULL_TREE;
3676     }
3677
3678   --processing_template_parmlist;
3679
3680   return saved_parmlist;
3681 }
3682
3683 /* end_template_decl is called after a template declaration is seen.  */
3684
3685 void
3686 end_template_decl (void)
3687 {
3688   reset_specialization ();
3689
3690   if (! processing_template_decl)
3691     return;
3692
3693   /* This matches the pushlevel in begin_template_parm_list.  */
3694   finish_scope ();
3695
3696   --processing_template_decl;
3697   current_template_parms = TREE_CHAIN (current_template_parms);
3698 }
3699
3700 /* Takes a TREE_LIST representing a template parameter and convert it
3701    into an argument suitable to be passed to the type substitution
3702    functions.  Note that If the TREE_LIST contains an error_mark
3703    node, the returned argument is error_mark_node.  */
3704
3705 static tree
3706 template_parm_to_arg (tree t)
3707 {
3708
3709   if (t == NULL_TREE
3710       || TREE_CODE (t) != TREE_LIST)
3711     return t;
3712
3713   if (error_operand_p (TREE_VALUE (t)))
3714     return error_mark_node;
3715
3716   t = TREE_VALUE (t);
3717
3718   if (TREE_CODE (t) == TYPE_DECL
3719       || TREE_CODE (t) == TEMPLATE_DECL)
3720     {
3721       t = TREE_TYPE (t);
3722
3723       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3724         {
3725           /* Turn this argument into a TYPE_ARGUMENT_PACK
3726              with a single element, which expands T.  */
3727           tree vec = make_tree_vec (1);
3728 #ifdef ENABLE_CHECKING
3729           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3730             (vec, TREE_VEC_LENGTH (vec));
3731 #endif
3732           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3733
3734           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3735           SET_ARGUMENT_PACK_ARGS (t, vec);
3736         }
3737     }
3738   else
3739     {
3740       t = DECL_INITIAL (t);
3741
3742       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3743         {
3744           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3745              with a single element, which expands T.  */
3746           tree vec = make_tree_vec (1);
3747           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3748 #ifdef ENABLE_CHECKING
3749           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3750             (vec, TREE_VEC_LENGTH (vec));
3751 #endif
3752           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3753
3754           t  = make_node (NONTYPE_ARGUMENT_PACK);
3755           SET_ARGUMENT_PACK_ARGS (t, vec);
3756           TREE_TYPE (t) = type;
3757         }
3758     }
3759   return t;
3760 }
3761
3762 /* This function returns TRUE if PARM_PACK is a template parameter
3763    pack and if ARG_PACK is what template_parm_to_arg returned when
3764    passed PARM_PACK.  */
3765
3766 static bool
3767 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
3768 {
3769   /* For clarity in the comments below let's use the representation
3770      argument_pack<elements>' to denote an argument pack and its
3771      elements.
3772
3773      In the 'if' block below, we want to detect cases where
3774      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
3775      check if ARG_PACK is an argument pack which sole element is
3776      the expansion of PARM_PACK.  That argument pack is typically
3777      created by template_parm_to_arg when passed a parameter
3778      pack.  */
3779
3780   if (arg_pack
3781       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
3782       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
3783     {
3784       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
3785       tree pattern = PACK_EXPANSION_PATTERN (expansion);
3786       if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
3787           || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
3788         /* The argument pack that the parameter maps to is just an
3789            expansion of the parameter itself, such as one would
3790            find in the implicit typedef of a class inside the
3791            class itself.  Consider this parameter "unsubstituted",
3792            so that we will maintain the outer pack expansion.  */
3793         return true;
3794     }
3795   return false;
3796 }
3797
3798 /* Within the declaration of a template, return all levels of template
3799    parameters that apply.  The template parameters are represented as
3800    a TREE_VEC, in the form documented in cp-tree.h for template
3801    arguments.  */
3802
3803 static tree
3804 current_template_args (void)
3805 {
3806   tree header;
3807   tree args = NULL_TREE;
3808   int length = TMPL_PARMS_DEPTH (current_template_parms);
3809   int l = length;
3810
3811   /* If there is only one level of template parameters, we do not
3812      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3813      TREE_VEC containing the arguments.  */
3814   if (length > 1)
3815     args = make_tree_vec (length);
3816
3817   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3818     {
3819       tree a = copy_node (TREE_VALUE (header));
3820       int i;
3821
3822       TREE_TYPE (a) = NULL_TREE;
3823       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3824         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
3825
3826 #ifdef ENABLE_CHECKING
3827       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3828 #endif
3829
3830       if (length > 1)
3831         TREE_VEC_ELT (args, --l) = a;
3832       else
3833         args = a;
3834     }
3835
3836     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
3837       /* This can happen for template parms of a template template
3838          parameter, e.g:
3839
3840          template<template<class T, class U> class TT> struct S;
3841
3842          Consider the level of the parms of TT; T and U both have
3843          level 2; TT has no template parm of level 1. So in this case
3844          the first element of full_template_args is NULL_TREE. If we
3845          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
3846          of 2. This will make tsubst wrongly consider that T and U
3847          have level 1. Instead, let's create a dummy vector as the
3848          first element of full_template_args so that TMPL_ARG_DEPTH
3849          returns the correct depth for args.  */
3850       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
3851   return args;
3852 }
3853
3854 /* Update the declared TYPE by doing any lookups which were thought to be
3855    dependent, but are not now that we know the SCOPE of the declarator.  */
3856
3857 tree
3858 maybe_update_decl_type (tree orig_type, tree scope)
3859 {
3860   tree type = orig_type;
3861
3862   if (type == NULL_TREE)
3863     return type;
3864
3865   if (TREE_CODE (orig_type) == TYPE_DECL)
3866     type = TREE_TYPE (type);
3867
3868   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3869       && dependent_type_p (type)
3870       /* Don't bother building up the args in this case.  */
3871       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3872     {
3873       /* tsubst in the args corresponding to the template parameters,
3874          including auto if present.  Most things will be unchanged, but
3875          make_typename_type and tsubst_qualified_id will resolve
3876          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3877       tree args = current_template_args ();
3878       tree auto_node = type_uses_auto (type);
3879       tree pushed;
3880       if (auto_node)
3881         {
3882           tree auto_vec = make_tree_vec (1);
3883           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3884           args = add_to_template_args (args, auto_vec);
3885         }
3886       pushed = push_scope (scope);
3887       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3888       if (pushed)
3889         pop_scope (scope);
3890     }
3891
3892   if (type == error_mark_node)
3893     return orig_type;
3894
3895   if (TREE_CODE (orig_type) == TYPE_DECL)
3896     {
3897       if (same_type_p (type, TREE_TYPE (orig_type)))
3898         type = orig_type;
3899       else
3900         type = TYPE_NAME (type);
3901     }
3902   return type;
3903 }
3904
3905 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3906    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3907    a member template.  Used by push_template_decl below.  */
3908
3909 static tree
3910 build_template_decl (tree decl, tree parms, bool member_template_p)
3911 {
3912   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3913   DECL_TEMPLATE_PARMS (tmpl) = parms;
3914   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3915   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3916   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3917
3918   return tmpl;
3919 }
3920
3921 struct template_parm_data
3922 {
3923   /* The level of the template parameters we are currently
3924      processing.  */
3925   int level;
3926
3927   /* The index of the specialization argument we are currently
3928      processing.  */
3929   int current_arg;
3930
3931   /* An array whose size is the number of template parameters.  The
3932      elements are nonzero if the parameter has been used in any one
3933      of the arguments processed so far.  */
3934   int* parms;
3935
3936   /* An array whose size is the number of template arguments.  The
3937      elements are nonzero if the argument makes use of template
3938      parameters of this level.  */
3939   int* arg_uses_template_parms;
3940 };
3941
3942 /* Subroutine of push_template_decl used to see if each template
3943    parameter in a partial specialization is used in the explicit
3944    argument list.  If T is of the LEVEL given in DATA (which is
3945    treated as a template_parm_data*), then DATA->PARMS is marked
3946    appropriately.  */
3947
3948 static int
3949 mark_template_parm (tree t, void* data)
3950 {
3951   int level;
3952   int idx;
3953   struct template_parm_data* tpd = (struct template_parm_data*) data;
3954
3955   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3956     {
3957       level = TEMPLATE_PARM_LEVEL (t);
3958       idx = TEMPLATE_PARM_IDX (t);
3959     }
3960   else
3961     {
3962       level = TEMPLATE_TYPE_LEVEL (t);
3963       idx = TEMPLATE_TYPE_IDX (t);
3964     }
3965
3966   if (level == tpd->level)
3967     {
3968       tpd->parms[idx] = 1;
3969       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3970     }
3971
3972   /* Return zero so that for_each_template_parm will continue the
3973      traversal of the tree; we want to mark *every* template parm.  */
3974   return 0;
3975 }
3976
3977 /* Process the partial specialization DECL.  */
3978
3979 static tree
3980 process_partial_specialization (tree decl)
3981 {
3982   tree type = TREE_TYPE (decl);
3983   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3984   tree specargs = CLASSTYPE_TI_ARGS (type);
3985   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3986   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3987   tree inner_parms;
3988   tree inst;
3989   int nargs = TREE_VEC_LENGTH (inner_args);
3990   int ntparms;
3991   int  i;
3992   bool did_error_intro = false;
3993   struct template_parm_data tpd;
3994   struct template_parm_data tpd2;
3995
3996   gcc_assert (current_template_parms);
3997
3998   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3999   ntparms = TREE_VEC_LENGTH (inner_parms);
4000
4001   /* We check that each of the template parameters given in the
4002      partial specialization is used in the argument list to the
4003      specialization.  For example:
4004
4005        template <class T> struct S;
4006        template <class T> struct S<T*>;
4007
4008      The second declaration is OK because `T*' uses the template
4009      parameter T, whereas
4010
4011        template <class T> struct S<int>;
4012
4013      is no good.  Even trickier is:
4014
4015        template <class T>
4016        struct S1
4017        {
4018           template <class U>
4019           struct S2;
4020           template <class U>
4021           struct S2<T>;
4022        };
4023
4024      The S2<T> declaration is actually invalid; it is a
4025      full-specialization.  Of course,
4026
4027           template <class U>
4028           struct S2<T (*)(U)>;
4029
4030      or some such would have been OK.  */
4031   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4032   tpd.parms = XALLOCAVEC (int, ntparms);
4033   memset (tpd.parms, 0, sizeof (int) * ntparms);
4034
4035   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4036   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4037   for (i = 0; i < nargs; ++i)
4038     {
4039       tpd.current_arg = i;
4040       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4041                               &mark_template_parm,
4042                               &tpd,
4043                               NULL,
4044                               /*include_nondeduced_p=*/false);
4045     }
4046   for (i = 0; i < ntparms; ++i)
4047     if (tpd.parms[i] == 0)
4048       {
4049         /* One of the template parms was not used in the
4050            specialization.  */
4051         if (!did_error_intro)
4052           {
4053             error ("template parameters not used in partial specialization:");
4054             did_error_intro = true;
4055           }
4056
4057         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4058       }
4059
4060   if (did_error_intro)
4061     return error_mark_node;
4062
4063   /* [temp.class.spec]
4064
4065      The argument list of the specialization shall not be identical to
4066      the implicit argument list of the primary template.  */
4067   if (comp_template_args
4068       (inner_args,
4069        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4070                                                    (maintmpl)))))
4071     error ("partial specialization %qT does not specialize any template arguments", type);
4072
4073   /* [temp.class.spec]
4074
4075      A partially specialized non-type argument expression shall not
4076      involve template parameters of the partial specialization except
4077      when the argument expression is a simple identifier.
4078
4079      The type of a template parameter corresponding to a specialized
4080      non-type argument shall not be dependent on a parameter of the
4081      specialization. 
4082
4083      Also, we verify that pack expansions only occur at the
4084      end of the argument list.  */
4085   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4086   tpd2.parms = 0;
4087   for (i = 0; i < nargs; ++i)
4088     {
4089       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4090       tree arg = TREE_VEC_ELT (inner_args, i);
4091       tree packed_args = NULL_TREE;
4092       int j, len = 1;
4093
4094       if (ARGUMENT_PACK_P (arg))
4095         {
4096           /* Extract the arguments from the argument pack. We'll be
4097              iterating over these in the following loop.  */
4098           packed_args = ARGUMENT_PACK_ARGS (arg);
4099           len = TREE_VEC_LENGTH (packed_args);
4100         }
4101
4102       for (j = 0; j < len; j++)
4103         {
4104           if (packed_args)
4105             /* Get the Jth argument in the parameter pack.  */
4106             arg = TREE_VEC_ELT (packed_args, j);
4107
4108           if (PACK_EXPANSION_P (arg))
4109             {
4110               /* Pack expansions must come at the end of the
4111                  argument list.  */
4112               if ((packed_args && j < len - 1)
4113                   || (!packed_args && i < nargs - 1))
4114                 {
4115                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4116                     error ("parameter pack argument %qE must be at the "
4117                            "end of the template argument list", arg);
4118                   else
4119                     error ("parameter pack argument %qT must be at the "
4120                            "end of the template argument list", arg);
4121                 }
4122             }
4123
4124           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4125             /* We only care about the pattern.  */
4126             arg = PACK_EXPANSION_PATTERN (arg);
4127
4128           if (/* These first two lines are the `non-type' bit.  */
4129               !TYPE_P (arg)
4130               && TREE_CODE (arg) != TEMPLATE_DECL
4131               /* This next line is the `argument expression is not just a
4132                  simple identifier' condition and also the `specialized
4133                  non-type argument' bit.  */
4134               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4135             {
4136               if ((!packed_args && tpd.arg_uses_template_parms[i])
4137                   || (packed_args && uses_template_parms (arg)))
4138                 error ("template argument %qE involves template parameter(s)",
4139                        arg);
4140               else 
4141                 {
4142                   /* Look at the corresponding template parameter,
4143                      marking which template parameters its type depends
4144                      upon.  */
4145                   tree type = TREE_TYPE (parm);
4146
4147                   if (!tpd2.parms)
4148                     {
4149                       /* We haven't yet initialized TPD2.  Do so now.  */
4150                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4151                       /* The number of parameters here is the number in the
4152                          main template, which, as checked in the assertion
4153                          above, is NARGS.  */
4154                       tpd2.parms = XALLOCAVEC (int, nargs);
4155                       tpd2.level = 
4156                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4157                     }
4158
4159                   /* Mark the template parameters.  But this time, we're
4160                      looking for the template parameters of the main
4161                      template, not in the specialization.  */
4162                   tpd2.current_arg = i;
4163                   tpd2.arg_uses_template_parms[i] = 0;
4164                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4165                   for_each_template_parm (type,
4166                                           &mark_template_parm,
4167                                           &tpd2,
4168                                           NULL,
4169                                           /*include_nondeduced_p=*/false);
4170
4171                   if (tpd2.arg_uses_template_parms [i])
4172                     {
4173                       /* The type depended on some template parameters.
4174                          If they are fully specialized in the
4175                          specialization, that's OK.  */
4176                       int j;
4177                       int count = 0;
4178                       for (j = 0; j < nargs; ++j)
4179                         if (tpd2.parms[j] != 0
4180                             && tpd.arg_uses_template_parms [j])
4181                           ++count;
4182                       if (count != 0)
4183                         error_n (input_location, count,
4184                                  "type %qT of template argument %qE depends "
4185                                  "on a template parameter",
4186                                  "type %qT of template argument %qE depends "
4187                                  "on template parameters",
4188                                  type,
4189                                  arg);
4190                     }
4191                 }
4192             }
4193         }
4194     }
4195
4196   /* We should only get here once.  */
4197   gcc_assert (!COMPLETE_TYPE_P (type));
4198
4199   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4200     = tree_cons (specargs, inner_parms,
4201                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4202   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4203
4204   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4205        inst = TREE_CHAIN (inst))
4206     {
4207       tree inst_type = TREE_VALUE (inst);
4208       if (COMPLETE_TYPE_P (inst_type)
4209           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4210         {
4211           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4212           if (spec && TREE_TYPE (spec) == type)
4213             permerror (input_location,
4214                        "partial specialization of %qT after instantiation "
4215                        "of %qT", type, inst_type);
4216         }
4217     }
4218
4219   return decl;
4220 }
4221
4222 /* Check that a template declaration's use of default arguments and
4223    parameter packs is not invalid.  Here, PARMS are the template
4224    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4225    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4226    specialization.
4227    
4228
4229    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4230    declaration (but not a definition); 1 indicates a declaration, 2
4231    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4232    emitted for extraneous default arguments.
4233
4234    Returns TRUE if there were no errors found, FALSE otherwise. */
4235
4236 bool
4237 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4238                          int is_partial, int is_friend_decl)
4239 {
4240   const char *msg;
4241   int last_level_to_check;
4242   tree parm_level;
4243   bool no_errors = true;
4244
4245   /* [temp.param]
4246
4247      A default template-argument shall not be specified in a
4248      function template declaration or a function template definition, nor
4249      in the template-parameter-list of the definition of a member of a
4250      class template.  */
4251
4252   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4253     /* You can't have a function template declaration in a local
4254        scope, nor you can you define a member of a class template in a
4255        local scope.  */
4256     return true;
4257
4258   if (current_class_type
4259       && !TYPE_BEING_DEFINED (current_class_type)
4260       && DECL_LANG_SPECIFIC (decl)
4261       && DECL_DECLARES_FUNCTION_P (decl)
4262       /* If this is either a friend defined in the scope of the class
4263          or a member function.  */
4264       && (DECL_FUNCTION_MEMBER_P (decl)
4265           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4266           : DECL_FRIEND_CONTEXT (decl)
4267           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4268           : false)
4269       /* And, if it was a member function, it really was defined in
4270          the scope of the class.  */
4271       && (!DECL_FUNCTION_MEMBER_P (decl)
4272           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4273     /* We already checked these parameters when the template was
4274        declared, so there's no need to do it again now.  This function
4275        was defined in class scope, but we're processing it's body now
4276        that the class is complete.  */
4277     return true;
4278
4279   /* Core issue 226 (C++0x only): the following only applies to class
4280      templates.  */
4281   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4282     {
4283       /* [temp.param]
4284
4285          If a template-parameter has a default template-argument, all
4286          subsequent template-parameters shall have a default
4287          template-argument supplied.  */
4288       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4289         {
4290           tree inner_parms = TREE_VALUE (parm_level);
4291           int ntparms = TREE_VEC_LENGTH (inner_parms);
4292           int seen_def_arg_p = 0;
4293           int i;
4294
4295           for (i = 0; i < ntparms; ++i)
4296             {
4297               tree parm = TREE_VEC_ELT (inner_parms, i);
4298
4299               if (parm == error_mark_node)
4300                 continue;
4301
4302               if (TREE_PURPOSE (parm))
4303                 seen_def_arg_p = 1;
4304               else if (seen_def_arg_p
4305                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4306                 {
4307                   error ("no default argument for %qD", TREE_VALUE (parm));
4308                   /* For better subsequent error-recovery, we indicate that
4309                      there should have been a default argument.  */
4310                   TREE_PURPOSE (parm) = error_mark_node;
4311                   no_errors = false;
4312                 }
4313               else if (is_primary
4314                        && !is_partial
4315                        && !is_friend_decl
4316                        /* Don't complain about an enclosing partial
4317                           specialization.  */
4318                        && parm_level == parms
4319                        && TREE_CODE (decl) == TYPE_DECL
4320                        && i < ntparms - 1
4321                        && template_parameter_pack_p (TREE_VALUE (parm)))
4322                 {
4323                   /* A primary class template can only have one
4324                      parameter pack, at the end of the template
4325                      parameter list.  */
4326
4327                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4328                     error ("parameter pack %qE must be at the end of the"
4329                            " template parameter list", TREE_VALUE (parm));
4330                   else
4331                     error ("parameter pack %qT must be at the end of the"
4332                            " template parameter list", 
4333                            TREE_TYPE (TREE_VALUE (parm)));
4334
4335                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4336                     = error_mark_node;
4337                   no_errors = false;
4338                 }
4339             }
4340         }
4341     }
4342
4343   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4344       || is_partial 
4345       || !is_primary
4346       || is_friend_decl)
4347     /* For an ordinary class template, default template arguments are
4348        allowed at the innermost level, e.g.:
4349          template <class T = int>
4350          struct S {};
4351        but, in a partial specialization, they're not allowed even
4352        there, as we have in [temp.class.spec]:
4353
4354          The template parameter list of a specialization shall not
4355          contain default template argument values.
4356
4357        So, for a partial specialization, or for a function template
4358        (in C++98/C++03), we look at all of them.  */
4359     ;
4360   else
4361     /* But, for a primary class template that is not a partial
4362        specialization we look at all template parameters except the
4363        innermost ones.  */
4364     parms = TREE_CHAIN (parms);
4365
4366   /* Figure out what error message to issue.  */
4367   if (is_friend_decl == 2)
4368     msg = G_("default template arguments may not be used in function template "
4369              "friend re-declaration");
4370   else if (is_friend_decl)
4371     msg = G_("default template arguments may not be used in function template "
4372              "friend declarations");
4373   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4374     msg = G_("default template arguments may not be used in function templates "
4375              "without -std=c++11 or -std=gnu++11");
4376   else if (is_partial)
4377     msg = G_("default template arguments may not be used in "
4378              "partial specializations");
4379   else
4380     msg = G_("default argument for template parameter for class enclosing %qD");
4381
4382   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4383     /* If we're inside a class definition, there's no need to
4384        examine the parameters to the class itself.  On the one
4385        hand, they will be checked when the class is defined, and,
4386        on the other, default arguments are valid in things like:
4387          template <class T = double>
4388          struct S { template <class U> void f(U); };
4389        Here the default argument for `S' has no bearing on the
4390        declaration of `f'.  */
4391     last_level_to_check = template_class_depth (current_class_type) + 1;
4392   else
4393     /* Check everything.  */
4394     last_level_to_check = 0;
4395
4396   for (parm_level = parms;
4397        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4398        parm_level = TREE_CHAIN (parm_level))
4399     {
4400       tree inner_parms = TREE_VALUE (parm_level);
4401       int i;
4402       int ntparms;
4403
4404       ntparms = TREE_VEC_LENGTH (inner_parms);
4405       for (i = 0; i < ntparms; ++i)
4406         {
4407           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4408             continue;
4409
4410           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4411             {
4412               if (msg)
4413                 {
4414                   no_errors = false;
4415                   if (is_friend_decl == 2)
4416                     return no_errors;
4417
4418                   error (msg, decl);
4419                   msg = 0;
4420                 }
4421
4422               /* Clear out the default argument so that we are not
4423                  confused later.  */
4424               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4425             }
4426         }
4427
4428       /* At this point, if we're still interested in issuing messages,
4429          they must apply to classes surrounding the object declared.  */
4430       if (msg)
4431         msg = G_("default argument for template parameter for class "
4432                  "enclosing %qD");
4433     }
4434
4435   return no_errors;
4436 }
4437
4438 /* Worker for push_template_decl_real, called via
4439    for_each_template_parm.  DATA is really an int, indicating the
4440    level of the parameters we are interested in.  If T is a template
4441    parameter of that level, return nonzero.  */
4442
4443 static int
4444 template_parm_this_level_p (tree t, void* data)
4445 {
4446   int this_level = *(int *)data;
4447   int level;
4448
4449   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4450     level = TEMPLATE_PARM_LEVEL (t);
4451   else
4452     level = TEMPLATE_TYPE_LEVEL (t);
4453   return level == this_level;
4454 }
4455
4456 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4457    parameters given by current_template_args, or reuses a
4458    previously existing one, if appropriate.  Returns the DECL, or an
4459    equivalent one, if it is replaced via a call to duplicate_decls.
4460
4461    If IS_FRIEND is true, DECL is a friend declaration.  */
4462
4463 tree
4464 push_template_decl_real (tree decl, bool is_friend)
4465 {
4466   tree tmpl;
4467   tree args;
4468   tree info;
4469   tree ctx;
4470   int primary;
4471   int is_partial;
4472   int new_template_p = 0;
4473   /* True if the template is a member template, in the sense of
4474      [temp.mem].  */
4475   bool member_template_p = false;
4476
4477   if (decl == error_mark_node || !current_template_parms)
4478     return error_mark_node;
4479
4480   /* See if this is a partial specialization.  */
4481   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4482                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4483                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4484
4485   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4486     is_friend = true;
4487
4488   if (is_friend)
4489     /* For a friend, we want the context of the friend function, not
4490        the type of which it is a friend.  */
4491     ctx = CP_DECL_CONTEXT (decl);
4492   else if (CP_DECL_CONTEXT (decl)
4493            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4494     /* In the case of a virtual function, we want the class in which
4495        it is defined.  */
4496     ctx = CP_DECL_CONTEXT (decl);
4497   else
4498     /* Otherwise, if we're currently defining some class, the DECL
4499        is assumed to be a member of the class.  */
4500     ctx = current_scope ();
4501
4502   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4503     ctx = NULL_TREE;
4504
4505   if (!DECL_CONTEXT (decl))
4506     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4507
4508   /* See if this is a primary template.  */
4509   if (is_friend && ctx)
4510     /* A friend template that specifies a class context, i.e.
4511          template <typename T> friend void A<T>::f();
4512        is not primary.  */
4513     primary = 0;
4514   else
4515     primary = template_parm_scope_p ();
4516
4517   if (primary)
4518     {
4519       if (DECL_CLASS_SCOPE_P (decl))
4520         member_template_p = true;
4521       if (TREE_CODE (decl) == TYPE_DECL
4522           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4523         {
4524           error ("template class without a name");
4525           return error_mark_node;
4526         }
4527       else if (TREE_CODE (decl) == FUNCTION_DECL)
4528         {
4529           if (DECL_DESTRUCTOR_P (decl))
4530             {
4531               /* [temp.mem]
4532
4533                  A destructor shall not be a member template.  */
4534               error ("destructor %qD declared as member template", decl);
4535               return error_mark_node;
4536             }
4537           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4538               && (!prototype_p (TREE_TYPE (decl))
4539                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4540                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4541                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4542                       == void_list_node)))
4543             {
4544               /* [basic.stc.dynamic.allocation]
4545
4546                  An allocation function can be a function
4547                  template. ... Template allocation functions shall
4548                  have two or more parameters.  */
4549               error ("invalid template declaration of %qD", decl);
4550               return error_mark_node;
4551             }
4552         }
4553       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4554                && CLASS_TYPE_P (TREE_TYPE (decl)))
4555         /* OK */;
4556       else if (TREE_CODE (decl) == TYPE_DECL
4557                && TYPE_DECL_ALIAS_P (decl))
4558         /* alias-declaration */
4559         gcc_assert (!DECL_ARTIFICIAL (decl));
4560       else
4561         {
4562           error ("template declaration of %q#D", decl);
4563           return error_mark_node;
4564         }
4565     }
4566
4567   /* Check to see that the rules regarding the use of default
4568      arguments are not being violated.  */
4569   check_default_tmpl_args (decl, current_template_parms,
4570                            primary, is_partial, /*is_friend_decl=*/0);
4571
4572   /* Ensure that there are no parameter packs in the type of this
4573      declaration that have not been expanded.  */
4574   if (TREE_CODE (decl) == FUNCTION_DECL)
4575     {
4576       /* Check each of the arguments individually to see if there are
4577          any bare parameter packs.  */
4578       tree type = TREE_TYPE (decl);
4579       tree arg = DECL_ARGUMENTS (decl);
4580       tree argtype = TYPE_ARG_TYPES (type);
4581
4582       while (arg && argtype)
4583         {
4584           if (!FUNCTION_PARAMETER_PACK_P (arg)
4585               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4586             {
4587             /* This is a PARM_DECL that contains unexpanded parameter
4588                packs. We have already complained about this in the
4589                check_for_bare_parameter_packs call, so just replace
4590                these types with ERROR_MARK_NODE.  */
4591               TREE_TYPE (arg) = error_mark_node;
4592               TREE_VALUE (argtype) = error_mark_node;
4593             }
4594
4595           arg = DECL_CHAIN (arg);
4596           argtype = TREE_CHAIN (argtype);
4597         }
4598
4599       /* Check for bare parameter packs in the return type and the
4600          exception specifiers.  */
4601       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4602         /* Errors were already issued, set return type to int
4603            as the frontend doesn't expect error_mark_node as
4604            the return type.  */
4605         TREE_TYPE (type) = integer_type_node;
4606       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4607         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4608     }
4609   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
4610                                             && TYPE_DECL_ALIAS_P (decl))
4611                                            ? DECL_ORIGINAL_TYPE (decl)
4612                                            : TREE_TYPE (decl)))
4613     {
4614       TREE_TYPE (decl) = error_mark_node;
4615       return error_mark_node;
4616     }
4617
4618   if (is_partial)
4619     return process_partial_specialization (decl);
4620
4621   args = current_template_args ();
4622
4623   if (!ctx
4624       || TREE_CODE (ctx) == FUNCTION_DECL
4625       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4626       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4627     {
4628       if (DECL_LANG_SPECIFIC (decl)
4629           && DECL_TEMPLATE_INFO (decl)
4630           && DECL_TI_TEMPLATE (decl))
4631         tmpl = DECL_TI_TEMPLATE (decl);
4632       /* If DECL is a TYPE_DECL for a class-template, then there won't
4633          be DECL_LANG_SPECIFIC.  The information equivalent to
4634          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4635       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4636                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4637                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4638         {
4639           /* Since a template declaration already existed for this
4640              class-type, we must be redeclaring it here.  Make sure
4641              that the redeclaration is valid.  */
4642           redeclare_class_template (TREE_TYPE (decl),
4643                                     current_template_parms);
4644           /* We don't need to create a new TEMPLATE_DECL; just use the
4645              one we already had.  */
4646           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4647         }
4648       else
4649         {
4650           tmpl = build_template_decl (decl, current_template_parms,
4651                                       member_template_p);
4652           new_template_p = 1;
4653
4654           if (DECL_LANG_SPECIFIC (decl)
4655               && DECL_TEMPLATE_SPECIALIZATION (decl))
4656             {
4657               /* A specialization of a member template of a template
4658                  class.  */
4659               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4660               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4661               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4662             }
4663         }
4664     }
4665   else
4666     {
4667       tree a, t, current, parms;
4668       int i;
4669       tree tinfo = get_template_info (decl);
4670
4671       if (!tinfo)
4672         {
4673           error ("template definition of non-template %q#D", decl);
4674           return error_mark_node;
4675         }
4676
4677       tmpl = TI_TEMPLATE (tinfo);
4678
4679       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4680           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4681           && DECL_TEMPLATE_SPECIALIZATION (decl)
4682           && DECL_MEMBER_TEMPLATE_P (tmpl))
4683         {
4684           tree new_tmpl;
4685
4686           /* The declaration is a specialization of a member
4687              template, declared outside the class.  Therefore, the
4688              innermost template arguments will be NULL, so we
4689              replace them with the arguments determined by the
4690              earlier call to check_explicit_specialization.  */
4691           args = DECL_TI_ARGS (decl);
4692
4693           new_tmpl
4694             = build_template_decl (decl, current_template_parms,
4695                                    member_template_p);
4696           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4697           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4698           DECL_TI_TEMPLATE (decl) = new_tmpl;
4699           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4700           DECL_TEMPLATE_INFO (new_tmpl)
4701             = build_template_info (tmpl, args);
4702
4703           register_specialization (new_tmpl,
4704                                    most_general_template (tmpl),
4705                                    args,
4706                                    is_friend, 0);
4707           return decl;
4708         }
4709
4710       /* Make sure the template headers we got make sense.  */
4711
4712       parms = DECL_TEMPLATE_PARMS (tmpl);
4713       i = TMPL_PARMS_DEPTH (parms);
4714       if (TMPL_ARGS_DEPTH (args) != i)
4715         {
4716           error ("expected %d levels of template parms for %q#D, got %d",
4717                  i, decl, TMPL_ARGS_DEPTH (args));
4718         }
4719       else
4720         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4721           {
4722             a = TMPL_ARGS_LEVEL (args, i);
4723             t = INNERMOST_TEMPLATE_PARMS (parms);
4724
4725             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4726               {
4727                 if (current == decl)
4728                   error ("got %d template parameters for %q#D",
4729                          TREE_VEC_LENGTH (a), decl);
4730                 else
4731                   error ("got %d template parameters for %q#T",
4732                          TREE_VEC_LENGTH (a), current);
4733                 error ("  but %d required", TREE_VEC_LENGTH (t));
4734                 return error_mark_node;
4735               }
4736
4737             if (current == decl)
4738               current = ctx;
4739             else if (current == NULL_TREE)
4740               /* Can happen in erroneous input.  */
4741               break;
4742             else
4743               current = (TYPE_P (current)
4744                          ? TYPE_CONTEXT (current)
4745                          : DECL_CONTEXT (current));
4746           }
4747
4748       /* Check that the parms are used in the appropriate qualifying scopes
4749          in the declarator.  */
4750       if (!comp_template_args
4751           (TI_ARGS (tinfo),
4752            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4753         {
4754           error ("\
4755 template arguments to %qD do not match original template %qD",
4756                  decl, DECL_TEMPLATE_RESULT (tmpl));
4757           if (!uses_template_parms (TI_ARGS (tinfo)))
4758             inform (input_location, "use template<> for an explicit specialization");
4759           /* Avoid crash in import_export_decl.  */
4760           DECL_INTERFACE_KNOWN (decl) = 1;
4761           return error_mark_node;
4762         }
4763     }
4764
4765   DECL_TEMPLATE_RESULT (tmpl) = decl;
4766   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4767
4768   /* Push template declarations for global functions and types.  Note
4769      that we do not try to push a global template friend declared in a
4770      template class; such a thing may well depend on the template
4771      parameters of the class.  */
4772   if (new_template_p && !ctx
4773       && !(is_friend && template_class_depth (current_class_type) > 0))
4774     {
4775       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4776       if (tmpl == error_mark_node)
4777         return error_mark_node;
4778
4779       /* Hide template friend classes that haven't been declared yet.  */
4780       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4781         {
4782           DECL_ANTICIPATED (tmpl) = 1;
4783           DECL_FRIEND_P (tmpl) = 1;
4784         }
4785     }
4786
4787   if (primary)
4788     {
4789       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4790       int i;
4791
4792       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4793       if (DECL_CONV_FN_P (tmpl))
4794         {
4795           int depth = TMPL_PARMS_DEPTH (parms);
4796
4797           /* It is a conversion operator. See if the type converted to
4798              depends on innermost template operands.  */
4799
4800           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4801                                          depth))
4802             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4803         }
4804
4805       /* Give template template parms a DECL_CONTEXT of the template
4806          for which they are a parameter.  */
4807       parms = INNERMOST_TEMPLATE_PARMS (parms);
4808       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4809         {
4810           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4811           if (TREE_CODE (parm) == TEMPLATE_DECL)
4812             DECL_CONTEXT (parm) = tmpl;
4813         }
4814     }
4815
4816   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4817      back to its most general template.  If TMPL is a specialization,
4818      ARGS may only have the innermost set of arguments.  Add the missing
4819      argument levels if necessary.  */
4820   if (DECL_TEMPLATE_INFO (tmpl))
4821     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4822
4823   info = build_template_info (tmpl, args);
4824
4825   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4826     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4827   else
4828     {
4829       if (primary && !DECL_LANG_SPECIFIC (decl))
4830         retrofit_lang_decl (decl);
4831       if (DECL_LANG_SPECIFIC (decl))
4832         DECL_TEMPLATE_INFO (decl) = info;
4833     }
4834
4835   return DECL_TEMPLATE_RESULT (tmpl);
4836 }
4837
4838 tree
4839 push_template_decl (tree decl)
4840 {
4841   return push_template_decl_real (decl, false);
4842 }
4843
4844 /* Called when a class template TYPE is redeclared with the indicated
4845    template PARMS, e.g.:
4846
4847      template <class T> struct S;
4848      template <class T> struct S {};  */
4849
4850 bool
4851 redeclare_class_template (tree type, tree parms)
4852 {
4853   tree tmpl;
4854   tree tmpl_parms;
4855   int i;
4856
4857   if (!TYPE_TEMPLATE_INFO (type))
4858     {
4859       error ("%qT is not a template type", type);
4860       return false;
4861     }
4862
4863   tmpl = TYPE_TI_TEMPLATE (type);
4864   if (!PRIMARY_TEMPLATE_P (tmpl))
4865     /* The type is nested in some template class.  Nothing to worry
4866        about here; there are no new template parameters for the nested
4867        type.  */
4868     return true;
4869
4870   if (!parms)
4871     {
4872       error ("template specifiers not specified in declaration of %qD",
4873              tmpl);
4874       return false;
4875     }
4876
4877   parms = INNERMOST_TEMPLATE_PARMS (parms);
4878   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4879
4880   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4881     {
4882       error_n (input_location, TREE_VEC_LENGTH (parms),
4883                "redeclared with %d template parameter",
4884                "redeclared with %d template parameters",
4885                TREE_VEC_LENGTH (parms));
4886       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4887                 "previous declaration %q+D used %d template parameter",
4888                 "previous declaration %q+D used %d template parameters",
4889                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4890       return false;
4891     }
4892
4893   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4894     {
4895       tree tmpl_parm;
4896       tree parm;
4897       tree tmpl_default;
4898       tree parm_default;
4899
4900       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4901           || TREE_VEC_ELT (parms, i) == error_mark_node)
4902         continue;
4903
4904       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4905       if (tmpl_parm == error_mark_node)
4906         return false;
4907
4908       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4909       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4910       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4911
4912       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4913          TEMPLATE_DECL.  */
4914       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4915           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4916               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4917           || (TREE_CODE (tmpl_parm) != PARM_DECL
4918               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4919                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4920           || (TREE_CODE (tmpl_parm) == PARM_DECL
4921               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4922                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4923         {
4924           error ("template parameter %q+#D", tmpl_parm);
4925           error ("redeclared here as %q#D", parm);
4926           return false;
4927         }
4928
4929       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4930         {
4931           /* We have in [temp.param]:
4932
4933              A template-parameter may not be given default arguments
4934              by two different declarations in the same scope.  */
4935           error_at (input_location, "redefinition of default argument for %q#D", parm);
4936           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4937                   "original definition appeared here");
4938           return false;
4939         }
4940
4941       if (parm_default != NULL_TREE)
4942         /* Update the previous template parameters (which are the ones
4943            that will really count) with the new default value.  */
4944         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4945       else if (tmpl_default != NULL_TREE)
4946         /* Update the new parameters, too; they'll be used as the
4947            parameters for any members.  */
4948         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4949     }
4950
4951     return true;
4952 }
4953
4954 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4955    (possibly simplified) expression.  */
4956
4957 static tree
4958 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
4959 {
4960   if (expr == NULL_TREE)
4961     return NULL_TREE;
4962
4963   /* If we're in a template, but EXPR isn't value dependent, simplify
4964      it.  We're supposed to treat:
4965
4966        template <typename T> void f(T[1 + 1]);
4967        template <typename T> void f(T[2]);
4968
4969      as two declarations of the same function, for example.  */
4970   if (processing_template_decl
4971       && !type_dependent_expression_p (expr)
4972       && potential_constant_expression (expr)
4973       && !value_dependent_expression_p (expr))
4974     {
4975       HOST_WIDE_INT saved_processing_template_decl;
4976
4977       saved_processing_template_decl = processing_template_decl;
4978       processing_template_decl = 0;
4979       expr = tsubst_copy_and_build (expr,
4980                                     /*args=*/NULL_TREE,
4981                                     complain,
4982                                     /*in_decl=*/NULL_TREE,
4983                                     /*function_p=*/false,
4984                                     /*integral_constant_expression_p=*/true);
4985       processing_template_decl = saved_processing_template_decl;
4986     }
4987   return expr;
4988 }
4989
4990 tree
4991 fold_non_dependent_expr (tree expr)
4992 {
4993   return fold_non_dependent_expr_sfinae (expr, tf_error);
4994 }
4995
4996 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
4997    template declaration, or a TYPE_DECL for an alias declaration.  */
4998
4999 bool
5000 alias_type_or_template_p (tree t)
5001 {
5002   if (t == NULL_TREE)
5003     return false;
5004   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5005           || (TYPE_P (t)
5006               && TYPE_NAME (t)
5007               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5008           || DECL_ALIAS_TEMPLATE_P (t));
5009 }
5010
5011 /* Return TRUE iff is a specialization of an alias template.  */
5012
5013 bool
5014 alias_template_specialization_p (tree t)
5015 {
5016   if (t == NULL_TREE)
5017     return false;
5018   return (primary_template_instantiation_p (t)
5019           && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (t)));
5020 }
5021
5022 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5023    must be a function or a pointer-to-function type, as specified
5024    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5025    and check that the resulting function has external linkage.  */
5026
5027 static tree
5028 convert_nontype_argument_function (tree type, tree expr)
5029 {
5030   tree fns = expr;
5031   tree fn, fn_no_ptr;
5032   linkage_kind linkage;
5033
5034   fn = instantiate_type (type, fns, tf_none);
5035   if (fn == error_mark_node)
5036     return error_mark_node;
5037
5038   fn_no_ptr = fn;
5039   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5040     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5041   if (BASELINK_P (fn_no_ptr))
5042     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5043  
5044   /* [temp.arg.nontype]/1
5045
5046      A template-argument for a non-type, non-template template-parameter
5047      shall be one of:
5048      [...]
5049      -- the address of an object or function with external [C++11: or
5050         internal] linkage.  */
5051   linkage = decl_linkage (fn_no_ptr);
5052   if (cxx_dialect >= cxx0x ? linkage == lk_none : linkage != lk_external)
5053     {
5054       if (cxx_dialect >= cxx0x)
5055         error ("%qE is not a valid template argument for type %qT "
5056                "because %qD has no linkage",
5057                expr, type, fn_no_ptr);
5058       else
5059         error ("%qE is not a valid template argument for type %qT "
5060                "because %qD does not have external linkage",
5061                expr, type, fn_no_ptr);
5062       return NULL_TREE;
5063     }
5064
5065   return fn;
5066 }
5067
5068 /* Subroutine of convert_nontype_argument.
5069    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5070    Emit an error otherwise.  */
5071
5072 static bool
5073 check_valid_ptrmem_cst_expr (tree type, tree expr,
5074                              tsubst_flags_t complain)
5075 {
5076   STRIP_NOPS (expr);
5077   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5078     return true;
5079   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5080     return true;
5081   if (complain & tf_error)
5082     {
5083       error ("%qE is not a valid template argument for type %qT",
5084              expr, type);
5085       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5086     }
5087   return false;
5088 }
5089
5090 /* Returns TRUE iff the address of OP is value-dependent.
5091
5092    14.6.2.4 [temp.dep.temp]:
5093    A non-integral non-type template-argument is dependent if its type is
5094    dependent or it has either of the following forms
5095      qualified-id
5096      & qualified-id
5097    and contains a nested-name-specifier which specifies a class-name that
5098    names a dependent type.
5099
5100    We generalize this to just say that the address of a member of a
5101    dependent class is value-dependent; the above doesn't cover the
5102    address of a static data member named with an unqualified-id.  */
5103
5104 static bool
5105 has_value_dependent_address (tree op)
5106 {
5107   /* We could use get_inner_reference here, but there's no need;
5108      this is only relevant for template non-type arguments, which
5109      can only be expressed as &id-expression.  */
5110   if (DECL_P (op))
5111     {
5112       tree ctx = CP_DECL_CONTEXT (op);
5113       if (TYPE_P (ctx) && dependent_type_p (ctx))
5114         return true;
5115     }
5116
5117   return false;
5118 }
5119
5120 /* The next set of functions are used for providing helpful explanatory
5121    diagnostics for failed overload resolution.  Their messages should be
5122    indented by two spaces for consistency with the messages in
5123    call.c  */
5124
5125 static int
5126 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5127 {
5128   return 0;
5129 }
5130
5131 static int
5132 unify_parameter_deduction_failure (bool explain_p, tree parm)
5133 {
5134   if (explain_p)
5135     inform (input_location,
5136             "  couldn't deduce template parameter %qD", parm);
5137   return 1;
5138 }
5139
5140 static int
5141 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5142 {
5143   return 1;
5144 }
5145
5146 static int
5147 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5148 {
5149   if (explain_p)
5150     inform (input_location,
5151             "  types %qT and %qT have incompatible cv-qualifiers",
5152             parm, arg);
5153   return 1;
5154 }
5155
5156 static int
5157 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5158 {
5159   if (explain_p)
5160     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5161   return 1;
5162 }
5163
5164 static int
5165 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5166 {
5167   if (explain_p)
5168     inform (input_location,
5169             "  template parameter %qD is not a parameter pack, but "
5170             "argument %qD is",
5171             parm, arg);
5172   return 1;
5173 }
5174
5175 static int
5176 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5177 {
5178   if (explain_p)
5179     inform (input_location,
5180             "  template argument %qE does not match "
5181             "pointer-to-member constant %qE",
5182             arg, parm);
5183   return 1;
5184 }
5185
5186 static int
5187 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5188 {
5189   if (explain_p)
5190     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5191   return 1;
5192 }
5193
5194 static int
5195 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5196 {
5197   if (explain_p)
5198     inform (input_location,
5199             "  inconsistent parameter pack deduction with %qT and %qT",
5200             old_arg, new_arg);
5201   return 1;
5202 }
5203
5204 static int
5205 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5206 {
5207   if (explain_p)
5208     {
5209       if (TYPE_P (parm))
5210         inform (input_location,
5211                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
5212                 parm, first, second);
5213       else
5214         inform (input_location,
5215                 "  deduced conflicting values for non-type parameter "
5216                 "%qE (%qE and %qE)", parm, first, second);
5217     }
5218   return 1;
5219 }
5220
5221 static int
5222 unify_vla_arg (bool explain_p, tree arg)
5223 {
5224   if (explain_p)
5225     inform (input_location,
5226             "  variable-sized array type %qT is not "
5227             "a valid template argument",
5228             arg);
5229   return 1;
5230 }
5231
5232 static int
5233 unify_method_type_error (bool explain_p, tree arg)
5234 {
5235   if (explain_p)
5236     inform (input_location,
5237             "  member function type %qT is not a valid template argument",
5238             arg);
5239   return 1;
5240 }
5241
5242 static int
5243 unify_arity (bool explain_p, int have, int wanted)
5244 {
5245   if (explain_p)
5246     inform_n (input_location, wanted,
5247               "  candidate expects %d argument, %d provided",
5248               "  candidate expects %d arguments, %d provided",
5249               wanted, have);
5250   return 1;
5251 }
5252
5253 static int
5254 unify_too_many_arguments (bool explain_p, int have, int wanted)
5255 {
5256   return unify_arity (explain_p, have, wanted);
5257 }
5258
5259 static int
5260 unify_too_few_arguments (bool explain_p, int have, int wanted)
5261 {
5262   return unify_arity (explain_p, have, wanted);
5263 }
5264
5265 static int
5266 unify_arg_conversion (bool explain_p, tree to_type,
5267                       tree from_type, tree arg)
5268 {
5269   if (explain_p)
5270     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5271             arg, from_type, to_type);
5272   return 1;
5273 }
5274
5275 static int
5276 unify_no_common_base (bool explain_p, enum template_base_result r,
5277                       tree parm, tree arg)
5278 {
5279   if (explain_p)
5280     switch (r)
5281       {
5282       case tbr_ambiguous_baseclass:
5283         inform (input_location, "  %qT is an ambiguous base class of %qT",
5284                 arg, parm);
5285         break;
5286       default:
5287         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5288         break;
5289       }
5290   return 1;
5291 }
5292
5293 static int
5294 unify_inconsistent_template_template_parameters (bool explain_p)
5295 {
5296   if (explain_p)
5297     inform (input_location,
5298             "  template parameters of a template template argument are "
5299             "inconsistent with other deduced template arguments");
5300   return 1;
5301 }
5302
5303 static int
5304 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5305 {
5306   if (explain_p)
5307     inform (input_location,
5308             "  can't deduce a template for %qT from non-template type %qT",
5309             parm, arg);
5310   return 1;
5311 }
5312
5313 static int
5314 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5315 {
5316   if (explain_p)
5317     inform (input_location,
5318             "  template argument %qE does not match %qD", arg, parm);
5319   return 1;
5320 }
5321
5322 static int
5323 unify_overload_resolution_failure (bool explain_p, tree arg)
5324 {
5325   if (explain_p)
5326     inform (input_location,
5327             "  could not resolve address from overloaded function %qE",
5328             arg);
5329   return 1;
5330 }
5331
5332 /* Attempt to convert the non-type template parameter EXPR to the
5333    indicated TYPE.  If the conversion is successful, return the
5334    converted value.  If the conversion is unsuccessful, return
5335    NULL_TREE if we issued an error message, or error_mark_node if we
5336    did not.  We issue error messages for out-and-out bad template
5337    parameters, but not simply because the conversion failed, since we
5338    might be just trying to do argument deduction.  Both TYPE and EXPR
5339    must be non-dependent.
5340
5341    The conversion follows the special rules described in
5342    [temp.arg.nontype], and it is much more strict than an implicit
5343    conversion.
5344
5345    This function is called twice for each template argument (see
5346    lookup_template_class for a more accurate description of this
5347    problem). This means that we need to handle expressions which
5348    are not valid in a C++ source, but can be created from the
5349    first call (for instance, casts to perform conversions). These
5350    hacks can go away after we fix the double coercion problem.  */
5351
5352 static tree
5353 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5354 {
5355   tree expr_type;
5356
5357   /* Detect immediately string literals as invalid non-type argument.
5358      This special-case is not needed for correctness (we would easily
5359      catch this later), but only to provide better diagnostic for this
5360      common user mistake. As suggested by DR 100, we do not mention
5361      linkage issues in the diagnostic as this is not the point.  */
5362   /* FIXME we're making this OK.  */
5363   if (TREE_CODE (expr) == STRING_CST)
5364     {
5365       if (complain & tf_error)
5366         error ("%qE is not a valid template argument for type %qT "
5367                "because string literals can never be used in this context",
5368                expr, type);
5369       return NULL_TREE;
5370     }
5371
5372   /* Add the ADDR_EXPR now for the benefit of
5373      value_dependent_expression_p.  */
5374   if (TYPE_PTROBV_P (type)
5375       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5376     expr = decay_conversion (expr);
5377
5378   /* If we are in a template, EXPR may be non-dependent, but still
5379      have a syntactic, rather than semantic, form.  For example, EXPR
5380      might be a SCOPE_REF, rather than the VAR_DECL to which the
5381      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5382      so that access checking can be performed when the template is
5383      instantiated -- but here we need the resolved form so that we can
5384      convert the argument.  */
5385   if (TYPE_REF_OBJ_P (type)
5386       && has_value_dependent_address (expr))
5387     /* If we want the address and it's value-dependent, don't fold.  */;
5388   else if (!type_unknown_p (expr))
5389     expr = fold_non_dependent_expr_sfinae (expr, complain);
5390   if (error_operand_p (expr))
5391     return error_mark_node;
5392   expr_type = TREE_TYPE (expr);
5393   if (TREE_CODE (type) == REFERENCE_TYPE)
5394     expr = mark_lvalue_use (expr);
5395   else
5396     expr = mark_rvalue_use (expr);
5397
5398   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5399      to a non-type argument of "nullptr".  */
5400   if (expr == nullptr_node
5401       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5402     expr = convert (type, expr);
5403
5404   /* In C++11, integral or enumeration non-type template arguments can be
5405      arbitrary constant expressions.  Pointer and pointer to
5406      member arguments can be general constant expressions that evaluate
5407      to a null value, but otherwise still need to be of a specific form.  */
5408   if (cxx_dialect >= cxx0x)
5409     {
5410       if (TREE_CODE (expr) == PTRMEM_CST)
5411         /* A PTRMEM_CST is already constant, and a valid template
5412            argument for a parameter of pointer to member type, we just want
5413            to leave it in that form rather than lower it to a
5414            CONSTRUCTOR.  */;
5415       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5416         expr = maybe_constant_value (expr);
5417       else if (TYPE_PTR_P (type)
5418                || TYPE_PTR_TO_MEMBER_P (type))
5419         {
5420           tree folded = maybe_constant_value (expr);
5421           if (TYPE_PTR_P (type) ? integer_zerop (folded)
5422               : null_member_pointer_value_p (folded))
5423             expr = folded;
5424         }
5425     }
5426
5427   /* HACK: Due to double coercion, we can get a
5428      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5429      which is the tree that we built on the first call (see
5430      below when coercing to reference to object or to reference to
5431      function). We just strip everything and get to the arg.
5432      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5433      for examples.  */
5434   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5435     {
5436       tree probe_type, probe = expr;
5437       if (REFERENCE_REF_P (probe))
5438         probe = TREE_OPERAND (probe, 0);
5439       probe_type = TREE_TYPE (probe);
5440       if (TREE_CODE (probe) == NOP_EXPR)
5441         {
5442           /* ??? Maybe we could use convert_from_reference here, but we
5443              would need to relax its constraints because the NOP_EXPR
5444              could actually change the type to something more cv-qualified,
5445              and this is not folded by convert_from_reference.  */
5446           tree addr = TREE_OPERAND (probe, 0);
5447           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5448           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5449           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5450           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5451                       (TREE_TYPE (probe_type),
5452                        TREE_TYPE (TREE_TYPE (addr))));
5453
5454           expr = TREE_OPERAND (addr, 0);
5455           expr_type = TREE_TYPE (expr);
5456         }
5457     }
5458
5459   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5460      parameter is a pointer to object, through decay and
5461      qualification conversion. Let's strip everything.  */
5462   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5463     {
5464       STRIP_NOPS (expr);
5465       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5466       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5467       /* Skip the ADDR_EXPR only if it is part of the decay for
5468          an array. Otherwise, it is part of the original argument
5469          in the source code.  */
5470       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5471         expr = TREE_OPERAND (expr, 0);
5472       expr_type = TREE_TYPE (expr);
5473     }
5474
5475   /* [temp.arg.nontype]/5, bullet 1
5476
5477      For a non-type template-parameter of integral or enumeration type,
5478      integral promotions (_conv.prom_) and integral conversions
5479      (_conv.integral_) are applied.  */
5480   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5481     {
5482       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5483       t = maybe_constant_value (t);
5484       if (t != error_mark_node)
5485         expr = t;
5486
5487       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5488         return error_mark_node;
5489
5490       /* Notice that there are constant expressions like '4 % 0' which
5491          do not fold into integer constants.  */
5492       if (TREE_CODE (expr) != INTEGER_CST)
5493         {
5494           if (complain & tf_error)
5495             {
5496               int errs = errorcount, warns = warningcount;
5497               if (processing_template_decl
5498                   && !require_potential_constant_expression (expr))
5499                 return NULL_TREE;
5500               expr = cxx_constant_value (expr);
5501               if (errorcount > errs || warningcount > warns)
5502                 inform (EXPR_LOC_OR_HERE (expr),
5503                         "in template argument for type %qT ", type);
5504               if (expr == error_mark_node)
5505                 return NULL_TREE;
5506               /* else cxx_constant_value complained but gave us
5507                  a real constant, so go ahead.  */
5508               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5509             }
5510           else
5511             return NULL_TREE;
5512         }
5513     }
5514   /* [temp.arg.nontype]/5, bullet 2
5515
5516      For a non-type template-parameter of type pointer to object,
5517      qualification conversions (_conv.qual_) and the array-to-pointer
5518      conversion (_conv.array_) are applied.  */
5519   else if (TYPE_PTROBV_P (type))
5520     {
5521       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5522
5523          A template-argument for a non-type, non-template template-parameter
5524          shall be one of: [...]
5525
5526          -- the name of a non-type template-parameter;
5527          -- the address of an object or function with external linkage, [...]
5528             expressed as "& id-expression" where the & is optional if the name
5529             refers to a function or array, or if the corresponding
5530             template-parameter is a reference.
5531
5532         Here, we do not care about functions, as they are invalid anyway
5533         for a parameter of type pointer-to-object.  */
5534
5535       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5536         /* Non-type template parameters are OK.  */
5537         ;
5538       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5539         /* Null pointer values are OK in C++11.  */;
5540       else if (TREE_CODE (expr) != ADDR_EXPR
5541                && TREE_CODE (expr_type) != ARRAY_TYPE)
5542         {
5543           if (TREE_CODE (expr) == VAR_DECL)
5544             {
5545               error ("%qD is not a valid template argument "
5546                      "because %qD is a variable, not the address of "
5547                      "a variable",
5548                      expr, expr);
5549               return NULL_TREE;
5550             }
5551           /* Other values, like integer constants, might be valid
5552              non-type arguments of some other type.  */
5553           return error_mark_node;
5554         }
5555       else
5556         {
5557           tree decl;
5558
5559           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5560                   ? TREE_OPERAND (expr, 0) : expr);
5561           if (TREE_CODE (decl) != VAR_DECL)
5562             {
5563               error ("%qE is not a valid template argument of type %qT "
5564                      "because %qE is not a variable",
5565                      expr, type, decl);
5566               return NULL_TREE;
5567             }
5568           else if (cxx_dialect < cxx0x && !DECL_EXTERNAL_LINKAGE_P (decl))
5569             {
5570               error ("%qE is not a valid template argument of type %qT "
5571                      "because %qD does not have external linkage",
5572                      expr, type, decl);
5573               return NULL_TREE;
5574             }
5575           else if (cxx_dialect >= cxx0x && decl_linkage (decl) == lk_none)
5576             {
5577               error ("%qE is not a valid template argument of type %qT "
5578                      "because %qD has no linkage",
5579                      expr, type, decl);
5580               return NULL_TREE;
5581             }
5582         }
5583
5584       expr = decay_conversion (expr);
5585       if (expr == error_mark_node)
5586         return error_mark_node;
5587
5588       expr = perform_qualification_conversions (type, expr);
5589       if (expr == error_mark_node)
5590         return error_mark_node;
5591     }
5592   /* [temp.arg.nontype]/5, bullet 3
5593
5594      For a non-type template-parameter of type reference to object, no
5595      conversions apply. The type referred to by the reference may be more
5596      cv-qualified than the (otherwise identical) type of the
5597      template-argument. The template-parameter is bound directly to the
5598      template-argument, which must be an lvalue.  */
5599   else if (TYPE_REF_OBJ_P (type))
5600     {
5601       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5602                                                       expr_type))
5603         return error_mark_node;
5604
5605       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5606         {
5607           error ("%qE is not a valid template argument for type %qT "
5608                  "because of conflicts in cv-qualification", expr, type);
5609           return NULL_TREE;
5610         }
5611
5612       if (!real_lvalue_p (expr))
5613         {
5614           error ("%qE is not a valid template argument for type %qT "
5615                  "because it is not an lvalue", expr, type);
5616           return NULL_TREE;
5617         }
5618
5619       /* [temp.arg.nontype]/1
5620
5621          A template-argument for a non-type, non-template template-parameter
5622          shall be one of: [...]
5623
5624          -- the address of an object or function with external linkage.  */
5625       if (TREE_CODE (expr) == INDIRECT_REF
5626           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5627         {
5628           expr = TREE_OPERAND (expr, 0);
5629           if (DECL_P (expr))
5630             {
5631               error ("%q#D is not a valid template argument for type %qT "
5632                      "because a reference variable does not have a constant "
5633                      "address", expr, type);
5634               return NULL_TREE;
5635             }
5636         }
5637
5638       if (!DECL_P (expr))
5639         {
5640           error ("%qE is not a valid template argument for type %qT "
5641                  "because it is not an object with external linkage",
5642                  expr, type);
5643           return NULL_TREE;
5644         }
5645
5646       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5647         {
5648           error ("%qE is not a valid template argument for type %qT "
5649                  "because object %qD has not external linkage",
5650                  expr, type, expr);
5651           return NULL_TREE;
5652         }
5653
5654       expr = build_nop (type, build_address (expr));
5655     }
5656   /* [temp.arg.nontype]/5, bullet 4
5657
5658      For a non-type template-parameter of type pointer to function, only
5659      the function-to-pointer conversion (_conv.func_) is applied. If the
5660      template-argument represents a set of overloaded functions (or a
5661      pointer to such), the matching function is selected from the set
5662      (_over.over_).  */
5663   else if (TYPE_PTRFN_P (type))
5664     {
5665       /* If the argument is a template-id, we might not have enough
5666          context information to decay the pointer.  */
5667       if (!type_unknown_p (expr_type))
5668         {
5669           expr = decay_conversion (expr);
5670           if (expr == error_mark_node)
5671             return error_mark_node;
5672         }
5673
5674       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5675         /* Null pointer values are OK in C++11.  */
5676         return perform_qualification_conversions (type, expr);
5677
5678       expr = convert_nontype_argument_function (type, expr);
5679       if (!expr || expr == error_mark_node)
5680         return expr;
5681
5682       if (TREE_CODE (expr) != ADDR_EXPR)
5683         {
5684           error ("%qE is not a valid template argument for type %qT", expr, type);
5685           error ("it must be the address of a function with external linkage");
5686           return NULL_TREE;
5687         }
5688     }
5689   /* [temp.arg.nontype]/5, bullet 5
5690
5691      For a non-type template-parameter of type reference to function, no
5692      conversions apply. If the template-argument represents a set of
5693      overloaded functions, the matching function is selected from the set
5694      (_over.over_).  */
5695   else if (TYPE_REFFN_P (type))
5696     {
5697       if (TREE_CODE (expr) == ADDR_EXPR)
5698         {
5699           error ("%qE is not a valid template argument for type %qT "
5700                  "because it is a pointer", expr, type);
5701           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5702           return NULL_TREE;
5703         }
5704
5705       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5706       if (!expr || expr == error_mark_node)
5707         return expr;
5708
5709       expr = build_nop (type, build_address (expr));
5710     }
5711   /* [temp.arg.nontype]/5, bullet 6
5712
5713      For a non-type template-parameter of type pointer to member function,
5714      no conversions apply. If the template-argument represents a set of
5715      overloaded member functions, the matching member function is selected
5716      from the set (_over.over_).  */
5717   else if (TYPE_PTRMEMFUNC_P (type))
5718     {
5719       expr = instantiate_type (type, expr, tf_none);
5720       if (expr == error_mark_node)
5721         return error_mark_node;
5722
5723       /* [temp.arg.nontype] bullet 1 says the pointer to member
5724          expression must be a pointer-to-member constant.  */
5725       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5726         return error_mark_node;
5727
5728       /* There is no way to disable standard conversions in
5729          resolve_address_of_overloaded_function (called by
5730          instantiate_type). It is possible that the call succeeded by
5731          converting &B::I to &D::I (where B is a base of D), so we need
5732          to reject this conversion here.
5733
5734          Actually, even if there was a way to disable standard conversions,
5735          it would still be better to reject them here so that we can
5736          provide a superior diagnostic.  */
5737       if (!same_type_p (TREE_TYPE (expr), type))
5738         {
5739           error ("%qE is not a valid template argument for type %qT "
5740                  "because it is of type %qT", expr, type,
5741                  TREE_TYPE (expr));
5742           /* If we are just one standard conversion off, explain.  */
5743           if (can_convert (type, TREE_TYPE (expr)))
5744             inform (input_location,
5745                     "standard conversions are not allowed in this context");
5746           return NULL_TREE;
5747         }
5748     }
5749   /* [temp.arg.nontype]/5, bullet 7
5750
5751      For a non-type template-parameter of type pointer to data member,
5752      qualification conversions (_conv.qual_) are applied.  */
5753   else if (TYPE_PTRMEM_P (type))
5754     {
5755       /* [temp.arg.nontype] bullet 1 says the pointer to member
5756          expression must be a pointer-to-member constant.  */
5757       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5758         return error_mark_node;
5759
5760       expr = perform_qualification_conversions (type, expr);
5761       if (expr == error_mark_node)
5762         return expr;
5763     }
5764   else if (NULLPTR_TYPE_P (type))
5765     {
5766       if (expr != nullptr_node)
5767         {
5768           error ("%qE is not a valid template argument for type %qT "
5769                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
5770           return NULL_TREE;
5771         }
5772       return expr;
5773     }
5774   /* A template non-type parameter must be one of the above.  */
5775   else
5776     gcc_unreachable ();
5777
5778   /* Sanity check: did we actually convert the argument to the
5779      right type?  */
5780   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5781               (type, TREE_TYPE (expr)));
5782   return expr;
5783 }
5784
5785 /* Subroutine of coerce_template_template_parms, which returns 1 if
5786    PARM_PARM and ARG_PARM match using the rule for the template
5787    parameters of template template parameters. Both PARM and ARG are
5788    template parameters; the rest of the arguments are the same as for
5789    coerce_template_template_parms.
5790  */
5791 static int
5792 coerce_template_template_parm (tree parm,
5793                               tree arg,
5794                               tsubst_flags_t complain,
5795                               tree in_decl,
5796                               tree outer_args)
5797 {
5798   if (arg == NULL_TREE || arg == error_mark_node
5799       || parm == NULL_TREE || parm == error_mark_node)
5800     return 0;
5801   
5802   if (TREE_CODE (arg) != TREE_CODE (parm))
5803     return 0;
5804   
5805   switch (TREE_CODE (parm))
5806     {
5807     case TEMPLATE_DECL:
5808       /* We encounter instantiations of templates like
5809          template <template <template <class> class> class TT>
5810          class C;  */
5811       {
5812         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5813         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5814         
5815         if (!coerce_template_template_parms
5816             (parmparm, argparm, complain, in_decl, outer_args))
5817           return 0;
5818       }
5819       /* Fall through.  */
5820       
5821     case TYPE_DECL:
5822       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5823           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5824         /* Argument is a parameter pack but parameter is not.  */
5825         return 0;
5826       break;
5827       
5828     case PARM_DECL:
5829       /* The tsubst call is used to handle cases such as
5830          
5831            template <int> class C {};
5832            template <class T, template <T> class TT> class D {};
5833            D<int, C> d;
5834
5835          i.e. the parameter list of TT depends on earlier parameters.  */
5836       if (!uses_template_parms (TREE_TYPE (arg))
5837           && !same_type_p
5838                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5839                  TREE_TYPE (arg)))
5840         return 0;
5841       
5842       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5843           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5844         /* Argument is a parameter pack but parameter is not.  */
5845         return 0;
5846       
5847       break;
5848
5849     default:
5850       gcc_unreachable ();
5851     }
5852
5853   return 1;
5854 }
5855
5856
5857 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5858    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5859    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5860    or PARM_DECL.
5861
5862    Consider the example:
5863      template <class T> class A;
5864      template<template <class U> class TT> class B;
5865
5866    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5867    the parameters to A, and OUTER_ARGS contains A.  */
5868
5869 static int
5870 coerce_template_template_parms (tree parm_parms,
5871                                 tree arg_parms,
5872                                 tsubst_flags_t complain,
5873                                 tree in_decl,
5874                                 tree outer_args)
5875 {
5876   int nparms, nargs, i;
5877   tree parm, arg;
5878   int variadic_p = 0;
5879
5880   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5881   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5882
5883   nparms = TREE_VEC_LENGTH (parm_parms);
5884   nargs = TREE_VEC_LENGTH (arg_parms);
5885
5886   /* Determine whether we have a parameter pack at the end of the
5887      template template parameter's template parameter list.  */
5888   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5889     {
5890       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5891       
5892       if (parm == error_mark_node)
5893         return 0;
5894
5895       switch (TREE_CODE (parm))
5896         {
5897         case TEMPLATE_DECL:
5898         case TYPE_DECL:
5899           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5900             variadic_p = 1;
5901           break;
5902           
5903         case PARM_DECL:
5904           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5905             variadic_p = 1;
5906           break;
5907           
5908         default:
5909           gcc_unreachable ();
5910         }
5911     }
5912  
5913   if (nargs != nparms
5914       && !(variadic_p && nargs >= nparms - 1))
5915     return 0;
5916
5917   /* Check all of the template parameters except the parameter pack at
5918      the end (if any).  */
5919   for (i = 0; i < nparms - variadic_p; ++i)
5920     {
5921       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5922           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5923         continue;
5924
5925       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5926       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5927
5928       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5929                                           outer_args))
5930         return 0;
5931
5932     }
5933
5934   if (variadic_p)
5935     {
5936       /* Check each of the template parameters in the template
5937          argument against the template parameter pack at the end of
5938          the template template parameter.  */
5939       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5940         return 0;
5941
5942       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5943
5944       for (; i < nargs; ++i)
5945         {
5946           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5947             continue;
5948  
5949           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5950  
5951           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5952                                               outer_args))
5953             return 0;
5954         }
5955     }
5956
5957   return 1;
5958 }
5959
5960 /* Verifies that the deduced template arguments (in TARGS) for the
5961    template template parameters (in TPARMS) represent valid bindings,
5962    by comparing the template parameter list of each template argument
5963    to the template parameter list of its corresponding template
5964    template parameter, in accordance with DR150. This
5965    routine can only be called after all template arguments have been
5966    deduced. It will return TRUE if all of the template template
5967    parameter bindings are okay, FALSE otherwise.  */
5968 bool 
5969 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5970 {
5971   int i, ntparms = TREE_VEC_LENGTH (tparms);
5972   bool ret = true;
5973
5974   /* We're dealing with template parms in this process.  */
5975   ++processing_template_decl;
5976
5977   targs = INNERMOST_TEMPLATE_ARGS (targs);
5978
5979   for (i = 0; i < ntparms; ++i)
5980     {
5981       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5982       tree targ = TREE_VEC_ELT (targs, i);
5983
5984       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5985         {
5986           tree packed_args = NULL_TREE;
5987           int idx, len = 1;
5988
5989           if (ARGUMENT_PACK_P (targ))
5990             {
5991               /* Look inside the argument pack.  */
5992               packed_args = ARGUMENT_PACK_ARGS (targ);
5993               len = TREE_VEC_LENGTH (packed_args);
5994             }
5995
5996           for (idx = 0; idx < len; ++idx)
5997             {
5998               tree targ_parms = NULL_TREE;
5999
6000               if (packed_args)
6001                 /* Extract the next argument from the argument
6002                    pack.  */
6003                 targ = TREE_VEC_ELT (packed_args, idx);
6004
6005               if (PACK_EXPANSION_P (targ))
6006                 /* Look at the pattern of the pack expansion.  */
6007                 targ = PACK_EXPANSION_PATTERN (targ);
6008
6009               /* Extract the template parameters from the template
6010                  argument.  */
6011               if (TREE_CODE (targ) == TEMPLATE_DECL)
6012                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6013               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6014                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6015
6016               /* Verify that we can coerce the template template
6017                  parameters from the template argument to the template
6018                  parameter.  This requires an exact match.  */
6019               if (targ_parms
6020                   && !coerce_template_template_parms
6021                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6022                         targ_parms,
6023                         tf_none,
6024                         tparm,
6025                         targs))
6026                 {
6027                   ret = false;
6028                   goto out;
6029                 }
6030             }
6031         }
6032     }
6033
6034  out:
6035
6036   --processing_template_decl;
6037   return ret;
6038 }
6039
6040 /* Since type attributes aren't mangled, we need to strip them from
6041    template type arguments.  */
6042
6043 static tree
6044 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6045 {
6046   tree mv;
6047   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6048     return arg;
6049   mv = TYPE_MAIN_VARIANT (arg);
6050   arg = strip_typedefs (arg);
6051   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6052       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6053     {
6054       if (complain & tf_warning)
6055         warning (0, "ignoring attributes on template argument %qT", arg);
6056       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6057       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6058     }
6059   return arg;
6060 }
6061
6062 /* Convert the indicated template ARG as necessary to match the
6063    indicated template PARM.  Returns the converted ARG, or
6064    error_mark_node if the conversion was unsuccessful.  Error and
6065    warning messages are issued under control of COMPLAIN.  This
6066    conversion is for the Ith parameter in the parameter list.  ARGS is
6067    the full set of template arguments deduced so far.  */
6068
6069 static tree
6070 convert_template_argument (tree parm,
6071                            tree arg,
6072                            tree args,
6073                            tsubst_flags_t complain,
6074                            int i,
6075                            tree in_decl)
6076 {
6077   tree orig_arg;
6078   tree val;
6079   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6080
6081   if (TREE_CODE (arg) == TREE_LIST
6082       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6083     {
6084       /* The template argument was the name of some
6085          member function.  That's usually
6086          invalid, but static members are OK.  In any
6087          case, grab the underlying fields/functions
6088          and issue an error later if required.  */
6089       orig_arg = TREE_VALUE (arg);
6090       TREE_TYPE (arg) = unknown_type_node;
6091     }
6092
6093   orig_arg = arg;
6094
6095   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6096   requires_type = (TREE_CODE (parm) == TYPE_DECL
6097                    || requires_tmpl_type);
6098
6099   /* When determining whether an argument pack expansion is a template,
6100      look at the pattern.  */
6101   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6102     arg = PACK_EXPANSION_PATTERN (arg);
6103
6104   /* Deal with an injected-class-name used as a template template arg.  */
6105   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6106     {
6107       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6108       if (TREE_CODE (t) == TEMPLATE_DECL)
6109         {
6110           if (cxx_dialect >= cxx0x)
6111             /* OK under DR 1004.  */;
6112           else if (complain & tf_warning_or_error)
6113             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6114                      " used as template template argument", TYPE_NAME (arg));
6115           else if (flag_pedantic_errors)
6116             t = arg;
6117
6118           arg = t;
6119         }
6120     }
6121
6122   is_tmpl_type = 
6123     ((TREE_CODE (arg) == TEMPLATE_DECL
6124       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6125      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
6126      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6127      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6128
6129   if (is_tmpl_type
6130       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6131           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6132     arg = TYPE_STUB_DECL (arg);
6133
6134   is_type = TYPE_P (arg) || is_tmpl_type;
6135
6136   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6137       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6138     {
6139       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
6140         {
6141           if (complain & tf_error)
6142             error ("invalid use of destructor %qE as a type", orig_arg);
6143           return error_mark_node;
6144         }
6145
6146       permerror (input_location,
6147                  "to refer to a type member of a template parameter, "
6148                  "use %<typename %E%>", orig_arg);
6149
6150       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6151                                      TREE_OPERAND (arg, 1),
6152                                      typename_type,
6153                                      complain & tf_error);
6154       arg = orig_arg;
6155       is_type = 1;
6156     }
6157   if (is_type != requires_type)
6158     {
6159       if (in_decl)
6160         {
6161           if (complain & tf_error)
6162             {
6163               error ("type/value mismatch at argument %d in template "
6164                      "parameter list for %qD",
6165                      i + 1, in_decl);
6166               if (is_type)
6167                 error ("  expected a constant of type %qT, got %qT",
6168                        TREE_TYPE (parm),
6169                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6170               else if (requires_tmpl_type)
6171                 error ("  expected a class template, got %qE", orig_arg);
6172               else
6173                 error ("  expected a type, got %qE", orig_arg);
6174             }
6175         }
6176       return error_mark_node;
6177     }
6178   if (is_tmpl_type ^ requires_tmpl_type)
6179     {
6180       if (in_decl && (complain & tf_error))
6181         {
6182           error ("type/value mismatch at argument %d in template "
6183                  "parameter list for %qD",
6184                  i + 1, in_decl);
6185           if (is_tmpl_type)
6186             error ("  expected a type, got %qT", DECL_NAME (arg));
6187           else
6188             error ("  expected a class template, got %qT", orig_arg);
6189         }
6190       return error_mark_node;
6191     }
6192
6193   if (is_type)
6194     {
6195       if (requires_tmpl_type)
6196         {
6197           if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6198             val = orig_arg;
6199           else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6200             /* The number of argument required is not known yet.
6201                Just accept it for now.  */
6202             val = TREE_TYPE (arg);
6203           else
6204             {
6205               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6206               tree argparm;
6207
6208               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6209
6210               if (coerce_template_template_parms (parmparm, argparm,
6211                                                   complain, in_decl,
6212                                                   args))
6213                 {
6214                   val = arg;
6215
6216                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6217                      TEMPLATE_DECL.  */
6218                   if (val != error_mark_node)
6219                     {
6220                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6221                         val = TREE_TYPE (val);
6222                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6223                         val = make_pack_expansion (val);
6224                     }
6225                 }
6226               else
6227                 {
6228                   if (in_decl && (complain & tf_error))
6229                     {
6230                       error ("type/value mismatch at argument %d in "
6231                              "template parameter list for %qD",
6232                              i + 1, in_decl);
6233                       error ("  expected a template of type %qD, got %qT",
6234                              parm, orig_arg);
6235                     }
6236
6237                   val = error_mark_node;
6238                 }
6239             }
6240         }
6241       else
6242         val = orig_arg;
6243       /* We only form one instance of each template specialization.
6244          Therefore, if we use a non-canonical variant (i.e., a
6245          typedef), any future messages referring to the type will use
6246          the typedef, which is confusing if those future uses do not
6247          themselves also use the typedef.  */
6248       if (TYPE_P (val))
6249         val = canonicalize_type_argument (val, complain);
6250     }
6251   else
6252     {
6253       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6254
6255       if (invalid_nontype_parm_type_p (t, complain))
6256         return error_mark_node;
6257
6258       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6259         {
6260           if (same_type_p (t, TREE_TYPE (orig_arg)))
6261             val = orig_arg;
6262           else
6263             {
6264               /* Not sure if this is reachable, but it doesn't hurt
6265                  to be robust.  */
6266               error ("type mismatch in nontype parameter pack");
6267               val = error_mark_node;
6268             }
6269         }
6270       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6271         /* We used to call digest_init here.  However, digest_init
6272            will report errors, which we don't want when complain
6273            is zero.  More importantly, digest_init will try too
6274            hard to convert things: for example, `0' should not be
6275            converted to pointer type at this point according to
6276            the standard.  Accepting this is not merely an
6277            extension, since deciding whether or not these
6278            conversions can occur is part of determining which
6279            function template to call, or whether a given explicit
6280            argument specification is valid.  */
6281         val = convert_nontype_argument (t, orig_arg, complain);
6282       else
6283         val = strip_typedefs_expr (orig_arg);
6284
6285       if (val == NULL_TREE)
6286         val = error_mark_node;
6287       else if (val == error_mark_node && (complain & tf_error))
6288         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6289
6290       if (TREE_CODE (val) == SCOPE_REF)
6291         {
6292           /* Strip typedefs from the SCOPE_REF.  */
6293           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6294           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6295                                                    complain);
6296           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6297                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6298         }
6299     }
6300
6301   return val;
6302 }
6303
6304 /* Coerces the remaining template arguments in INNER_ARGS (from
6305    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6306    Returns the coerced argument pack. PARM_IDX is the position of this
6307    parameter in the template parameter list. ARGS is the original
6308    template argument list.  */
6309 static tree
6310 coerce_template_parameter_pack (tree parms,
6311                                 int parm_idx,
6312                                 tree args,
6313                                 tree inner_args,
6314                                 int arg_idx,
6315                                 tree new_args,
6316                                 int* lost,
6317                                 tree in_decl,
6318                                 tsubst_flags_t complain)
6319 {
6320   tree parm = TREE_VEC_ELT (parms, parm_idx);
6321   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6322   tree packed_args;
6323   tree argument_pack;
6324   tree packed_types = NULL_TREE;
6325
6326   if (arg_idx > nargs)
6327     arg_idx = nargs;
6328
6329   packed_args = make_tree_vec (nargs - arg_idx);
6330
6331   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6332       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6333     {
6334       /* When the template parameter is a non-type template
6335          parameter pack whose type uses parameter packs, we need
6336          to look at each of the template arguments
6337          separately. Build a vector of the types for these
6338          non-type template parameters in PACKED_TYPES.  */
6339       tree expansion 
6340         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6341       packed_types = tsubst_pack_expansion (expansion, args,
6342                                             complain, in_decl);
6343
6344       if (packed_types == error_mark_node)
6345         return error_mark_node;
6346
6347       /* Check that we have the right number of arguments.  */
6348       if (arg_idx < nargs
6349           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6350           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6351         {
6352           int needed_parms 
6353             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6354           error ("wrong number of template arguments (%d, should be %d)",
6355                  nargs, needed_parms);
6356           return error_mark_node;
6357         }
6358
6359       /* If we aren't able to check the actual arguments now
6360          (because they haven't been expanded yet), we can at least
6361          verify that all of the types used for the non-type
6362          template parameter pack are, in fact, valid for non-type
6363          template parameters.  */
6364       if (arg_idx < nargs 
6365           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6366         {
6367           int j, len = TREE_VEC_LENGTH (packed_types);
6368           for (j = 0; j < len; ++j)
6369             {
6370               tree t = TREE_VEC_ELT (packed_types, j);
6371               if (invalid_nontype_parm_type_p (t, complain))
6372                 return error_mark_node;
6373             }
6374         }
6375     }
6376
6377   /* Convert the remaining arguments, which will be a part of the
6378      parameter pack "parm".  */
6379   for (; arg_idx < nargs; ++arg_idx)
6380     {
6381       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6382       tree actual_parm = TREE_VALUE (parm);
6383
6384       if (packed_types && !PACK_EXPANSION_P (arg))
6385         {
6386           /* When we have a vector of types (corresponding to the
6387              non-type template parameter pack that uses parameter
6388              packs in its type, as mention above), and the
6389              argument is not an expansion (which expands to a
6390              currently unknown number of arguments), clone the
6391              parm and give it the next type in PACKED_TYPES.  */
6392           actual_parm = copy_node (actual_parm);
6393           TREE_TYPE (actual_parm) = 
6394             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6395         }
6396
6397       if (arg != error_mark_node)
6398         arg = convert_template_argument (actual_parm, 
6399                                          arg, new_args, complain, parm_idx,
6400                                          in_decl);
6401       if (arg == error_mark_node)
6402         (*lost)++;
6403       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6404     }
6405
6406   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6407       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6408     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6409   else
6410     {
6411       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6412       TREE_TYPE (argument_pack) 
6413         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6414       TREE_CONSTANT (argument_pack) = 1;
6415     }
6416
6417   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6418 #ifdef ENABLE_CHECKING
6419   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6420                                        TREE_VEC_LENGTH (packed_args));
6421 #endif
6422   return argument_pack;
6423 }
6424
6425 /* Returns true if the template argument vector ARGS contains
6426    any pack expansions, false otherwise.  */
6427
6428 static bool
6429 any_pack_expanson_args_p (tree args)
6430 {
6431   int i;
6432   if (args)
6433     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
6434       if (PACK_EXPANSION_P (TREE_VEC_ELT (args, i)))
6435         return true;
6436   return false;
6437 }
6438
6439 /* Convert all template arguments to their appropriate types, and
6440    return a vector containing the innermost resulting template
6441    arguments.  If any error occurs, return error_mark_node. Error and
6442    warning messages are issued under control of COMPLAIN.
6443
6444    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6445    for arguments not specified in ARGS.  Otherwise, if
6446    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6447    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6448    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6449    ARGS.  */
6450
6451 static tree
6452 coerce_template_parms (tree parms,
6453                        tree args,
6454                        tree in_decl,
6455                        tsubst_flags_t complain,
6456                        bool require_all_args,
6457                        bool use_default_args)
6458 {
6459   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6460   tree inner_args;
6461   tree new_args;
6462   tree new_inner_args;
6463   int saved_unevaluated_operand;
6464   int saved_inhibit_evaluation_warnings;
6465
6466   /* When used as a boolean value, indicates whether this is a
6467      variadic template parameter list. Since it's an int, we can also
6468      subtract it from nparms to get the number of non-variadic
6469      parameters.  */
6470   int variadic_p = 0;
6471   int post_variadic_parms = 0;
6472
6473   if (args == error_mark_node)
6474     return error_mark_node;
6475
6476   nparms = TREE_VEC_LENGTH (parms);
6477
6478   /* Determine if there are any parameter packs.  */
6479   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6480     {
6481       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6482       if (variadic_p)
6483         ++post_variadic_parms;
6484       if (template_parameter_pack_p (tparm))
6485         ++variadic_p;
6486     }
6487
6488   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6489   /* If there are no parameters that follow a parameter pack, we need to
6490      expand any argument packs so that we can deduce a parameter pack from
6491      some non-packed args followed by an argument pack, as in variadic85.C.
6492      If there are such parameters, we need to leave argument packs intact
6493      so the arguments are assigned properly.  This can happen when dealing
6494      with a nested class inside a partial specialization of a class
6495      template, as in variadic92.C, or when deducing a template parameter pack
6496      from a sub-declarator, as in variadic114.C.  */
6497   if (!post_variadic_parms)
6498     inner_args = expand_template_argument_pack (inner_args);
6499
6500   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6501   if ((nargs > nparms && !variadic_p)
6502       || (nargs < nparms - variadic_p
6503           && require_all_args
6504           && !any_pack_expanson_args_p (inner_args)
6505           && (!use_default_args
6506               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6507                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6508     {
6509       if (complain & tf_error)
6510         {
6511           if (variadic_p)
6512             {
6513               nparms -= variadic_p;
6514               error ("wrong number of template arguments "
6515                      "(%d, should be %d or more)", nargs, nparms);
6516             }
6517           else
6518              error ("wrong number of template arguments "
6519                     "(%d, should be %d)", nargs, nparms);
6520
6521           if (in_decl)
6522             error ("provided for %q+D", in_decl);
6523         }
6524
6525       return error_mark_node;
6526     }
6527
6528   /* We need to evaluate the template arguments, even though this
6529      template-id may be nested within a "sizeof".  */
6530   saved_unevaluated_operand = cp_unevaluated_operand;
6531   cp_unevaluated_operand = 0;
6532   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6533   c_inhibit_evaluation_warnings = 0;
6534   new_inner_args = make_tree_vec (nparms);
6535   new_args = add_outermost_template_args (args, new_inner_args);
6536   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6537     {
6538       tree arg;
6539       tree parm;
6540
6541       /* Get the Ith template parameter.  */
6542       parm = TREE_VEC_ELT (parms, parm_idx);
6543  
6544       if (parm == error_mark_node)
6545       {
6546         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6547         continue;
6548       }
6549
6550       /* Calculate the next argument.  */
6551       if (arg_idx < nargs)
6552         arg = TREE_VEC_ELT (inner_args, arg_idx);
6553       else
6554         arg = NULL_TREE;
6555
6556       if (template_parameter_pack_p (TREE_VALUE (parm))
6557           && !(arg && ARGUMENT_PACK_P (arg)))
6558         {
6559           /* All remaining arguments will be placed in the
6560              template parameter pack PARM.  */
6561           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6562                                                 inner_args, arg_idx,
6563                                                 new_args, &lost,
6564                                                 in_decl, complain);
6565
6566           /* Store this argument.  */
6567           if (arg == error_mark_node)
6568             lost++;
6569           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6570
6571           /* We are done with all of the arguments.  */
6572           arg_idx = nargs;
6573           
6574           continue;
6575         }
6576       else if (arg)
6577         {
6578           if (PACK_EXPANSION_P (arg))
6579             {
6580               /* We don't know how many args we have yet, just
6581                  use the unconverted ones for now.  */
6582               new_inner_args = inner_args;
6583               break;
6584             }
6585         }
6586       else if (require_all_args)
6587         {
6588           /* There must be a default arg in this case.  */
6589           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6590                                      complain, in_decl);
6591           /* The position of the first default template argument,
6592              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6593              Record that.  */
6594           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6595             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6596         }
6597       else
6598         break;
6599
6600       if (arg == error_mark_node)
6601         {
6602           if (complain & tf_error)
6603             error ("template argument %d is invalid", arg_idx + 1);
6604         }
6605       else if (!arg)
6606         /* This only occurs if there was an error in the template
6607            parameter list itself (which we would already have
6608            reported) that we are trying to recover from, e.g., a class
6609            template with a parameter list such as
6610            template<typename..., typename>.  */
6611         ++lost;
6612       else
6613         arg = convert_template_argument (TREE_VALUE (parm),
6614                                          arg, new_args, complain, 
6615                                          parm_idx, in_decl);
6616
6617       if (arg == error_mark_node)
6618         lost++;
6619       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6620     }
6621   cp_unevaluated_operand = saved_unevaluated_operand;
6622   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6623
6624   if (lost)
6625     return error_mark_node;
6626
6627 #ifdef ENABLE_CHECKING
6628   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6629     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6630                                          TREE_VEC_LENGTH (new_inner_args));
6631 #endif
6632
6633   return new_inner_args;
6634 }
6635
6636 /* Returns 1 if template args OT and NT are equivalent.  */
6637
6638 static int
6639 template_args_equal (tree ot, tree nt)
6640 {
6641   if (nt == ot)
6642     return 1;
6643   if (nt == NULL_TREE || ot == NULL_TREE)
6644     return false;
6645
6646   if (TREE_CODE (nt) == TREE_VEC)
6647     /* For member templates */
6648     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6649   else if (PACK_EXPANSION_P (ot))
6650     return (PACK_EXPANSION_P (nt)
6651             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6652                                     PACK_EXPANSION_PATTERN (nt))
6653             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
6654                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
6655   else if (ARGUMENT_PACK_P (ot))
6656     {
6657       int i, len;
6658       tree opack, npack;
6659
6660       if (!ARGUMENT_PACK_P (nt))
6661         return 0;
6662
6663       opack = ARGUMENT_PACK_ARGS (ot);
6664       npack = ARGUMENT_PACK_ARGS (nt);
6665       len = TREE_VEC_LENGTH (opack);
6666       if (TREE_VEC_LENGTH (npack) != len)
6667         return 0;
6668       for (i = 0; i < len; ++i)
6669         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6670                                   TREE_VEC_ELT (npack, i)))
6671           return 0;
6672       return 1;
6673     }
6674   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6675     {
6676       /* We get here probably because we are in the middle of substituting
6677          into the pattern of a pack expansion. In that case the
6678          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6679          interested in. So we want to use the initial pack argument for
6680          the comparison.  */
6681       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6682       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6683         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6684       return template_args_equal (ot, nt);
6685     }
6686   else if (TYPE_P (nt))
6687     return TYPE_P (ot) && same_type_p (ot, nt);
6688   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6689     return 0;
6690   else
6691     return cp_tree_equal (ot, nt);
6692 }
6693
6694 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6695    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6696    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6697
6698 static int
6699 comp_template_args_with_info (tree oldargs, tree newargs,
6700                               tree *oldarg_ptr, tree *newarg_ptr)
6701 {
6702   int i;
6703
6704   if (oldargs == newargs)
6705     return 1;
6706
6707   if (!oldargs || !newargs)
6708     return 0;
6709
6710   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6711     return 0;
6712
6713   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6714     {
6715       tree nt = TREE_VEC_ELT (newargs, i);
6716       tree ot = TREE_VEC_ELT (oldargs, i);
6717
6718       if (! template_args_equal (ot, nt))
6719         {
6720           if (oldarg_ptr != NULL)
6721             *oldarg_ptr = ot;
6722           if (newarg_ptr != NULL)
6723             *newarg_ptr = nt;
6724           return 0;
6725         }
6726     }
6727   return 1;
6728 }
6729
6730 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6731    of template arguments.  Returns 0 otherwise.  */
6732
6733 int
6734 comp_template_args (tree oldargs, tree newargs)
6735 {
6736   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6737 }
6738
6739 static void
6740 add_pending_template (tree d)
6741 {
6742   tree ti = (TYPE_P (d)
6743              ? CLASSTYPE_TEMPLATE_INFO (d)
6744              : DECL_TEMPLATE_INFO (d));
6745   struct pending_template *pt;
6746   int level;
6747
6748   if (TI_PENDING_TEMPLATE_FLAG (ti))
6749     return;
6750
6751   /* We are called both from instantiate_decl, where we've already had a
6752      tinst_level pushed, and instantiate_template, where we haven't.
6753      Compensate.  */
6754   level = !current_tinst_level || current_tinst_level->decl != d;
6755
6756   if (level)
6757     push_tinst_level (d);
6758
6759   pt = ggc_alloc_pending_template ();
6760   pt->next = NULL;
6761   pt->tinst = current_tinst_level;
6762   if (last_pending_template)
6763     last_pending_template->next = pt;
6764   else
6765     pending_templates = pt;
6766
6767   last_pending_template = pt;
6768
6769   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6770
6771   if (level)
6772     pop_tinst_level ();
6773 }
6774
6775
6776 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6777    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6778    documentation for TEMPLATE_ID_EXPR.  */
6779
6780 tree
6781 lookup_template_function (tree fns, tree arglist)
6782 {
6783   tree type;
6784
6785   if (fns == error_mark_node || arglist == error_mark_node)
6786     return error_mark_node;
6787
6788   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6789
6790   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6791     {
6792       error ("%q#D is not a function template", fns);
6793       return error_mark_node;
6794     }
6795
6796   if (BASELINK_P (fns))
6797     {
6798       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6799                                          unknown_type_node,
6800                                          BASELINK_FUNCTIONS (fns),
6801                                          arglist);
6802       return fns;
6803     }
6804
6805   type = TREE_TYPE (fns);
6806   if (TREE_CODE (fns) == OVERLOAD || !type)
6807     type = unknown_type_node;
6808
6809   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6810 }
6811
6812 /* Within the scope of a template class S<T>, the name S gets bound
6813    (in build_self_reference) to a TYPE_DECL for the class, not a
6814    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6815    or one of its enclosing classes, and that type is a template,
6816    return the associated TEMPLATE_DECL.  Otherwise, the original
6817    DECL is returned.
6818
6819    Also handle the case when DECL is a TREE_LIST of ambiguous
6820    injected-class-names from different bases.  */
6821
6822 tree
6823 maybe_get_template_decl_from_type_decl (tree decl)
6824 {
6825   if (decl == NULL_TREE)
6826     return decl;
6827
6828   /* DR 176: A lookup that finds an injected-class-name (10.2
6829      [class.member.lookup]) can result in an ambiguity in certain cases
6830      (for example, if it is found in more than one base class). If all of
6831      the injected-class-names that are found refer to specializations of
6832      the same class template, and if the name is followed by a
6833      template-argument-list, the reference refers to the class template
6834      itself and not a specialization thereof, and is not ambiguous.  */
6835   if (TREE_CODE (decl) == TREE_LIST)
6836     {
6837       tree t, tmpl = NULL_TREE;
6838       for (t = decl; t; t = TREE_CHAIN (t))
6839         {
6840           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6841           if (!tmpl)
6842             tmpl = elt;
6843           else if (tmpl != elt)
6844             break;
6845         }
6846       if (tmpl && t == NULL_TREE)
6847         return tmpl;
6848       else
6849         return decl;
6850     }
6851
6852   return (decl != NULL_TREE
6853           && DECL_SELF_REFERENCE_P (decl)
6854           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6855     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6856 }
6857
6858 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6859    parameters, find the desired type.
6860
6861    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6862
6863    IN_DECL, if non-NULL, is the template declaration we are trying to
6864    instantiate.
6865
6866    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6867    the class we are looking up.
6868
6869    Issue error and warning messages under control of COMPLAIN.
6870
6871    If the template class is really a local class in a template
6872    function, then the FUNCTION_CONTEXT is the function in which it is
6873    being instantiated.
6874
6875    ??? Note that this function is currently called *twice* for each
6876    template-id: the first time from the parser, while creating the
6877    incomplete type (finish_template_type), and the second type during the
6878    real instantiation (instantiate_template_class). This is surely something
6879    that we want to avoid. It also causes some problems with argument
6880    coercion (see convert_nontype_argument for more information on this).  */
6881
6882 static tree
6883 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6884                          int entering_scope, tsubst_flags_t complain)
6885 {
6886   tree templ = NULL_TREE, parmlist;
6887   tree t;
6888   void **slot;
6889   spec_entry *entry;
6890   spec_entry elt;
6891   hashval_t hash;
6892
6893   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6894     {
6895       tree value = innermost_non_namespace_value (d1);
6896       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6897         templ = value;
6898       else
6899         {
6900           if (context)
6901             push_decl_namespace (context);
6902           templ = lookup_name (d1);
6903           templ = maybe_get_template_decl_from_type_decl (templ);
6904           if (context)
6905             pop_decl_namespace ();
6906         }
6907       if (templ)
6908         context = DECL_CONTEXT (templ);
6909     }
6910   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6911     {
6912       tree type = TREE_TYPE (d1);
6913
6914       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6915          an implicit typename for the second A.  Deal with it.  */
6916       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6917         type = TREE_TYPE (type);
6918
6919       if (CLASSTYPE_TEMPLATE_INFO (type))
6920         {
6921           templ = CLASSTYPE_TI_TEMPLATE (type);
6922           d1 = DECL_NAME (templ);
6923         }
6924     }
6925   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6926            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6927     {
6928       templ = TYPE_TI_TEMPLATE (d1);
6929       d1 = DECL_NAME (templ);
6930     }
6931   else if (TREE_CODE (d1) == TEMPLATE_DECL
6932            && DECL_TEMPLATE_RESULT (d1)
6933            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6934     {
6935       templ = d1;
6936       d1 = DECL_NAME (templ);
6937       context = DECL_CONTEXT (templ);
6938     }
6939
6940   /* Issue an error message if we didn't find a template.  */
6941   if (! templ)
6942     {
6943       if (complain & tf_error)
6944         error ("%qT is not a template", d1);
6945       return error_mark_node;
6946     }
6947
6948   if (TREE_CODE (templ) != TEMPLATE_DECL
6949          /* Make sure it's a user visible template, if it was named by
6950             the user.  */
6951       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6952           && !PRIMARY_TEMPLATE_P (templ)))
6953     {
6954       if (complain & tf_error)
6955         {
6956           error ("non-template type %qT used as a template", d1);
6957           if (in_decl)
6958             error ("for template declaration %q+D", in_decl);
6959         }
6960       return error_mark_node;
6961     }
6962
6963   complain &= ~tf_user;
6964
6965   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6966     {
6967       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6968          template arguments */
6969
6970       tree parm;
6971       tree arglist2;
6972       tree outer;
6973
6974       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6975
6976       /* Consider an example where a template template parameter declared as
6977
6978            template <class T, class U = std::allocator<T> > class TT
6979
6980          The template parameter level of T and U are one level larger than
6981          of TT.  To proper process the default argument of U, say when an
6982          instantiation `TT<int>' is seen, we need to build the full
6983          arguments containing {int} as the innermost level.  Outer levels,
6984          available when not appearing as default template argument, can be
6985          obtained from the arguments of the enclosing template.
6986
6987          Suppose that TT is later substituted with std::vector.  The above
6988          instantiation is `TT<int, std::allocator<T> >' with TT at
6989          level 1, and T at level 2, while the template arguments at level 1
6990          becomes {std::vector} and the inner level 2 is {int}.  */
6991
6992       outer = DECL_CONTEXT (templ);
6993       if (outer)
6994         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6995       else if (current_template_parms)
6996         /* This is an argument of the current template, so we haven't set
6997            DECL_CONTEXT yet.  */
6998         outer = current_template_args ();
6999
7000       if (outer)
7001         arglist = add_to_template_args (outer, arglist);
7002
7003       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7004                                         complain,
7005                                         /*require_all_args=*/true,
7006                                         /*use_default_args=*/true);
7007       if (arglist2 == error_mark_node
7008           || (!uses_template_parms (arglist2)
7009               && check_instantiated_args (templ, arglist2, complain)))
7010         return error_mark_node;
7011
7012       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7013       return parm;
7014     }
7015   else
7016     {
7017       tree template_type = TREE_TYPE (templ);
7018       tree gen_tmpl;
7019       tree type_decl;
7020       tree found = NULL_TREE;
7021       int arg_depth;
7022       int parm_depth;
7023       int is_dependent_type;
7024       int use_partial_inst_tmpl = false;
7025
7026       if (template_type == error_mark_node)
7027         /* An error occured while building the template TEMPL, and a
7028            diagnostic has most certainly been emitted for that
7029            already.  Let's propagate that error.  */
7030         return error_mark_node;
7031
7032       gen_tmpl = most_general_template (templ);
7033       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7034       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7035       arg_depth = TMPL_ARGS_DEPTH (arglist);
7036
7037       if (arg_depth == 1 && parm_depth > 1)
7038         {
7039           /* We've been given an incomplete set of template arguments.
7040              For example, given:
7041
7042                template <class T> struct S1 {
7043                  template <class U> struct S2 {};
7044                  template <class U> struct S2<U*> {};
7045                 };
7046
7047              we will be called with an ARGLIST of `U*', but the
7048              TEMPLATE will be `template <class T> template
7049              <class U> struct S1<T>::S2'.  We must fill in the missing
7050              arguments.  */
7051           arglist
7052             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7053                                            arglist);
7054           arg_depth = TMPL_ARGS_DEPTH (arglist);
7055         }
7056
7057       /* Now we should have enough arguments.  */
7058       gcc_assert (parm_depth == arg_depth);
7059
7060       /* From here on, we're only interested in the most general
7061          template.  */
7062
7063       /* Calculate the BOUND_ARGS.  These will be the args that are
7064          actually tsubst'd into the definition to create the
7065          instantiation.  */
7066       if (parm_depth > 1)
7067         {
7068           /* We have multiple levels of arguments to coerce, at once.  */
7069           int i;
7070           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7071
7072           tree bound_args = make_tree_vec (parm_depth);
7073
7074           for (i = saved_depth,
7075                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7076                i > 0 && t != NULL_TREE;
7077                --i, t = TREE_CHAIN (t))
7078             {
7079               tree a;
7080               if (i == saved_depth)
7081                 a = coerce_template_parms (TREE_VALUE (t),
7082                                            arglist, gen_tmpl,
7083                                            complain,
7084                                            /*require_all_args=*/true,
7085                                            /*use_default_args=*/true);
7086               else
7087                 /* Outer levels should have already been coerced.  */
7088                 a = TMPL_ARGS_LEVEL (arglist, i);
7089
7090               /* Don't process further if one of the levels fails.  */
7091               if (a == error_mark_node)
7092                 {
7093                   /* Restore the ARGLIST to its full size.  */
7094                   TREE_VEC_LENGTH (arglist) = saved_depth;
7095                   return error_mark_node;
7096                 }
7097
7098               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7099
7100               /* We temporarily reduce the length of the ARGLIST so
7101                  that coerce_template_parms will see only the arguments
7102                  corresponding to the template parameters it is
7103                  examining.  */
7104               TREE_VEC_LENGTH (arglist)--;
7105             }
7106
7107           /* Restore the ARGLIST to its full size.  */
7108           TREE_VEC_LENGTH (arglist) = saved_depth;
7109
7110           arglist = bound_args;
7111         }
7112       else
7113         arglist
7114           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7115                                    INNERMOST_TEMPLATE_ARGS (arglist),
7116                                    gen_tmpl,
7117                                    complain,
7118                                    /*require_all_args=*/true,
7119                                    /*use_default_args=*/true);
7120
7121       if (arglist == error_mark_node)
7122         /* We were unable to bind the arguments.  */
7123         return error_mark_node;
7124
7125       /* In the scope of a template class, explicit references to the
7126          template class refer to the type of the template, not any
7127          instantiation of it.  For example, in:
7128
7129            template <class T> class C { void f(C<T>); }
7130
7131          the `C<T>' is just the same as `C'.  Outside of the
7132          class, however, such a reference is an instantiation.  */
7133       if ((entering_scope
7134            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7135            || currently_open_class (template_type))
7136           /* comp_template_args is expensive, check it last.  */
7137           && comp_template_args (TYPE_TI_ARGS (template_type),
7138                                  arglist))
7139         return template_type;
7140
7141       /* If we already have this specialization, return it.  */
7142       elt.tmpl = gen_tmpl;
7143       elt.args = arglist;
7144       hash = hash_specialization (&elt);
7145       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7146                                                   &elt, hash);
7147
7148       if (entry)
7149         return entry->spec;
7150
7151       is_dependent_type = uses_template_parms (arglist);
7152
7153       /* If the deduced arguments are invalid, then the binding
7154          failed.  */
7155       if (!is_dependent_type
7156           && check_instantiated_args (gen_tmpl,
7157                                       INNERMOST_TEMPLATE_ARGS (arglist),
7158                                       complain))
7159         return error_mark_node;
7160
7161       if (!is_dependent_type
7162           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7163           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7164           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7165         {
7166           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7167                                       DECL_NAME (gen_tmpl),
7168                                       /*tag_scope=*/ts_global);
7169           return found;
7170         }
7171
7172       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7173                         complain, in_decl);
7174       if (context == error_mark_node)
7175         return error_mark_node;
7176
7177       if (!context)
7178         context = global_namespace;
7179
7180       /* Create the type.  */
7181       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7182         {
7183           if (!is_dependent_type)
7184             {
7185               set_current_access_from_decl (TYPE_NAME (template_type));
7186               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7187                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7188                                       arglist, complain, in_decl),
7189                               SCOPED_ENUM_P (template_type), NULL);
7190             }
7191           else
7192             {
7193               /* We don't want to call start_enum for this type, since
7194                  the values for the enumeration constants may involve
7195                  template parameters.  And, no one should be interested
7196                  in the enumeration constants for such a type.  */
7197               t = cxx_make_type (ENUMERAL_TYPE);
7198               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7199             }
7200           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7201           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7202             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7203         }
7204       else if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7205         {
7206           /* The user referred to a specialization of an alias
7207             template represented by GEN_TMPL.
7208
7209             [temp.alias]/2 says:
7210
7211                 When a template-id refers to the specialization of an
7212                 alias template, it is equivalent to the associated
7213                 type obtained by substitution of its
7214                 template-arguments for the template-parameters in the
7215                 type-id of the alias template.  */
7216
7217           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
7218           /* Note that the call above (by indirectly calling
7219              register_specialization in tsubst_decl) registers the
7220              TYPE_DECL representing the specialization of the alias
7221              template.  So next time someone substitutes ARGLIST for
7222              the template parms into the alias template (GEN_TMPL),
7223              she'll get that TYPE_DECL back.  */
7224
7225           if (t == error_mark_node)
7226             return t;
7227         }
7228       else if (CLASS_TYPE_P (template_type))
7229         {
7230           t = make_class_type (TREE_CODE (template_type));
7231           CLASSTYPE_DECLARED_CLASS (t)
7232             = CLASSTYPE_DECLARED_CLASS (template_type);
7233           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7234           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7235
7236           /* A local class.  Make sure the decl gets registered properly.  */
7237           if (context == current_function_decl)
7238             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_global);
7239
7240           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7241             /* This instantiation is another name for the primary
7242                template type. Set the TYPE_CANONICAL field
7243                appropriately. */
7244             TYPE_CANONICAL (t) = template_type;
7245           else if (any_template_arguments_need_structural_equality_p (arglist))
7246             /* Some of the template arguments require structural
7247                equality testing, so this template class requires
7248                structural equality testing. */
7249             SET_TYPE_STRUCTURAL_EQUALITY (t);
7250         }
7251       else
7252         gcc_unreachable ();
7253
7254       /* If we called start_enum or pushtag above, this information
7255          will already be set up.  */
7256       if (!TYPE_NAME (t))
7257         {
7258           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7259
7260           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7261           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7262           DECL_SOURCE_LOCATION (type_decl)
7263             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7264         }
7265       else
7266         type_decl = TYPE_NAME (t);
7267
7268       if (CLASS_TYPE_P (template_type))
7269         {
7270           TREE_PRIVATE (type_decl)
7271             = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7272           TREE_PROTECTED (type_decl)
7273             = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7274           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7275             {
7276               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7277               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7278             }
7279         }
7280
7281       /* Let's consider the explicit specialization of a member
7282          of a class template specialization that is implicitely instantiated,
7283          e.g.:
7284              template<class T>
7285              struct S
7286              {
7287                template<class U> struct M {}; //#0
7288              };
7289
7290              template<>
7291              template<>
7292              struct S<int>::M<char> //#1
7293              {
7294                int i;
7295              };
7296         [temp.expl.spec]/4 says this is valid.
7297
7298         In this case, when we write:
7299         S<int>::M<char> m;
7300
7301         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7302         the one of #0.
7303
7304         When we encounter #1, we want to store the partial instantiation
7305         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7306
7307         For all cases other than this "explicit specialization of member of a
7308         class template", we just want to store the most general template into
7309         the CLASSTYPE_TI_TEMPLATE of M.
7310
7311         This case of "explicit specialization of member of a class template"
7312         only happens when:
7313         1/ the enclosing class is an instantiation of, and therefore not
7314         the same as, the context of the most general template, and
7315         2/ we aren't looking at the partial instantiation itself, i.e.
7316         the innermost arguments are not the same as the innermost parms of
7317         the most general template.
7318
7319         So it's only when 1/ and 2/ happens that we want to use the partial
7320         instantiation of the member template in lieu of its most general
7321         template.  */
7322
7323       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7324           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7325           /* the enclosing class must be an instantiation...  */
7326           && CLASS_TYPE_P (context)
7327           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7328         {
7329           tree partial_inst_args;
7330           TREE_VEC_LENGTH (arglist)--;
7331           ++processing_template_decl;
7332           partial_inst_args =
7333             tsubst (INNERMOST_TEMPLATE_ARGS
7334                         (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7335                     arglist, complain, NULL_TREE);
7336           --processing_template_decl;
7337           TREE_VEC_LENGTH (arglist)++;
7338           use_partial_inst_tmpl =
7339             /*...and we must not be looking at the partial instantiation
7340              itself. */
7341             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7342                                  partial_inst_args);
7343         }
7344
7345       if (!use_partial_inst_tmpl)
7346         /* This case is easy; there are no member templates involved.  */
7347         found = gen_tmpl;
7348       else
7349         {
7350           /* This is a full instantiation of a member template.  Find
7351              the partial instantiation of which this is an instance.  */
7352
7353           /* Temporarily reduce by one the number of levels in the ARGLIST
7354              so as to avoid comparing the last set of arguments.  */
7355           TREE_VEC_LENGTH (arglist)--;
7356           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7357           TREE_VEC_LENGTH (arglist)++;
7358           /* FOUND is either a proper class type, or an alias
7359              template specialization.  In the later case, it's a
7360              TYPE_DECL, resulting from the substituting of arguments
7361              for parameters in the TYPE_DECL of the alias template
7362              done earlier.  So be careful while getting the template
7363              of FOUND.  */
7364           found = TREE_CODE (found) == TYPE_DECL
7365             ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
7366             : CLASSTYPE_TI_TEMPLATE (found);
7367         }
7368
7369       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7370
7371       elt.spec = t;
7372       slot = htab_find_slot_with_hash (type_specializations,
7373                                        &elt, hash, INSERT);
7374       entry = ggc_alloc_spec_entry ();
7375       *entry = elt;
7376       *slot = entry;
7377
7378       /* Note this use of the partial instantiation so we can check it
7379          later in maybe_process_partial_specialization.  */
7380       DECL_TEMPLATE_INSTANTIATIONS (templ)
7381         = tree_cons (arglist, t,
7382                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7383
7384       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7385         /* Now that the type has been registered on the instantiations
7386            list, we set up the enumerators.  Because the enumeration
7387            constants may involve the enumeration type itself, we make
7388            sure to register the type first, and then create the
7389            constants.  That way, doing tsubst_expr for the enumeration
7390            constants won't result in recursive calls here; we'll find
7391            the instantiation and exit above.  */
7392         tsubst_enum (template_type, t, arglist);
7393
7394       if (CLASS_TYPE_P (template_type) && is_dependent_type)
7395         /* If the type makes use of template parameters, the
7396            code that generates debugging information will crash.  */
7397         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7398
7399       /* Possibly limit visibility based on template args.  */
7400       TREE_PUBLIC (type_decl) = 1;
7401       determine_visibility (type_decl);
7402
7403       return t;
7404     }
7405 }
7406
7407 /* Wrapper for lookup_template_class_1.  */
7408
7409 tree
7410 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7411                        int entering_scope, tsubst_flags_t complain)
7412 {
7413   tree ret;
7414   timevar_push (TV_TEMPLATE_INST);
7415   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7416                                  entering_scope, complain);
7417   timevar_pop (TV_TEMPLATE_INST);
7418   return ret;
7419 }
7420 \f
7421 struct pair_fn_data
7422 {
7423   tree_fn_t fn;
7424   void *data;
7425   /* True when we should also visit template parameters that occur in
7426      non-deduced contexts.  */
7427   bool include_nondeduced_p;
7428   struct pointer_set_t *visited;
7429 };
7430
7431 /* Called from for_each_template_parm via walk_tree.  */
7432
7433 static tree
7434 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7435 {
7436   tree t = *tp;
7437   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7438   tree_fn_t fn = pfd->fn;
7439   void *data = pfd->data;
7440
7441   if (TYPE_P (t)
7442       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7443       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7444                                  pfd->include_nondeduced_p))
7445     return error_mark_node;
7446
7447   switch (TREE_CODE (t))
7448     {
7449     case RECORD_TYPE:
7450       if (TYPE_PTRMEMFUNC_P (t))
7451         break;
7452       /* Fall through.  */
7453
7454     case UNION_TYPE:
7455     case ENUMERAL_TYPE:
7456       if (!TYPE_TEMPLATE_INFO (t))
7457         *walk_subtrees = 0;
7458       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7459                                        fn, data, pfd->visited, 
7460                                        pfd->include_nondeduced_p))
7461         return error_mark_node;
7462       break;
7463
7464     case INTEGER_TYPE:
7465       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7466                                   fn, data, pfd->visited, 
7467                                   pfd->include_nondeduced_p)
7468           || for_each_template_parm (TYPE_MAX_VALUE (t),
7469                                      fn, data, pfd->visited,
7470                                      pfd->include_nondeduced_p))
7471         return error_mark_node;
7472       break;
7473
7474     case METHOD_TYPE:
7475       /* Since we're not going to walk subtrees, we have to do this
7476          explicitly here.  */
7477       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7478                                   pfd->visited, pfd->include_nondeduced_p))
7479         return error_mark_node;
7480       /* Fall through.  */
7481
7482     case FUNCTION_TYPE:
7483       /* Check the return type.  */
7484       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7485                                   pfd->include_nondeduced_p))
7486         return error_mark_node;
7487
7488       /* Check the parameter types.  Since default arguments are not
7489          instantiated until they are needed, the TYPE_ARG_TYPES may
7490          contain expressions that involve template parameters.  But,
7491          no-one should be looking at them yet.  And, once they're
7492          instantiated, they don't contain template parameters, so
7493          there's no point in looking at them then, either.  */
7494       {
7495         tree parm;
7496
7497         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7498           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7499                                       pfd->visited, pfd->include_nondeduced_p))
7500             return error_mark_node;
7501
7502         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7503            want walk_tree walking into them itself.  */
7504         *walk_subtrees = 0;
7505       }
7506       break;
7507
7508     case TYPEOF_TYPE:
7509     case UNDERLYING_TYPE:
7510       if (pfd->include_nondeduced_p
7511           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7512                                      pfd->visited, 
7513                                      pfd->include_nondeduced_p))
7514         return error_mark_node;
7515       break;
7516
7517     case FUNCTION_DECL:
7518     case VAR_DECL:
7519       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7520           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7521                                      pfd->visited, pfd->include_nondeduced_p))
7522         return error_mark_node;
7523       /* Fall through.  */
7524
7525     case PARM_DECL:
7526     case CONST_DECL:
7527       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7528           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7529                                      pfd->visited, pfd->include_nondeduced_p))
7530         return error_mark_node;
7531       if (DECL_CONTEXT (t)
7532           && pfd->include_nondeduced_p
7533           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7534                                      pfd->visited, pfd->include_nondeduced_p))
7535         return error_mark_node;
7536       break;
7537
7538     case BOUND_TEMPLATE_TEMPLATE_PARM:
7539       /* Record template parameters such as `T' inside `TT<T>'.  */
7540       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7541                                   pfd->include_nondeduced_p))
7542         return error_mark_node;
7543       /* Fall through.  */
7544
7545     case TEMPLATE_TEMPLATE_PARM:
7546     case TEMPLATE_TYPE_PARM:
7547     case TEMPLATE_PARM_INDEX:
7548       if (fn && (*fn)(t, data))
7549         return error_mark_node;
7550       else if (!fn)
7551         return error_mark_node;
7552       break;
7553
7554     case TEMPLATE_DECL:
7555       /* A template template parameter is encountered.  */
7556       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7557           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7558                                      pfd->include_nondeduced_p))
7559         return error_mark_node;
7560
7561       /* Already substituted template template parameter */
7562       *walk_subtrees = 0;
7563       break;
7564
7565     case TYPENAME_TYPE:
7566       if (!fn
7567           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7568                                      data, pfd->visited, 
7569                                      pfd->include_nondeduced_p))
7570         return error_mark_node;
7571       break;
7572
7573     case CONSTRUCTOR:
7574       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7575           && pfd->include_nondeduced_p
7576           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7577                                      (TREE_TYPE (t)), fn, data,
7578                                      pfd->visited, pfd->include_nondeduced_p))
7579         return error_mark_node;
7580       break;
7581
7582     case INDIRECT_REF:
7583     case COMPONENT_REF:
7584       /* If there's no type, then this thing must be some expression
7585          involving template parameters.  */
7586       if (!fn && !TREE_TYPE (t))
7587         return error_mark_node;
7588       break;
7589
7590     case MODOP_EXPR:
7591     case CAST_EXPR:
7592     case IMPLICIT_CONV_EXPR:
7593     case REINTERPRET_CAST_EXPR:
7594     case CONST_CAST_EXPR:
7595     case STATIC_CAST_EXPR:
7596     case DYNAMIC_CAST_EXPR:
7597     case ARROW_EXPR:
7598     case DOTSTAR_EXPR:
7599     case TYPEID_EXPR:
7600     case PSEUDO_DTOR_EXPR:
7601       if (!fn)
7602         return error_mark_node;
7603       break;
7604
7605     default:
7606       break;
7607     }
7608
7609   /* We didn't find any template parameters we liked.  */
7610   return NULL_TREE;
7611 }
7612
7613 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7614    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7615    call FN with the parameter and the DATA.
7616    If FN returns nonzero, the iteration is terminated, and
7617    for_each_template_parm returns 1.  Otherwise, the iteration
7618    continues.  If FN never returns a nonzero value, the value
7619    returned by for_each_template_parm is 0.  If FN is NULL, it is
7620    considered to be the function which always returns 1.
7621
7622    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7623    parameters that occur in non-deduced contexts.  When false, only
7624    visits those template parameters that can be deduced.  */
7625
7626 static int
7627 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7628                         struct pointer_set_t *visited,
7629                         bool include_nondeduced_p)
7630 {
7631   struct pair_fn_data pfd;
7632   int result;
7633
7634   /* Set up.  */
7635   pfd.fn = fn;
7636   pfd.data = data;
7637   pfd.include_nondeduced_p = include_nondeduced_p;
7638
7639   /* Walk the tree.  (Conceptually, we would like to walk without
7640      duplicates, but for_each_template_parm_r recursively calls
7641      for_each_template_parm, so we would need to reorganize a fair
7642      bit to use walk_tree_without_duplicates, so we keep our own
7643      visited list.)  */
7644   if (visited)
7645     pfd.visited = visited;
7646   else
7647     pfd.visited = pointer_set_create ();
7648   result = cp_walk_tree (&t,
7649                          for_each_template_parm_r,
7650                          &pfd,
7651                          pfd.visited) != NULL_TREE;
7652
7653   /* Clean up.  */
7654   if (!visited)
7655     {
7656       pointer_set_destroy (pfd.visited);
7657       pfd.visited = 0;
7658     }
7659
7660   return result;
7661 }
7662
7663 /* Returns true if T depends on any template parameter.  */
7664
7665 int
7666 uses_template_parms (tree t)
7667 {
7668   bool dependent_p;
7669   int saved_processing_template_decl;
7670
7671   saved_processing_template_decl = processing_template_decl;
7672   if (!saved_processing_template_decl)
7673     processing_template_decl = 1;
7674   if (TYPE_P (t))
7675     dependent_p = dependent_type_p (t);
7676   else if (TREE_CODE (t) == TREE_VEC)
7677     dependent_p = any_dependent_template_arguments_p (t);
7678   else if (TREE_CODE (t) == TREE_LIST)
7679     dependent_p = (uses_template_parms (TREE_VALUE (t))
7680                    || uses_template_parms (TREE_CHAIN (t)));
7681   else if (TREE_CODE (t) == TYPE_DECL)
7682     dependent_p = dependent_type_p (TREE_TYPE (t));
7683   else if (DECL_P (t)
7684            || EXPR_P (t)
7685            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7686            || TREE_CODE (t) == OVERLOAD
7687            || BASELINK_P (t)
7688            || TREE_CODE (t) == IDENTIFIER_NODE
7689            || TREE_CODE (t) == TRAIT_EXPR
7690            || TREE_CODE (t) == CONSTRUCTOR
7691            || CONSTANT_CLASS_P (t))
7692     dependent_p = (type_dependent_expression_p (t)
7693                    || value_dependent_expression_p (t));
7694   else
7695     {
7696       gcc_assert (t == error_mark_node);
7697       dependent_p = false;
7698     }
7699
7700   processing_template_decl = saved_processing_template_decl;
7701
7702   return dependent_p;
7703 }
7704
7705 /* Returns true if T depends on any template parameter with level LEVEL.  */
7706
7707 int
7708 uses_template_parms_level (tree t, int level)
7709 {
7710   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7711                                  /*include_nondeduced_p=*/true);
7712 }
7713
7714 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7715    ill-formed translation unit, i.e. a variable or function that isn't
7716    usable in a constant expression.  */
7717
7718 static inline bool
7719 neglectable_inst_p (tree d)
7720 {
7721   return (DECL_P (d)
7722           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7723                : decl_maybe_constant_var_p (d)));
7724 }
7725
7726 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7727    neglectable and instantiated from within an erroneous instantiation.  */
7728
7729 static bool
7730 limit_bad_template_recursion (tree decl)
7731 {
7732   struct tinst_level *lev = current_tinst_level;
7733   int errs = errorcount + sorrycount;
7734   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7735     return false;
7736
7737   for (; lev; lev = lev->next)
7738     if (neglectable_inst_p (lev->decl))
7739       break;
7740
7741   return (lev && errs > lev->errors);
7742 }
7743
7744 static int tinst_depth;
7745 extern int max_tinst_depth;
7746 #ifdef GATHER_STATISTICS
7747 int depth_reached;
7748 #endif
7749 static GTY(()) struct tinst_level *last_error_tinst_level;
7750
7751 /* We're starting to instantiate D; record the template instantiation context
7752    for diagnostics and to restore it later.  */
7753
7754 int
7755 push_tinst_level (tree d)
7756 {
7757   struct tinst_level *new_level;
7758
7759   if (tinst_depth >= max_tinst_depth)
7760     {
7761       last_error_tinst_level = current_tinst_level;
7762       if (TREE_CODE (d) == TREE_LIST)
7763         error ("template instantiation depth exceeds maximum of %d (use "
7764                "-ftemplate-depth= to increase the maximum) substituting %qS",
7765                max_tinst_depth, d);
7766       else
7767         error ("template instantiation depth exceeds maximum of %d (use "
7768                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7769                max_tinst_depth, d);
7770
7771       print_instantiation_context ();
7772
7773       return 0;
7774     }
7775
7776   /* If the current instantiation caused problems, don't let it instantiate
7777      anything else.  Do allow deduction substitution and decls usable in
7778      constant expressions.  */
7779   if (limit_bad_template_recursion (d))
7780     return 0;
7781
7782   new_level = ggc_alloc_tinst_level ();
7783   new_level->decl = d;
7784   new_level->locus = input_location;
7785   new_level->errors = errorcount+sorrycount;
7786   new_level->in_system_header_p = in_system_header;
7787   new_level->next = current_tinst_level;
7788   current_tinst_level = new_level;
7789
7790   ++tinst_depth;
7791 #ifdef GATHER_STATISTICS
7792   if (tinst_depth > depth_reached)
7793     depth_reached = tinst_depth;
7794 #endif
7795
7796   return 1;
7797 }
7798
7799 /* We're done instantiating this template; return to the instantiation
7800    context.  */
7801
7802 void
7803 pop_tinst_level (void)
7804 {
7805   /* Restore the filename and line number stashed away when we started
7806      this instantiation.  */
7807   input_location = current_tinst_level->locus;
7808   current_tinst_level = current_tinst_level->next;
7809   --tinst_depth;
7810 }
7811
7812 /* We're instantiating a deferred template; restore the template
7813    instantiation context in which the instantiation was requested, which
7814    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7815
7816 static tree
7817 reopen_tinst_level (struct tinst_level *level)
7818 {
7819   struct tinst_level *t;
7820
7821   tinst_depth = 0;
7822   for (t = level; t; t = t->next)
7823     ++tinst_depth;
7824
7825   current_tinst_level = level;
7826   pop_tinst_level ();
7827   if (current_tinst_level)
7828     current_tinst_level->errors = errorcount+sorrycount;
7829   return level->decl;
7830 }
7831
7832 /* Returns the TINST_LEVEL which gives the original instantiation
7833    context.  */
7834
7835 struct tinst_level *
7836 outermost_tinst_level (void)
7837 {
7838   struct tinst_level *level = current_tinst_level;
7839   if (level)
7840     while (level->next)
7841       level = level->next;
7842   return level;
7843 }
7844
7845 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7846
7847 bool
7848 parameter_of_template_p (tree parm, tree templ)
7849 {
7850   tree parms;
7851   int i;
7852
7853   if (!parm || !templ)
7854     return false;
7855
7856   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7857   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7858
7859   parms = DECL_TEMPLATE_PARMS (templ);
7860   parms = INNERMOST_TEMPLATE_PARMS (parms);
7861
7862   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7863     {
7864       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7865       if (p == error_mark_node)
7866         continue;
7867
7868       if (parm == p
7869           || (DECL_INITIAL (parm)
7870               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7871         return true;
7872     }
7873
7874   return false;
7875 }
7876
7877 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7878    vector of template arguments, as for tsubst.
7879
7880    Returns an appropriate tsubst'd friend declaration.  */
7881
7882 static tree
7883 tsubst_friend_function (tree decl, tree args)
7884 {
7885   tree new_friend;
7886
7887   if (TREE_CODE (decl) == FUNCTION_DECL
7888       && DECL_TEMPLATE_INSTANTIATION (decl)
7889       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7890     /* This was a friend declared with an explicit template
7891        argument list, e.g.:
7892
7893        friend void f<>(T);
7894
7895        to indicate that f was a template instantiation, not a new
7896        function declaration.  Now, we have to figure out what
7897        instantiation of what template.  */
7898     {
7899       tree template_id, arglist, fns;
7900       tree new_args;
7901       tree tmpl;
7902       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7903
7904       /* Friend functions are looked up in the containing namespace scope.
7905          We must enter that scope, to avoid finding member functions of the
7906          current class with same name.  */
7907       push_nested_namespace (ns);
7908       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7909                          tf_warning_or_error, NULL_TREE,
7910                          /*integral_constant_expression_p=*/false);
7911       pop_nested_namespace (ns);
7912       arglist = tsubst (DECL_TI_ARGS (decl), args,
7913                         tf_warning_or_error, NULL_TREE);
7914       template_id = lookup_template_function (fns, arglist);
7915
7916       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7917       tmpl = determine_specialization (template_id, new_friend,
7918                                        &new_args,
7919                                        /*need_member_template=*/0,
7920                                        TREE_VEC_LENGTH (args),
7921                                        tsk_none);
7922       return instantiate_template (tmpl, new_args, tf_error);
7923     }
7924
7925   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7926
7927   /* The NEW_FRIEND will look like an instantiation, to the
7928      compiler, but is not an instantiation from the point of view of
7929      the language.  For example, we might have had:
7930
7931      template <class T> struct S {
7932        template <class U> friend void f(T, U);
7933      };
7934
7935      Then, in S<int>, template <class U> void f(int, U) is not an
7936      instantiation of anything.  */
7937   if (new_friend == error_mark_node)
7938     return error_mark_node;
7939
7940   DECL_USE_TEMPLATE (new_friend) = 0;
7941   if (TREE_CODE (decl) == TEMPLATE_DECL)
7942     {
7943       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7944       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7945         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7946     }
7947
7948   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7949      is not a template instantiation and should not be mangled like
7950      one.  Therefore, we forget the mangling here; we'll recompute it
7951      later if we need it.  */
7952   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7953     {
7954       SET_DECL_RTL (new_friend, NULL);
7955       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7956     }
7957
7958   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7959     {
7960       tree old_decl;
7961       tree new_friend_template_info;
7962       tree new_friend_result_template_info;
7963       tree ns;
7964       int  new_friend_is_defn;
7965
7966       /* We must save some information from NEW_FRIEND before calling
7967          duplicate decls since that function will free NEW_FRIEND if
7968          possible.  */
7969       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7970       new_friend_is_defn =
7971             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7972                            (template_for_substitution (new_friend)))
7973              != NULL_TREE);
7974       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7975         {
7976           /* This declaration is a `primary' template.  */
7977           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7978
7979           new_friend_result_template_info
7980             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7981         }
7982       else
7983         new_friend_result_template_info = NULL_TREE;
7984
7985       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7986       if (new_friend_is_defn)
7987         DECL_INITIAL (new_friend) = error_mark_node;
7988
7989       /* Inside pushdecl_namespace_level, we will push into the
7990          current namespace. However, the friend function should go
7991          into the namespace of the template.  */
7992       ns = decl_namespace_context (new_friend);
7993       push_nested_namespace (ns);
7994       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7995       pop_nested_namespace (ns);
7996
7997       if (old_decl == error_mark_node)
7998         return error_mark_node;
7999
8000       if (old_decl != new_friend)
8001         {
8002           /* This new friend declaration matched an existing
8003              declaration.  For example, given:
8004
8005                template <class T> void f(T);
8006                template <class U> class C {
8007                  template <class T> friend void f(T) {}
8008                };
8009
8010              the friend declaration actually provides the definition
8011              of `f', once C has been instantiated for some type.  So,
8012              old_decl will be the out-of-class template declaration,
8013              while new_friend is the in-class definition.
8014
8015              But, if `f' was called before this point, the
8016              instantiation of `f' will have DECL_TI_ARGS corresponding
8017              to `T' but not to `U', references to which might appear
8018              in the definition of `f'.  Previously, the most general
8019              template for an instantiation of `f' was the out-of-class
8020              version; now it is the in-class version.  Therefore, we
8021              run through all specialization of `f', adding to their
8022              DECL_TI_ARGS appropriately.  In particular, they need a
8023              new set of outer arguments, corresponding to the
8024              arguments for this class instantiation.
8025
8026              The same situation can arise with something like this:
8027
8028                friend void f(int);
8029                template <class T> class C {
8030                  friend void f(T) {}
8031                };
8032
8033              when `C<int>' is instantiated.  Now, `f(int)' is defined
8034              in the class.  */
8035
8036           if (!new_friend_is_defn)
8037             /* On the other hand, if the in-class declaration does
8038                *not* provide a definition, then we don't want to alter
8039                existing definitions.  We can just leave everything
8040                alone.  */
8041             ;
8042           else
8043             {
8044               tree new_template = TI_TEMPLATE (new_friend_template_info);
8045               tree new_args = TI_ARGS (new_friend_template_info);
8046
8047               /* Overwrite whatever template info was there before, if
8048                  any, with the new template information pertaining to
8049                  the declaration.  */
8050               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8051
8052               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8053                 {
8054                   /* We should have called reregister_specialization in
8055                      duplicate_decls.  */
8056                   gcc_assert (retrieve_specialization (new_template,
8057                                                        new_args, 0)
8058                               == old_decl);
8059
8060                   /* Instantiate it if the global has already been used.  */
8061                   if (DECL_ODR_USED (old_decl))
8062                     instantiate_decl (old_decl, /*defer_ok=*/true,
8063                                       /*expl_inst_class_mem_p=*/false);
8064                 }
8065               else
8066                 {
8067                   tree t;
8068
8069                   /* Indicate that the old function template is a partial
8070                      instantiation.  */
8071                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8072                     = new_friend_result_template_info;
8073
8074                   gcc_assert (new_template
8075                               == most_general_template (new_template));
8076                   gcc_assert (new_template != old_decl);
8077
8078                   /* Reassign any specializations already in the hash table
8079                      to the new more general template, and add the
8080                      additional template args.  */
8081                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8082                        t != NULL_TREE;
8083                        t = TREE_CHAIN (t))
8084                     {
8085                       tree spec = TREE_VALUE (t);
8086                       spec_entry elt;
8087
8088                       elt.tmpl = old_decl;
8089                       elt.args = DECL_TI_ARGS (spec);
8090                       elt.spec = NULL_TREE;
8091
8092                       htab_remove_elt (decl_specializations, &elt);
8093
8094                       DECL_TI_ARGS (spec)
8095                         = add_outermost_template_args (new_args,
8096                                                        DECL_TI_ARGS (spec));
8097
8098                       register_specialization
8099                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8100
8101                     }
8102                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8103                 }
8104             }
8105
8106           /* The information from NEW_FRIEND has been merged into OLD_DECL
8107              by duplicate_decls.  */
8108           new_friend = old_decl;
8109         }
8110     }
8111   else
8112     {
8113       tree context = DECL_CONTEXT (new_friend);
8114       bool dependent_p;
8115
8116       /* In the code
8117            template <class T> class C {
8118              template <class U> friend void C1<U>::f (); // case 1
8119              friend void C2<T>::f ();                    // case 2
8120            };
8121          we only need to make sure CONTEXT is a complete type for
8122          case 2.  To distinguish between the two cases, we note that
8123          CONTEXT of case 1 remains dependent type after tsubst while
8124          this isn't true for case 2.  */
8125       ++processing_template_decl;
8126       dependent_p = dependent_type_p (context);
8127       --processing_template_decl;
8128
8129       if (!dependent_p
8130           && !complete_type_or_else (context, NULL_TREE))
8131         return error_mark_node;
8132
8133       if (COMPLETE_TYPE_P (context))
8134         {
8135           /* Check to see that the declaration is really present, and,
8136              possibly obtain an improved declaration.  */
8137           tree fn = check_classfn (context,
8138                                    new_friend, NULL_TREE);
8139
8140           if (fn)
8141             new_friend = fn;
8142         }
8143     }
8144
8145   return new_friend;
8146 }
8147
8148 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8149    template arguments, as for tsubst.
8150
8151    Returns an appropriate tsubst'd friend type or error_mark_node on
8152    failure.  */
8153
8154 static tree
8155 tsubst_friend_class (tree friend_tmpl, tree args)
8156 {
8157   tree friend_type;
8158   tree tmpl;
8159   tree context;
8160
8161   context = CP_DECL_CONTEXT (friend_tmpl);
8162
8163   if (context != global_namespace)
8164     {
8165       if (TREE_CODE (context) == NAMESPACE_DECL)
8166         push_nested_namespace (context);
8167       else
8168         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8169     }
8170
8171   /* Look for a class template declaration.  We look for hidden names
8172      because two friend declarations of the same template are the
8173      same.  For example, in:
8174
8175        struct A { 
8176          template <typename> friend class F;
8177        };
8178        template <typename> struct B { 
8179          template <typename> friend class F;
8180        };
8181
8182      both F templates are the same.  */
8183   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8184                            /*block_p=*/true, 0, 
8185                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8186
8187   /* But, if we don't find one, it might be because we're in a
8188      situation like this:
8189
8190        template <class T>
8191        struct S {
8192          template <class U>
8193          friend struct S;
8194        };
8195
8196      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8197      for `S<int>', not the TEMPLATE_DECL.  */
8198   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8199     {
8200       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8201       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8202     }
8203
8204   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8205     {
8206       /* The friend template has already been declared.  Just
8207          check to see that the declarations match, and install any new
8208          default parameters.  We must tsubst the default parameters,
8209          of course.  We only need the innermost template parameters
8210          because that is all that redeclare_class_template will look
8211          at.  */
8212       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8213           > TMPL_ARGS_DEPTH (args))
8214         {
8215           tree parms;
8216           location_t saved_input_location;
8217           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8218                                          args, tf_warning_or_error);
8219
8220           saved_input_location = input_location;
8221           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8222           redeclare_class_template (TREE_TYPE (tmpl), parms);
8223           input_location = saved_input_location;
8224           
8225         }
8226
8227       friend_type = TREE_TYPE (tmpl);
8228     }
8229   else
8230     {
8231       /* The friend template has not already been declared.  In this
8232          case, the instantiation of the template class will cause the
8233          injection of this template into the global scope.  */
8234       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8235       if (tmpl == error_mark_node)
8236         return error_mark_node;
8237
8238       /* The new TMPL is not an instantiation of anything, so we
8239          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8240          the new type because that is supposed to be the corresponding
8241          template decl, i.e., TMPL.  */
8242       DECL_USE_TEMPLATE (tmpl) = 0;
8243       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8244       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8245       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8246         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8247
8248       /* Inject this template into the global scope.  */
8249       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8250     }
8251
8252   if (context != global_namespace)
8253     {
8254       if (TREE_CODE (context) == NAMESPACE_DECL)
8255         pop_nested_namespace (context);
8256       else
8257         pop_nested_class ();
8258     }
8259
8260   return friend_type;
8261 }
8262
8263 /* Returns zero if TYPE cannot be completed later due to circularity.
8264    Otherwise returns one.  */
8265
8266 static int
8267 can_complete_type_without_circularity (tree type)
8268 {
8269   if (type == NULL_TREE || type == error_mark_node)
8270     return 0;
8271   else if (COMPLETE_TYPE_P (type))
8272     return 1;
8273   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8274     return can_complete_type_without_circularity (TREE_TYPE (type));
8275   else if (CLASS_TYPE_P (type)
8276            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8277     return 0;
8278   else
8279     return 1;
8280 }
8281
8282 /* Apply any attributes which had to be deferred until instantiation
8283    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8284    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8285
8286 static void
8287 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8288                                 tree args, tsubst_flags_t complain, tree in_decl)
8289 {
8290   tree last_dep = NULL_TREE;
8291   tree t;
8292   tree *p;
8293
8294   for (t = attributes; t; t = TREE_CHAIN (t))
8295     if (ATTR_IS_DEPENDENT (t))
8296       {
8297         last_dep = t;
8298         attributes = copy_list (attributes);
8299         break;
8300       }
8301
8302   if (DECL_P (*decl_p))
8303     {
8304       if (TREE_TYPE (*decl_p) == error_mark_node)
8305         return;
8306       p = &DECL_ATTRIBUTES (*decl_p);
8307     }
8308   else
8309     p = &TYPE_ATTRIBUTES (*decl_p);
8310
8311   if (last_dep)
8312     {
8313       tree late_attrs = NULL_TREE;
8314       tree *q = &late_attrs;
8315
8316       for (*p = attributes; *p; )
8317         {
8318           t = *p;
8319           if (ATTR_IS_DEPENDENT (t))
8320             {
8321               *p = TREE_CHAIN (t);
8322               TREE_CHAIN (t) = NULL_TREE;
8323               /* If the first attribute argument is an identifier, don't
8324                  pass it through tsubst.  Attributes like mode, format,
8325                  cleanup and several target specific attributes expect it
8326                  unmodified.  */
8327               if (TREE_VALUE (t)
8328                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8329                   && TREE_VALUE (TREE_VALUE (t))
8330                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8331                       == IDENTIFIER_NODE))
8332                 {
8333                   tree chain
8334                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8335                                    in_decl,
8336                                    /*integral_constant_expression_p=*/false);
8337                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8338                     TREE_VALUE (t)
8339                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8340                                    chain);
8341                 }
8342               else
8343                 TREE_VALUE (t)
8344                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8345                                  /*integral_constant_expression_p=*/false);
8346               *q = t;
8347               q = &TREE_CHAIN (t);
8348             }
8349           else
8350             p = &TREE_CHAIN (t);
8351         }
8352
8353       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8354     }
8355 }
8356
8357 /* Perform (or defer) access check for typedefs that were referenced
8358    from within the template TMPL code.
8359    This is a subroutine of instantiate_template and instantiate_class_template.
8360    TMPL is the template to consider and TARGS is the list of arguments of
8361    that template.  */
8362
8363 static void
8364 perform_typedefs_access_check (tree tmpl, tree targs)
8365 {
8366   location_t saved_location;
8367   int i;
8368   qualified_typedef_usage_t *iter;
8369
8370   if (!tmpl
8371       || (!CLASS_TYPE_P (tmpl)
8372           && TREE_CODE (tmpl) != FUNCTION_DECL))
8373     return;
8374
8375   saved_location = input_location;
8376   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8377                     get_types_needing_access_check (tmpl),
8378                     i, iter)
8379     {
8380       tree type_decl = iter->typedef_decl;
8381       tree type_scope = iter->context;
8382
8383       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8384         continue;
8385
8386       if (uses_template_parms (type_decl))
8387         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8388       if (uses_template_parms (type_scope))
8389         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8390
8391       /* Make access check error messages point to the location
8392          of the use of the typedef.  */
8393       input_location = iter->locus;
8394       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8395                                      type_decl, type_decl);
8396     }
8397     input_location = saved_location;
8398 }
8399
8400 static tree
8401 instantiate_class_template_1 (tree type)
8402 {
8403   tree templ, args, pattern, t, member;
8404   tree typedecl;
8405   tree pbinfo;
8406   tree base_list;
8407   unsigned int saved_maximum_field_alignment;
8408   tree fn_context;
8409
8410   if (type == error_mark_node)
8411     return error_mark_node;
8412
8413   if (COMPLETE_OR_OPEN_TYPE_P (type)
8414       || uses_template_parms (type))
8415     return type;
8416
8417   /* Figure out which template is being instantiated.  */
8418   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8419   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8420
8421   /* Determine what specialization of the original template to
8422      instantiate.  */
8423   t = most_specialized_class (type, templ, tf_warning_or_error);
8424   if (t == error_mark_node)
8425     {
8426       TYPE_BEING_DEFINED (type) = 1;
8427       return error_mark_node;
8428     }
8429   else if (t)
8430     {
8431       /* This TYPE is actually an instantiation of a partial
8432          specialization.  We replace the innermost set of ARGS with
8433          the arguments appropriate for substitution.  For example,
8434          given:
8435
8436            template <class T> struct S {};
8437            template <class T> struct S<T*> {};
8438
8439          and supposing that we are instantiating S<int*>, ARGS will
8440          presently be {int*} -- but we need {int}.  */
8441       pattern = TREE_TYPE (t);
8442       args = TREE_PURPOSE (t);
8443     }
8444   else
8445     {
8446       pattern = TREE_TYPE (templ);
8447       args = CLASSTYPE_TI_ARGS (type);
8448     }
8449
8450   /* If the template we're instantiating is incomplete, then clearly
8451      there's nothing we can do.  */
8452   if (!COMPLETE_TYPE_P (pattern))
8453     return type;
8454
8455   /* If we've recursively instantiated too many templates, stop.  */
8456   if (! push_tinst_level (type))
8457     return type;
8458
8459   /* Now we're really doing the instantiation.  Mark the type as in
8460      the process of being defined.  */
8461   TYPE_BEING_DEFINED (type) = 1;
8462
8463   /* We may be in the middle of deferred access check.  Disable
8464      it now.  */
8465   push_deferring_access_checks (dk_no_deferred);
8466
8467   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
8468   if (!fn_context)
8469     push_to_top_level ();
8470   /* Use #pragma pack from the template context.  */
8471   saved_maximum_field_alignment = maximum_field_alignment;
8472   maximum_field_alignment = TYPE_PRECISION (pattern);
8473
8474   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8475
8476   /* Set the input location to the most specialized template definition.
8477      This is needed if tsubsting causes an error.  */
8478   typedecl = TYPE_MAIN_DECL (pattern);
8479   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8480     DECL_SOURCE_LOCATION (typedecl);
8481
8482   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8483   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8484   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8485   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8486   if (ANON_AGGR_TYPE_P (pattern))
8487     SET_ANON_AGGR_TYPE_P (type);
8488   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8489     {
8490       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8491       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8492       /* Adjust visibility for template arguments.  */
8493       determine_visibility (TYPE_MAIN_DECL (type));
8494     }
8495   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8496
8497   pbinfo = TYPE_BINFO (pattern);
8498
8499   /* We should never instantiate a nested class before its enclosing
8500      class; we need to look up the nested class by name before we can
8501      instantiate it, and that lookup should instantiate the enclosing
8502      class.  */
8503   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8504               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8505
8506   base_list = NULL_TREE;
8507   if (BINFO_N_BASE_BINFOS (pbinfo))
8508     {
8509       tree pbase_binfo;
8510       tree pushed_scope;
8511       int i;
8512
8513       /* We must enter the scope containing the type, as that is where
8514          the accessibility of types named in dependent bases are
8515          looked up from.  */
8516       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8517
8518       /* Substitute into each of the bases to determine the actual
8519          basetypes.  */
8520       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8521         {
8522           tree base;
8523           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8524           tree expanded_bases = NULL_TREE;
8525           int idx, len = 1;
8526
8527           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8528             {
8529               expanded_bases = 
8530                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8531                                        args, tf_error, NULL_TREE);
8532               if (expanded_bases == error_mark_node)
8533                 continue;
8534
8535               len = TREE_VEC_LENGTH (expanded_bases);
8536             }
8537
8538           for (idx = 0; idx < len; idx++)
8539             {
8540               if (expanded_bases)
8541                 /* Extract the already-expanded base class.  */
8542                 base = TREE_VEC_ELT (expanded_bases, idx);
8543               else
8544                 /* Substitute to figure out the base class.  */
8545                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8546                                NULL_TREE);
8547
8548               if (base == error_mark_node)
8549                 continue;
8550
8551               base_list = tree_cons (access, base, base_list);
8552               if (BINFO_VIRTUAL_P (pbase_binfo))
8553                 TREE_TYPE (base_list) = integer_type_node;
8554             }
8555         }
8556
8557       /* The list is now in reverse order; correct that.  */
8558       base_list = nreverse (base_list);
8559
8560       if (pushed_scope)
8561         pop_scope (pushed_scope);
8562     }
8563   /* Now call xref_basetypes to set up all the base-class
8564      information.  */
8565   xref_basetypes (type, base_list);
8566
8567   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8568                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8569                                   args, tf_error, NULL_TREE);
8570   fixup_attribute_variants (type);
8571
8572   /* Now that our base classes are set up, enter the scope of the
8573      class, so that name lookups into base classes, etc. will work
8574      correctly.  This is precisely analogous to what we do in
8575      begin_class_definition when defining an ordinary non-template
8576      class, except we also need to push the enclosing classes.  */
8577   push_nested_class (type);
8578
8579   /* Now members are processed in the order of declaration.  */
8580   for (member = CLASSTYPE_DECL_LIST (pattern);
8581        member; member = TREE_CHAIN (member))
8582     {
8583       tree t = TREE_VALUE (member);
8584
8585       if (TREE_PURPOSE (member))
8586         {
8587           if (TYPE_P (t))
8588             {
8589               /* Build new CLASSTYPE_NESTED_UTDS.  */
8590
8591               tree newtag;
8592               bool class_template_p;
8593
8594               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8595                                   && TYPE_LANG_SPECIFIC (t)
8596                                   && CLASSTYPE_IS_TEMPLATE (t));
8597               /* If the member is a class template, then -- even after
8598                  substitution -- there may be dependent types in the
8599                  template argument list for the class.  We increment
8600                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8601                  that function will assume that no types are dependent
8602                  when outside of a template.  */
8603               if (class_template_p)
8604                 ++processing_template_decl;
8605               newtag = tsubst (t, args, tf_error, NULL_TREE);
8606               if (class_template_p)
8607                 --processing_template_decl;
8608               if (newtag == error_mark_node)
8609                 continue;
8610
8611               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8612                 {
8613                   tree name = TYPE_IDENTIFIER (t);
8614
8615                   if (class_template_p)
8616                     /* Unfortunately, lookup_template_class sets
8617                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8618                        instantiation (i.e., for the type of a member
8619                        template class nested within a template class.)
8620                        This behavior is required for
8621                        maybe_process_partial_specialization to work
8622                        correctly, but is not accurate in this case;
8623                        the TAG is not an instantiation of anything.
8624                        (The corresponding TEMPLATE_DECL is an
8625                        instantiation, but the TYPE is not.) */
8626                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8627
8628                   /* Now, we call pushtag to put this NEWTAG into the scope of
8629                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8630                      pushtag calling push_template_decl.  We don't have to do
8631                      this for enums because it will already have been done in
8632                      tsubst_enum.  */
8633                   if (name)
8634                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8635                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8636                 }
8637             }
8638           else if (TREE_CODE (t) == FUNCTION_DECL
8639                    || DECL_FUNCTION_TEMPLATE_P (t))
8640             {
8641               /* Build new TYPE_METHODS.  */
8642               tree r;
8643
8644               if (TREE_CODE (t) == TEMPLATE_DECL)
8645                 ++processing_template_decl;
8646               r = tsubst (t, args, tf_error, NULL_TREE);
8647               if (TREE_CODE (t) == TEMPLATE_DECL)
8648                 --processing_template_decl;
8649               set_current_access_from_decl (r);
8650               finish_member_declaration (r);
8651               /* Instantiate members marked with attribute used.  */
8652               if (r != error_mark_node && DECL_PRESERVE_P (r))
8653                 mark_used (r);
8654             }
8655           else
8656             {
8657               /* Build new TYPE_FIELDS.  */
8658               if (TREE_CODE (t) == STATIC_ASSERT)
8659                 {
8660                   tree condition = 
8661                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8662                                  tf_warning_or_error, NULL_TREE,
8663                                  /*integral_constant_expression_p=*/true);
8664                   finish_static_assert (condition,
8665                                         STATIC_ASSERT_MESSAGE (t), 
8666                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8667                                         /*member_p=*/true);
8668                 }
8669               else if (TREE_CODE (t) != CONST_DECL)
8670                 {
8671                   tree r;
8672
8673                   /* The file and line for this declaration, to
8674                      assist in error message reporting.  Since we
8675                      called push_tinst_level above, we don't need to
8676                      restore these.  */
8677                   input_location = DECL_SOURCE_LOCATION (t);
8678
8679                   if (TREE_CODE (t) == TEMPLATE_DECL)
8680                     ++processing_template_decl;
8681                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8682                   if (TREE_CODE (t) == TEMPLATE_DECL)
8683                     --processing_template_decl;
8684                   if (TREE_CODE (r) == VAR_DECL)
8685                     {
8686                       /* In [temp.inst]:
8687
8688                            [t]he initialization (and any associated
8689                            side-effects) of a static data member does
8690                            not occur unless the static data member is
8691                            itself used in a way that requires the
8692                            definition of the static data member to
8693                            exist.
8694
8695                          Therefore, we do not substitute into the
8696                          initialized for the static data member here.  */
8697                       finish_static_data_member_decl
8698                         (r,
8699                          /*init=*/NULL_TREE,
8700                          /*init_const_expr_p=*/false,
8701                          /*asmspec_tree=*/NULL_TREE,
8702                          /*flags=*/0);
8703                       /* Instantiate members marked with attribute used.  */
8704                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8705                         mark_used (r);
8706                     }
8707                   else if (TREE_CODE (r) == FIELD_DECL)
8708                     {
8709                       /* Determine whether R has a valid type and can be
8710                          completed later.  If R is invalid, then it is
8711                          replaced by error_mark_node so that it will not be
8712                          added to TYPE_FIELDS.  */
8713                       tree rtype = TREE_TYPE (r);
8714                       if (can_complete_type_without_circularity (rtype))
8715                         complete_type (rtype);
8716
8717                       if (!COMPLETE_TYPE_P (rtype))
8718                         {
8719                           cxx_incomplete_type_error (r, rtype);
8720                           r = error_mark_node;
8721                         }
8722                     }
8723
8724                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8725                      such a thing will already have been added to the field
8726                      list by tsubst_enum in finish_member_declaration in the
8727                      CLASSTYPE_NESTED_UTDS case above.  */
8728                   if (!(TREE_CODE (r) == TYPE_DECL
8729                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8730                         && DECL_ARTIFICIAL (r)))
8731                     {
8732                       set_current_access_from_decl (r);
8733                       finish_member_declaration (r);
8734                     }
8735                 }
8736             }
8737         }
8738       else
8739         {
8740           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8741             {
8742               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8743
8744               tree friend_type = t;
8745               bool adjust_processing_template_decl = false;
8746
8747               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8748                 {
8749                   /* template <class T> friend class C;  */
8750                   friend_type = tsubst_friend_class (friend_type, args);
8751                   adjust_processing_template_decl = true;
8752                 }
8753               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8754                 {
8755                   /* template <class T> friend class C::D;  */
8756                   friend_type = tsubst (friend_type, args,
8757                                         tf_warning_or_error, NULL_TREE);
8758                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8759                     friend_type = TREE_TYPE (friend_type);
8760                   adjust_processing_template_decl = true;
8761                 }
8762               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8763                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8764                 {
8765                   /* This could be either
8766
8767                        friend class T::C;
8768
8769                      when dependent_type_p is false or
8770
8771                        template <class U> friend class T::C;
8772
8773                      otherwise.  */
8774                   friend_type = tsubst (friend_type, args,
8775                                         tf_warning_or_error, NULL_TREE);
8776                   /* Bump processing_template_decl for correct
8777                      dependent_type_p calculation.  */
8778                   ++processing_template_decl;
8779                   if (dependent_type_p (friend_type))
8780                     adjust_processing_template_decl = true;
8781                   --processing_template_decl;
8782                 }
8783               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8784                        && hidden_name_p (TYPE_NAME (friend_type)))
8785                 {
8786                   /* friend class C;
8787
8788                      where C hasn't been declared yet.  Let's lookup name
8789                      from namespace scope directly, bypassing any name that
8790                      come from dependent base class.  */
8791                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8792
8793                   /* The call to xref_tag_from_type does injection for friend
8794                      classes.  */
8795                   push_nested_namespace (ns);
8796                   friend_type =
8797                     xref_tag_from_type (friend_type, NULL_TREE,
8798                                         /*tag_scope=*/ts_current);
8799                   pop_nested_namespace (ns);
8800                 }
8801               else if (uses_template_parms (friend_type))
8802                 /* friend class C<T>;  */
8803                 friend_type = tsubst (friend_type, args,
8804                                       tf_warning_or_error, NULL_TREE);
8805               /* Otherwise it's
8806
8807                    friend class C;
8808
8809                  where C is already declared or
8810
8811                    friend class C<int>;
8812
8813                  We don't have to do anything in these cases.  */
8814
8815               if (adjust_processing_template_decl)
8816                 /* Trick make_friend_class into realizing that the friend
8817                    we're adding is a template, not an ordinary class.  It's
8818                    important that we use make_friend_class since it will
8819                    perform some error-checking and output cross-reference
8820                    information.  */
8821                 ++processing_template_decl;
8822
8823               if (friend_type != error_mark_node)
8824                 make_friend_class (type, friend_type, /*complain=*/false);
8825
8826               if (adjust_processing_template_decl)
8827                 --processing_template_decl;
8828             }
8829           else
8830             {
8831               /* Build new DECL_FRIENDLIST.  */
8832               tree r;
8833
8834               /* The file and line for this declaration, to
8835                  assist in error message reporting.  Since we
8836                  called push_tinst_level above, we don't need to
8837                  restore these.  */
8838               input_location = DECL_SOURCE_LOCATION (t);
8839
8840               if (TREE_CODE (t) == TEMPLATE_DECL)
8841                 {
8842                   ++processing_template_decl;
8843                   push_deferring_access_checks (dk_no_check);
8844                 }
8845
8846               r = tsubst_friend_function (t, args);
8847               add_friend (type, r, /*complain=*/false);
8848               if (TREE_CODE (t) == TEMPLATE_DECL)
8849                 {
8850                   pop_deferring_access_checks ();
8851                   --processing_template_decl;
8852                 }
8853             }
8854         }
8855     }
8856
8857   if (CLASSTYPE_LAMBDA_EXPR (type))
8858     {
8859       tree decl = lambda_function (type);
8860       if (decl)
8861         {
8862           tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8863           if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8864             {
8865               apply_lambda_return_type (lambda, void_type_node);
8866               LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8867             }
8868
8869           LAMBDA_EXPR_THIS_CAPTURE (lambda)
8870             = lookup_field_1 (type, get_identifier ("__this"), false);
8871
8872           instantiate_decl (decl, false, false);
8873           maybe_add_lambda_conv_op (type);
8874
8875           LAMBDA_EXPR_THIS_CAPTURE (lambda) = NULL_TREE;
8876         }
8877       else
8878         gcc_assert (errorcount);
8879     }
8880
8881   /* Set the file and line number information to whatever is given for
8882      the class itself.  This puts error messages involving generated
8883      implicit functions at a predictable point, and the same point
8884      that would be used for non-template classes.  */
8885   input_location = DECL_SOURCE_LOCATION (typedecl);
8886
8887   unreverse_member_declarations (type);
8888   finish_struct_1 (type);
8889   TYPE_BEING_DEFINED (type) = 0;
8890
8891   /* We don't instantiate default arguments for member functions.  14.7.1:
8892
8893      The implicit instantiation of a class template specialization causes
8894      the implicit instantiation of the declarations, but not of the
8895      definitions or default arguments, of the class member functions,
8896      member classes, static data members and member templates....  */
8897
8898   /* Some typedefs referenced from within the template code need to be access
8899      checked at template instantiation time, i.e now. These types were
8900      added to the template at parsing time. Let's get those and perform
8901      the access checks then.  */
8902   perform_typedefs_access_check (pattern, args);
8903   perform_deferred_access_checks ();
8904   pop_nested_class ();
8905   maximum_field_alignment = saved_maximum_field_alignment;
8906   if (!fn_context)
8907     pop_from_top_level ();
8908   pop_deferring_access_checks ();
8909   pop_tinst_level ();
8910
8911   /* The vtable for a template class can be emitted in any translation
8912      unit in which the class is instantiated.  When there is no key
8913      method, however, finish_struct_1 will already have added TYPE to
8914      the keyed_classes list.  */
8915   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8916     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8917
8918   return type;
8919 }
8920
8921 /* Wrapper for instantiate_class_template_1.  */
8922
8923 tree
8924 instantiate_class_template (tree type)
8925 {
8926   tree ret;
8927   timevar_push (TV_TEMPLATE_INST);
8928   ret = instantiate_class_template_1 (type);
8929   timevar_pop (TV_TEMPLATE_INST);
8930   return ret;
8931 }
8932
8933 static tree
8934 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8935 {
8936   tree r;
8937
8938   if (!t)
8939     r = t;
8940   else if (TYPE_P (t))
8941     r = tsubst (t, args, complain, in_decl);
8942   else
8943     {
8944       if (!(complain & tf_warning))
8945         ++c_inhibit_evaluation_warnings;
8946       r = tsubst_expr (t, args, complain, in_decl,
8947                        /*integral_constant_expression_p=*/true);
8948       if (!(complain & tf_warning))
8949         --c_inhibit_evaluation_warnings;
8950       /* Preserve the raw-reference nature of T.  */
8951       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
8952           && REFERENCE_REF_P (r))
8953         r = TREE_OPERAND (r, 0);
8954     }
8955   return r;
8956 }
8957
8958 /* Given a function parameter pack TMPL_PARM and some function parameters
8959    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
8960    and set *SPEC_P to point at the next point in the list.  */
8961
8962 static tree
8963 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
8964 {
8965   /* Collect all of the extra "packed" parameters into an
8966      argument pack.  */
8967   tree parmvec;
8968   tree parmtypevec;
8969   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8970   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8971   tree spec_parm = *spec_p;
8972   int i, len;
8973
8974   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
8975     if (tmpl_parm
8976         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
8977       break;
8978
8979   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8980   parmvec = make_tree_vec (len);
8981   parmtypevec = make_tree_vec (len);
8982   spec_parm = *spec_p;
8983   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8984     {
8985       TREE_VEC_ELT (parmvec, i) = spec_parm;
8986       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8987     }
8988
8989   /* Build the argument packs.  */
8990   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8991   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8992   TREE_TYPE (argpack) = argtypepack;
8993   *spec_p = spec_parm;
8994
8995   return argpack;
8996 }
8997
8998 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8999    NONTYPE_ARGUMENT_PACK.  */
9000
9001 static tree
9002 make_fnparm_pack (tree spec_parm)
9003 {
9004   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9005 }
9006
9007 /* Substitute ARGS into T, which is an pack expansion
9008    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9009    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9010    (if only a partial substitution could be performed) or
9011    ERROR_MARK_NODE if there was an error.  */
9012 tree
9013 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9014                        tree in_decl)
9015 {
9016   tree pattern;
9017   tree pack, packs = NULL_TREE;
9018   bool unsubstituted_packs = false;
9019   bool real_packs = false;
9020   int missing_level = 0;
9021   int i, len = -1;
9022   tree result;
9023   htab_t saved_local_specializations = NULL;
9024   bool need_local_specializations = false;
9025   int levels;
9026
9027   gcc_assert (PACK_EXPANSION_P (t));
9028   pattern = PACK_EXPANSION_PATTERN (t);
9029
9030   /* Add in any args remembered from an earlier partial instantiation.  */
9031   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
9032
9033   levels = TMPL_ARGS_DEPTH (args);
9034
9035   /* Determine the argument packs that will instantiate the parameter
9036      packs used in the expansion expression. While we're at it,
9037      compute the number of arguments to be expanded and make sure it
9038      is consistent.  */
9039   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9040        pack = TREE_CHAIN (pack))
9041     {
9042       tree parm_pack = TREE_VALUE (pack);
9043       tree arg_pack = NULL_TREE;
9044       tree orig_arg = NULL_TREE;
9045       int level = 0;
9046
9047       if (TREE_CODE (parm_pack) == BASES)
9048        {
9049          if (BASES_DIRECT (parm_pack))
9050            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9051                                                         args, complain, in_decl, false));
9052          else
9053            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9054                                                  args, complain, in_decl, false));
9055        }
9056       if (TREE_CODE (parm_pack) == PARM_DECL)
9057         {
9058           if (PACK_EXPANSION_LOCAL_P (t))
9059             arg_pack = retrieve_local_specialization (parm_pack);
9060           else
9061             {
9062               /* We can't rely on local_specializations for a parameter
9063                  name used later in a function declaration (such as in a
9064                  late-specified return type).  Even if it exists, it might
9065                  have the wrong value for a recursive call.  Just make a
9066                  dummy decl, since it's only used for its type.  */
9067               /* Copy before tsubsting so that we don't recurse into any
9068                  later PARM_DECLs.  */
9069               arg_pack = tsubst_decl (copy_node (parm_pack), args, complain);
9070               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9071                 /* Partial instantiation of the parm_pack, we can't build
9072                    up an argument pack yet.  */
9073                 arg_pack = NULL_TREE;
9074               else
9075                 arg_pack = make_fnparm_pack (arg_pack);
9076               need_local_specializations = true;
9077             }
9078         }
9079       else
9080         {
9081           int idx;
9082           template_parm_level_and_index (parm_pack, &level, &idx);
9083
9084           if (level <= levels)
9085             arg_pack = TMPL_ARG (args, level, idx);
9086         }
9087
9088       orig_arg = arg_pack;
9089       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9090         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9091       
9092       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9093         /* This can only happen if we forget to expand an argument
9094            pack somewhere else. Just return an error, silently.  */
9095         {
9096           result = make_tree_vec (1);
9097           TREE_VEC_ELT (result, 0) = error_mark_node;
9098           return result;
9099         }
9100
9101       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9102         /* The argument pack that the parameter maps to is just an
9103            expansion of the parameter itself, such as one would find
9104            in the implicit typedef of a class inside the class itself.
9105            Consider this parameter "unsubstituted", so that we will
9106            maintain the outer pack expansion.  */
9107         arg_pack = NULL_TREE;
9108           
9109       if (arg_pack)
9110         {
9111           int my_len = 
9112             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9113
9114           /* Don't bother trying to do a partial substitution with
9115              incomplete packs; we'll try again after deduction.  */
9116           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9117             return t;
9118
9119           if (len < 0)
9120             len = my_len;
9121           else if (len != my_len)
9122             {
9123               if (!(complain & tf_error))
9124                 /* Fail quietly.  */;
9125               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9126                 error ("mismatched argument pack lengths while expanding "
9127                        "%<%T%>",
9128                        pattern);
9129               else
9130                 error ("mismatched argument pack lengths while expanding "
9131                        "%<%E%>",
9132                        pattern);
9133               return error_mark_node;
9134             }
9135
9136           if (TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
9137               && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack),
9138                                                  0)))
9139             /* This isn't a real argument pack yet.  */;
9140           else
9141             real_packs = true;
9142
9143           /* Keep track of the parameter packs and their corresponding
9144              argument packs.  */
9145           packs = tree_cons (parm_pack, arg_pack, packs);
9146           TREE_TYPE (packs) = orig_arg;
9147         }
9148       else
9149         {
9150           /* We can't substitute for this parameter pack.  We use a flag as
9151              well as the missing_level counter because function parameter
9152              packs don't have a level.  */
9153           unsubstituted_packs = true;
9154           if (!missing_level || missing_level > level)
9155             missing_level = level;
9156         }
9157     }
9158
9159   /* We cannot expand this expansion expression, because we don't have
9160      all of the argument packs we need.  */
9161   if (unsubstituted_packs)
9162     {
9163       if (real_packs)
9164         {
9165           /* We got some full packs, but we can't substitute them in until we
9166              have values for all the packs.  So remember these until then.  */
9167           tree save_args;
9168
9169           t = make_pack_expansion (pattern);
9170
9171           /* The call to add_to_template_args above assumes no overlap
9172              between saved args and new args, so prune away any fake
9173              args, i.e. those that satisfied arg_from_parm_pack_p above.  */
9174           if (missing_level && levels >= missing_level)
9175             {
9176               gcc_assert (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
9177                           && missing_level > 1);
9178               TREE_VEC_LENGTH (args) = missing_level - 1;
9179               save_args = copy_node (args);
9180               TREE_VEC_LENGTH (args) = levels;
9181             }
9182           else
9183             save_args = args;
9184
9185           PACK_EXPANSION_EXTRA_ARGS (t) = save_args;
9186         }
9187       else
9188         {
9189           /* There were no real arguments, we're just replacing a parameter
9190              pack with another version of itself. Substitute into the
9191              pattern and return a PACK_EXPANSION_*. The caller will need to
9192              deal with that.  */
9193           if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9194             t = tsubst_expr (pattern, args, complain, in_decl,
9195                              /*integral_constant_expression_p=*/false);
9196           else
9197             t = tsubst (pattern, args, complain, in_decl);
9198           t = make_pack_expansion (t);
9199         }
9200       return t;
9201     }
9202
9203   /* We could not find any argument packs that work.  */
9204   if (len < 0)
9205     return error_mark_node;
9206
9207   if (need_local_specializations)
9208     {
9209       /* We're in a late-specified return type, so create our own local
9210          specializations table; the current table is either NULL or (in the
9211          case of recursive unification) might have bindings that we don't
9212          want to use or alter.  */
9213       saved_local_specializations = local_specializations;
9214       local_specializations = htab_create (37,
9215                                            hash_local_specialization,
9216                                            eq_local_specializations,
9217                                            NULL);
9218     }
9219
9220   /* For each argument in each argument pack, substitute into the
9221      pattern.  */
9222   result = make_tree_vec (len);
9223   for (i = 0; i < len; ++i)
9224     {
9225       /* For parameter pack, change the substitution of the parameter
9226          pack to the ith argument in its argument pack, then expand
9227          the pattern.  */
9228       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9229         {
9230           tree parm = TREE_PURPOSE (pack);
9231           tree arg;
9232
9233           /* Select the Ith argument from the pack.  */
9234           if (TREE_CODE (parm) == PARM_DECL)
9235             {
9236               if (i == 0)
9237                 {
9238                   arg = make_node (ARGUMENT_PACK_SELECT);
9239                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9240                   mark_used (parm);
9241                   register_local_specialization (arg, parm);
9242                 }
9243               else
9244                 arg = retrieve_local_specialization (parm);
9245             }
9246           else
9247             {
9248               int idx, level;
9249               template_parm_level_and_index (parm, &level, &idx);
9250
9251               if (i == 0)
9252                 {
9253                   arg = make_node (ARGUMENT_PACK_SELECT);
9254                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9255                   /* Update the corresponding argument.  */
9256                   TMPL_ARG (args, level, idx) = arg;
9257                 }
9258               else
9259                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9260                 arg = TMPL_ARG (args, level, idx);
9261             }
9262           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9263         }
9264
9265       /* Substitute into the PATTERN with the altered arguments.  */
9266       if (!TYPE_P (pattern))
9267         TREE_VEC_ELT (result, i) = 
9268           tsubst_expr (pattern, args, complain, in_decl,
9269                        /*integral_constant_expression_p=*/false);
9270       else
9271         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9272
9273       if (TREE_VEC_ELT (result, i) == error_mark_node)
9274         {
9275           result = error_mark_node;
9276           break;
9277         }
9278     }
9279
9280   /* Update ARGS to restore the substitution from parameter packs to
9281      their argument packs.  */
9282   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9283     {
9284       tree parm = TREE_PURPOSE (pack);
9285
9286       if (TREE_CODE (parm) == PARM_DECL)
9287         register_local_specialization (TREE_TYPE (pack), parm);
9288       else
9289         {
9290           int idx, level;
9291           template_parm_level_and_index (parm, &level, &idx);
9292           
9293           /* Update the corresponding argument.  */
9294           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9295             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9296               TREE_TYPE (pack);
9297           else
9298             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9299         }
9300     }
9301
9302   if (need_local_specializations)
9303     {
9304       htab_delete (local_specializations);
9305       local_specializations = saved_local_specializations;
9306     }
9307   
9308   return result;
9309 }
9310
9311 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9312    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9313    parameter packs; all parms generated from a function parameter pack will
9314    have the same DECL_PARM_INDEX.  */
9315
9316 tree
9317 get_pattern_parm (tree parm, tree tmpl)
9318 {
9319   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9320   tree patparm;
9321
9322   if (DECL_ARTIFICIAL (parm))
9323     {
9324       for (patparm = DECL_ARGUMENTS (pattern);
9325            patparm; patparm = DECL_CHAIN (patparm))
9326         if (DECL_ARTIFICIAL (patparm)
9327             && DECL_NAME (parm) == DECL_NAME (patparm))
9328           break;
9329     }
9330   else
9331     {
9332       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9333       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9334       gcc_assert (DECL_PARM_INDEX (patparm)
9335                   == DECL_PARM_INDEX (parm));
9336     }
9337
9338   return patparm;
9339 }
9340
9341 /* Substitute ARGS into the vector or list of template arguments T.  */
9342
9343 static tree
9344 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9345 {
9346   tree orig_t = t;
9347   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9348   tree *elts;
9349
9350   if (t == error_mark_node)
9351     return error_mark_node;
9352
9353   len = TREE_VEC_LENGTH (t);
9354   elts = XALLOCAVEC (tree, len);
9355
9356   for (i = 0; i < len; i++)
9357     {
9358       tree orig_arg = TREE_VEC_ELT (t, i);
9359       tree new_arg;
9360
9361       if (TREE_CODE (orig_arg) == TREE_VEC)
9362         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9363       else if (PACK_EXPANSION_P (orig_arg))
9364         {
9365           /* Substitute into an expansion expression.  */
9366           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9367
9368           if (TREE_CODE (new_arg) == TREE_VEC)
9369             /* Add to the expanded length adjustment the number of
9370                expanded arguments. We subtract one from this
9371                measurement, because the argument pack expression
9372                itself is already counted as 1 in
9373                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9374                the argument pack is empty.  */
9375             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9376         }
9377       else if (ARGUMENT_PACK_P (orig_arg))
9378         {
9379           /* Substitute into each of the arguments.  */
9380           new_arg = TYPE_P (orig_arg)
9381             ? cxx_make_type (TREE_CODE (orig_arg))
9382             : make_node (TREE_CODE (orig_arg));
9383           
9384           SET_ARGUMENT_PACK_ARGS (
9385             new_arg,
9386             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9387                                   args, complain, in_decl));
9388
9389           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9390             new_arg = error_mark_node;
9391
9392           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9393             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9394                                           complain, in_decl);
9395             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9396
9397             if (TREE_TYPE (new_arg) == error_mark_node)
9398               new_arg = error_mark_node;
9399           }
9400         }
9401       else
9402         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9403
9404       if (new_arg == error_mark_node)
9405         return error_mark_node;
9406
9407       elts[i] = new_arg;
9408       if (new_arg != orig_arg)
9409         need_new = 1;
9410     }
9411
9412   if (!need_new)
9413     return t;
9414
9415   /* Make space for the expanded arguments coming from template
9416      argument packs.  */
9417   t = make_tree_vec (len + expanded_len_adjust);
9418   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9419      arguments for a member template.
9420      In that case each TREE_VEC in ORIG_T represents a level of template
9421      arguments, and ORIG_T won't carry any non defaulted argument count.
9422      It will rather be the nested TREE_VECs that will carry one.
9423      In other words, ORIG_T carries a non defaulted argument count only
9424      if it doesn't contain any nested TREE_VEC.  */
9425   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9426     {
9427       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9428       count += expanded_len_adjust;
9429       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9430     }
9431   for (i = 0, out = 0; i < len; i++)
9432     {
9433       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9434            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9435           && TREE_CODE (elts[i]) == TREE_VEC)
9436         {
9437           int idx;
9438
9439           /* Now expand the template argument pack "in place".  */
9440           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9441             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9442         }
9443       else
9444         {
9445           TREE_VEC_ELT (t, out) = elts[i];
9446           out++;
9447         }
9448     }
9449
9450   return t;
9451 }
9452
9453 /* Return the result of substituting ARGS into the template parameters
9454    given by PARMS.  If there are m levels of ARGS and m + n levels of
9455    PARMS, then the result will contain n levels of PARMS.  For
9456    example, if PARMS is `template <class T> template <class U>
9457    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9458    result will be `template <int*, double, class V>'.  */
9459
9460 static tree
9461 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9462 {
9463   tree r = NULL_TREE;
9464   tree* new_parms;
9465
9466   /* When substituting into a template, we must set
9467      PROCESSING_TEMPLATE_DECL as the template parameters may be
9468      dependent if they are based on one-another, and the dependency
9469      predicates are short-circuit outside of templates.  */
9470   ++processing_template_decl;
9471
9472   for (new_parms = &r;
9473        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9474        new_parms = &(TREE_CHAIN (*new_parms)),
9475          parms = TREE_CHAIN (parms))
9476     {
9477       tree new_vec =
9478         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9479       int i;
9480
9481       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9482         {
9483           tree tuple;
9484
9485           if (parms == error_mark_node)
9486             continue;
9487
9488           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9489
9490           if (tuple == error_mark_node)
9491             continue;
9492
9493           TREE_VEC_ELT (new_vec, i) =
9494             tsubst_template_parm (tuple, args, complain);
9495         }
9496
9497       *new_parms =
9498         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9499                              - TMPL_ARGS_DEPTH (args)),
9500                    new_vec, NULL_TREE);
9501     }
9502
9503   --processing_template_decl;
9504
9505   return r;
9506 }
9507
9508 /* Return the result of substituting ARGS into one template parameter
9509    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9510    parameter and which TREE_PURPOSE is the default argument of the
9511    template parameter.  */
9512
9513 static tree
9514 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9515 {
9516   tree default_value, parm_decl;
9517
9518   if (args == NULL_TREE
9519       || t == NULL_TREE
9520       || t == error_mark_node)
9521     return t;
9522
9523   gcc_assert (TREE_CODE (t) == TREE_LIST);
9524
9525   default_value = TREE_PURPOSE (t);
9526   parm_decl = TREE_VALUE (t);
9527
9528   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9529   if (TREE_CODE (parm_decl) == PARM_DECL
9530       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9531     parm_decl = error_mark_node;
9532   default_value = tsubst_template_arg (default_value, args,
9533                                        complain, NULL_TREE);
9534
9535   return build_tree_list (default_value, parm_decl);
9536 }
9537
9538 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9539    type T.  If T is not an aggregate or enumeration type, it is
9540    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9541    ENTERING_SCOPE is nonzero, T is the context for a template which
9542    we are presently tsubst'ing.  Return the substituted value.  */
9543
9544 static tree
9545 tsubst_aggr_type (tree t,
9546                   tree args,
9547                   tsubst_flags_t complain,
9548                   tree in_decl,
9549                   int entering_scope)
9550 {
9551   if (t == NULL_TREE)
9552     return NULL_TREE;
9553
9554   switch (TREE_CODE (t))
9555     {
9556     case RECORD_TYPE:
9557       if (TYPE_PTRMEMFUNC_P (t))
9558         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9559
9560       /* Else fall through.  */
9561     case ENUMERAL_TYPE:
9562     case UNION_TYPE:
9563       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9564         {
9565           tree argvec;
9566           tree context;
9567           tree r;
9568           int saved_unevaluated_operand;
9569           int saved_inhibit_evaluation_warnings;
9570
9571           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9572           saved_unevaluated_operand = cp_unevaluated_operand;
9573           cp_unevaluated_operand = 0;
9574           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9575           c_inhibit_evaluation_warnings = 0;
9576
9577           /* First, determine the context for the type we are looking
9578              up.  */
9579           context = TYPE_CONTEXT (t);
9580           if (context && TYPE_P (context))
9581             {
9582               context = tsubst_aggr_type (context, args, complain,
9583                                           in_decl, /*entering_scope=*/1);
9584               /* If context is a nested class inside a class template,
9585                  it may still need to be instantiated (c++/33959).  */
9586               context = complete_type (context);
9587             }
9588
9589           /* Then, figure out what arguments are appropriate for the
9590              type we are trying to find.  For example, given:
9591
9592                template <class T> struct S;
9593                template <class T, class U> void f(T, U) { S<U> su; }
9594
9595              and supposing that we are instantiating f<int, double>,
9596              then our ARGS will be {int, double}, but, when looking up
9597              S we only want {double}.  */
9598           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9599                                          complain, in_decl);
9600           if (argvec == error_mark_node)
9601             r = error_mark_node;
9602           else
9603             {
9604               r = lookup_template_class (t, argvec, in_decl, context,
9605                                          entering_scope, complain);
9606               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9607             }
9608
9609           cp_unevaluated_operand = saved_unevaluated_operand;
9610           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9611
9612           return r;
9613         }
9614       else
9615         /* This is not a template type, so there's nothing to do.  */
9616         return t;
9617
9618     default:
9619       return tsubst (t, args, complain, in_decl);
9620     }
9621 }
9622
9623 /* Substitute into the default argument ARG (a default argument for
9624    FN), which has the indicated TYPE.  */
9625
9626 tree
9627 tsubst_default_argument (tree fn, tree type, tree arg)
9628 {
9629   tree saved_class_ptr = NULL_TREE;
9630   tree saved_class_ref = NULL_TREE;
9631
9632   /* This can happen in invalid code.  */
9633   if (TREE_CODE (arg) == DEFAULT_ARG)
9634     return arg;
9635
9636   /* This default argument came from a template.  Instantiate the
9637      default argument here, not in tsubst.  In the case of
9638      something like:
9639
9640        template <class T>
9641        struct S {
9642          static T t();
9643          void f(T = t());
9644        };
9645
9646      we must be careful to do name lookup in the scope of S<T>,
9647      rather than in the current class.  */
9648   push_access_scope (fn);
9649   /* The "this" pointer is not valid in a default argument.  */
9650   if (cfun)
9651     {
9652       saved_class_ptr = current_class_ptr;
9653       cp_function_chain->x_current_class_ptr = NULL_TREE;
9654       saved_class_ref = current_class_ref;
9655       cp_function_chain->x_current_class_ref = NULL_TREE;
9656     }
9657
9658   push_deferring_access_checks(dk_no_deferred);
9659   /* The default argument expression may cause implicitly defined
9660      member functions to be synthesized, which will result in garbage
9661      collection.  We must treat this situation as if we were within
9662      the body of function so as to avoid collecting live data on the
9663      stack.  */
9664   ++function_depth;
9665   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9666                      tf_warning_or_error, NULL_TREE,
9667                      /*integral_constant_expression_p=*/false);
9668   --function_depth;
9669   pop_deferring_access_checks();
9670
9671   /* Restore the "this" pointer.  */
9672   if (cfun)
9673     {
9674       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9675       cp_function_chain->x_current_class_ref = saved_class_ref;
9676     }
9677
9678   /* Make sure the default argument is reasonable.  */
9679   arg = check_default_argument (type, arg);
9680
9681   pop_access_scope (fn);
9682
9683   return arg;
9684 }
9685
9686 /* Substitute into all the default arguments for FN.  */
9687
9688 static void
9689 tsubst_default_arguments (tree fn)
9690 {
9691   tree arg;
9692   tree tmpl_args;
9693
9694   tmpl_args = DECL_TI_ARGS (fn);
9695
9696   /* If this function is not yet instantiated, we certainly don't need
9697      its default arguments.  */
9698   if (uses_template_parms (tmpl_args))
9699     return;
9700   /* Don't do this again for clones.  */
9701   if (DECL_CLONED_FUNCTION_P (fn))
9702     return;
9703
9704   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9705        arg;
9706        arg = TREE_CHAIN (arg))
9707     if (TREE_PURPOSE (arg))
9708       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9709                                                     TREE_VALUE (arg),
9710                                                     TREE_PURPOSE (arg));
9711 }
9712
9713 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9714    result of the substitution.  Issue error and warning messages under
9715    control of COMPLAIN.  */
9716
9717 static tree
9718 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9719 {
9720 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9721   location_t saved_loc;
9722   tree r = NULL_TREE;
9723   tree in_decl = t;
9724   hashval_t hash = 0;
9725
9726   /* Set the filename and linenumber to improve error-reporting.  */
9727   saved_loc = input_location;
9728   input_location = DECL_SOURCE_LOCATION (t);
9729
9730   switch (TREE_CODE (t))
9731     {
9732     case TEMPLATE_DECL:
9733       {
9734         /* We can get here when processing a member function template,
9735            member class template, or template template parameter.  */
9736         tree decl = DECL_TEMPLATE_RESULT (t);
9737         tree spec;
9738         tree tmpl_args;
9739         tree full_args;
9740
9741         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9742           {
9743             /* Template template parameter is treated here.  */
9744             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9745             if (new_type == error_mark_node)
9746               RETURN (error_mark_node);
9747
9748             r = copy_decl (t);
9749             DECL_CHAIN (r) = NULL_TREE;
9750             TREE_TYPE (r) = new_type;
9751             DECL_TEMPLATE_RESULT (r)
9752               = build_decl (DECL_SOURCE_LOCATION (decl),
9753                             TYPE_DECL, DECL_NAME (decl), new_type);
9754             DECL_TEMPLATE_PARMS (r)
9755               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9756                                        complain);
9757             TYPE_NAME (new_type) = r;
9758             break;
9759           }
9760
9761         /* We might already have an instance of this template.
9762            The ARGS are for the surrounding class type, so the
9763            full args contain the tsubst'd args for the context,
9764            plus the innermost args from the template decl.  */
9765         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9766           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9767           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9768         /* Because this is a template, the arguments will still be
9769            dependent, even after substitution.  If
9770            PROCESSING_TEMPLATE_DECL is not set, the dependency
9771            predicates will short-circuit.  */
9772         ++processing_template_decl;
9773         full_args = tsubst_template_args (tmpl_args, args,
9774                                           complain, in_decl);
9775         --processing_template_decl;
9776         if (full_args == error_mark_node)
9777           RETURN (error_mark_node);
9778
9779         /* If this is a default template template argument,
9780            tsubst might not have changed anything.  */
9781         if (full_args == tmpl_args)
9782           RETURN (t);
9783
9784         hash = hash_tmpl_and_args (t, full_args);
9785         spec = retrieve_specialization (t, full_args, hash);
9786         if (spec != NULL_TREE)
9787           {
9788             r = spec;
9789             break;
9790           }
9791
9792         /* Make a new template decl.  It will be similar to the
9793            original, but will record the current template arguments.
9794            We also create a new function declaration, which is just
9795            like the old one, but points to this new template, rather
9796            than the old one.  */
9797         r = copy_decl (t);
9798         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9799         DECL_CHAIN (r) = NULL_TREE;
9800
9801         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9802
9803         if (TREE_CODE (decl) == TYPE_DECL
9804             && !TYPE_DECL_ALIAS_P (decl))
9805           {
9806             tree new_type;
9807             ++processing_template_decl;
9808             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9809             --processing_template_decl;
9810             if (new_type == error_mark_node)
9811               RETURN (error_mark_node);
9812
9813             TREE_TYPE (r) = new_type;
9814             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9815             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9816             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9817             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9818           }
9819         else
9820           {
9821             tree new_decl;
9822             ++processing_template_decl;
9823             new_decl = tsubst (decl, args, complain, in_decl);
9824             --processing_template_decl;
9825             if (new_decl == error_mark_node)
9826               RETURN (error_mark_node);
9827
9828             DECL_TEMPLATE_RESULT (r) = new_decl;
9829             DECL_TI_TEMPLATE (new_decl) = r;
9830             TREE_TYPE (r) = TREE_TYPE (new_decl);
9831             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9832             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9833           }
9834
9835         SET_DECL_IMPLICIT_INSTANTIATION (r);
9836         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9837         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9838
9839         /* The template parameters for this new template are all the
9840            template parameters for the old template, except the
9841            outermost level of parameters.  */
9842         DECL_TEMPLATE_PARMS (r)
9843           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9844                                    complain);
9845
9846         if (PRIMARY_TEMPLATE_P (t))
9847           DECL_PRIMARY_TEMPLATE (r) = r;
9848
9849         if (TREE_CODE (decl) != TYPE_DECL)
9850           /* Record this non-type partial instantiation.  */
9851           register_specialization (r, t,
9852                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9853                                    false, hash);
9854       }
9855       break;
9856
9857     case FUNCTION_DECL:
9858       {
9859         tree ctx;
9860         tree argvec = NULL_TREE;
9861         tree *friends;
9862         tree gen_tmpl;
9863         tree type;
9864         int member;
9865         int args_depth;
9866         int parms_depth;
9867
9868         /* Nobody should be tsubst'ing into non-template functions.  */
9869         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9870
9871         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9872           {
9873             tree spec;
9874             bool dependent_p;
9875
9876             /* If T is not dependent, just return it.  We have to
9877                increment PROCESSING_TEMPLATE_DECL because
9878                value_dependent_expression_p assumes that nothing is
9879                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9880             ++processing_template_decl;
9881             dependent_p = value_dependent_expression_p (t);
9882             --processing_template_decl;
9883             if (!dependent_p)
9884               RETURN (t);
9885
9886             /* Calculate the most general template of which R is a
9887                specialization, and the complete set of arguments used to
9888                specialize R.  */
9889             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9890             argvec = tsubst_template_args (DECL_TI_ARGS
9891                                           (DECL_TEMPLATE_RESULT
9892                                                  (DECL_TI_TEMPLATE (t))),
9893                                            args, complain, in_decl);
9894             if (argvec == error_mark_node)
9895               RETURN (error_mark_node);
9896
9897             /* Check to see if we already have this specialization.  */
9898             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9899             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9900
9901             if (spec)
9902               {
9903                 r = spec;
9904                 break;
9905               }
9906
9907             /* We can see more levels of arguments than parameters if
9908                there was a specialization of a member template, like
9909                this:
9910
9911                  template <class T> struct S { template <class U> void f(); }
9912                  template <> template <class U> void S<int>::f(U);
9913
9914                Here, we'll be substituting into the specialization,
9915                because that's where we can find the code we actually
9916                want to generate, but we'll have enough arguments for
9917                the most general template.
9918
9919                We also deal with the peculiar case:
9920
9921                  template <class T> struct S {
9922                    template <class U> friend void f();
9923                  };
9924                  template <class U> void f() {}
9925                  template S<int>;
9926                  template void f<double>();
9927
9928                Here, the ARGS for the instantiation of will be {int,
9929                double}.  But, we only need as many ARGS as there are
9930                levels of template parameters in CODE_PATTERN.  We are
9931                careful not to get fooled into reducing the ARGS in
9932                situations like:
9933
9934                  template <class T> struct S { template <class U> void f(U); }
9935                  template <class T> template <> void S<T>::f(int) {}
9936
9937                which we can spot because the pattern will be a
9938                specialization in this case.  */
9939             args_depth = TMPL_ARGS_DEPTH (args);
9940             parms_depth =
9941               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9942             if (args_depth > parms_depth
9943                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9944               args = get_innermost_template_args (args, parms_depth);
9945           }
9946         else
9947           {
9948             /* This special case arises when we have something like this:
9949
9950                  template <class T> struct S {
9951                    friend void f<int>(int, double);
9952                  };
9953
9954                Here, the DECL_TI_TEMPLATE for the friend declaration
9955                will be an IDENTIFIER_NODE.  We are being called from
9956                tsubst_friend_function, and we want only to create a
9957                new decl (R) with appropriate types so that we can call
9958                determine_specialization.  */
9959             gen_tmpl = NULL_TREE;
9960           }
9961
9962         if (DECL_CLASS_SCOPE_P (t))
9963           {
9964             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9965               member = 2;
9966             else
9967               member = 1;
9968             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9969                                     complain, t, /*entering_scope=*/1);
9970           }
9971         else
9972           {
9973             member = 0;
9974             ctx = DECL_CONTEXT (t);
9975           }
9976         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9977         if (type == error_mark_node)
9978           RETURN (error_mark_node);
9979
9980         /* We do NOT check for matching decls pushed separately at this
9981            point, as they may not represent instantiations of this
9982            template, and in any case are considered separate under the
9983            discrete model.  */
9984         r = copy_decl (t);
9985         DECL_USE_TEMPLATE (r) = 0;
9986         TREE_TYPE (r) = type;
9987         /* Clear out the mangled name and RTL for the instantiation.  */
9988         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9989         SET_DECL_RTL (r, NULL);
9990         /* Leave DECL_INITIAL set on deleted instantiations.  */
9991         if (!DECL_DELETED_FN (r))
9992           DECL_INITIAL (r) = NULL_TREE;
9993         DECL_CONTEXT (r) = ctx;
9994
9995         if (member && DECL_CONV_FN_P (r))
9996           /* Type-conversion operator.  Reconstruct the name, in
9997              case it's the name of one of the template's parameters.  */
9998           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9999
10000         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10001                                      complain, t);
10002         DECL_RESULT (r) = NULL_TREE;
10003
10004         TREE_STATIC (r) = 0;
10005         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10006         DECL_EXTERNAL (r) = 1;
10007         /* If this is an instantiation of a function with internal
10008            linkage, we already know what object file linkage will be
10009            assigned to the instantiation.  */
10010         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10011         DECL_DEFER_OUTPUT (r) = 0;
10012         DECL_CHAIN (r) = NULL_TREE;
10013         DECL_PENDING_INLINE_INFO (r) = 0;
10014         DECL_PENDING_INLINE_P (r) = 0;
10015         DECL_SAVED_TREE (r) = NULL_TREE;
10016         DECL_STRUCT_FUNCTION (r) = NULL;
10017         TREE_USED (r) = 0;
10018         /* We'll re-clone as appropriate in instantiate_template.  */
10019         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10020
10021         /* If we aren't complaining now, return on error before we register
10022            the specialization so that we'll complain eventually.  */
10023         if ((complain & tf_error) == 0
10024             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10025             && !grok_op_properties (r, /*complain=*/false))
10026           RETURN (error_mark_node);
10027
10028         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10029            this in the special friend case mentioned above where
10030            GEN_TMPL is NULL.  */
10031         if (gen_tmpl)
10032           {
10033             DECL_TEMPLATE_INFO (r)
10034               = build_template_info (gen_tmpl, argvec);
10035             SET_DECL_IMPLICIT_INSTANTIATION (r);
10036             register_specialization (r, gen_tmpl, argvec, false, hash);
10037
10038             /* We're not supposed to instantiate default arguments
10039                until they are called, for a template.  But, for a
10040                declaration like:
10041
10042                  template <class T> void f ()
10043                  { extern void g(int i = T()); }
10044
10045                we should do the substitution when the template is
10046                instantiated.  We handle the member function case in
10047                instantiate_class_template since the default arguments
10048                might refer to other members of the class.  */
10049             if (!member
10050                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10051                 && !uses_template_parms (argvec))
10052               tsubst_default_arguments (r);
10053           }
10054         else
10055           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10056
10057         /* Copy the list of befriending classes.  */
10058         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10059              *friends;
10060              friends = &TREE_CHAIN (*friends))
10061           {
10062             *friends = copy_node (*friends);
10063             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10064                                             args, complain,
10065                                             in_decl);
10066           }
10067
10068         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10069           {
10070             maybe_retrofit_in_chrg (r);
10071             if (DECL_CONSTRUCTOR_P (r))
10072               grok_ctor_properties (ctx, r);
10073             /* If this is an instantiation of a member template, clone it.
10074                If it isn't, that'll be handled by
10075                clone_constructors_and_destructors.  */
10076             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10077               clone_function_decl (r, /*update_method_vec_p=*/0);
10078           }
10079         else if ((complain & tf_error) != 0
10080                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10081                  && !grok_op_properties (r, /*complain=*/true))
10082           RETURN (error_mark_node);
10083
10084         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10085           SET_DECL_FRIEND_CONTEXT (r,
10086                                    tsubst (DECL_FRIEND_CONTEXT (t),
10087                                             args, complain, in_decl));
10088
10089         /* Possibly limit visibility based on template args.  */
10090         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10091         if (DECL_VISIBILITY_SPECIFIED (t))
10092           {
10093             DECL_VISIBILITY_SPECIFIED (r) = 0;
10094             DECL_ATTRIBUTES (r)
10095               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10096           }
10097         determine_visibility (r);
10098         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10099             && !processing_template_decl)
10100           defaulted_late_check (r);
10101
10102         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10103                                         args, complain, in_decl);
10104       }
10105       break;
10106
10107     case PARM_DECL:
10108       {
10109         tree type = NULL_TREE;
10110         int i, len = 1;
10111         tree expanded_types = NULL_TREE;
10112         tree prev_r = NULL_TREE;
10113         tree first_r = NULL_TREE;
10114
10115         if (FUNCTION_PARAMETER_PACK_P (t))
10116           {
10117             /* If there is a local specialization that isn't a
10118                parameter pack, it means that we're doing a "simple"
10119                substitution from inside tsubst_pack_expansion. Just
10120                return the local specialization (which will be a single
10121                parm).  */
10122             tree spec = retrieve_local_specialization (t);
10123             if (spec 
10124                 && TREE_CODE (spec) == PARM_DECL
10125                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10126               RETURN (spec);
10127
10128             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10129                the parameters in this function parameter pack.  */
10130             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10131                                                     complain, in_decl);
10132             if (TREE_CODE (expanded_types) == TREE_VEC)
10133               {
10134                 len = TREE_VEC_LENGTH (expanded_types);
10135
10136                 /* Zero-length parameter packs are boring. Just substitute
10137                    into the chain.  */
10138                 if (len == 0)
10139                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10140                                   TREE_CHAIN (t)));
10141               }
10142             else
10143               {
10144                 /* All we did was update the type. Make a note of that.  */
10145                 type = expanded_types;
10146                 expanded_types = NULL_TREE;
10147               }
10148           }
10149
10150         /* Loop through all of the parameter's we'll build. When T is
10151            a function parameter pack, LEN is the number of expanded
10152            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10153         r = NULL_TREE;
10154         for (i = 0; i < len; ++i)
10155           {
10156             prev_r = r;
10157             r = copy_node (t);
10158             if (DECL_TEMPLATE_PARM_P (t))
10159               SET_DECL_TEMPLATE_PARM_P (r);
10160
10161             if (expanded_types)
10162               /* We're on the Ith parameter of the function parameter
10163                  pack.  */
10164               {
10165                 /* An argument of a function parameter pack is not a parameter
10166                    pack.  */
10167                 FUNCTION_PARAMETER_PACK_P (r) = false;
10168
10169                 /* Get the Ith type.  */
10170                 type = TREE_VEC_ELT (expanded_types, i);
10171
10172                 if (DECL_NAME (r))
10173                   /* Rename the parameter to include the index.  */
10174                   DECL_NAME (r) =
10175                     make_ith_pack_parameter_name (DECL_NAME (r), i);
10176               }
10177             else if (!type)
10178               /* We're dealing with a normal parameter.  */
10179               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10180
10181             type = type_decays_to (type);
10182             TREE_TYPE (r) = type;
10183             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10184
10185             if (DECL_INITIAL (r))
10186               {
10187                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10188                   DECL_INITIAL (r) = TREE_TYPE (r);
10189                 else
10190                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10191                                              complain, in_decl);
10192               }
10193
10194             DECL_CONTEXT (r) = NULL_TREE;
10195
10196             if (!DECL_TEMPLATE_PARM_P (r))
10197               DECL_ARG_TYPE (r) = type_passed_as (type);
10198
10199             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10200                                             args, complain, in_decl);
10201
10202             /* Keep track of the first new parameter we
10203                generate. That's what will be returned to the
10204                caller.  */
10205             if (!first_r)
10206               first_r = r;
10207
10208             /* Build a proper chain of parameters when substituting
10209                into a function parameter pack.  */
10210             if (prev_r)
10211               DECL_CHAIN (prev_r) = r;
10212           }
10213
10214         if (DECL_CHAIN (t))
10215           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10216                                    complain, DECL_CHAIN (t));
10217
10218         /* FIRST_R contains the start of the chain we've built.  */
10219         r = first_r;
10220       }
10221       break;
10222
10223     case FIELD_DECL:
10224       {
10225         tree type;
10226
10227         r = copy_decl (t);
10228         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10229         if (type == error_mark_node)
10230           RETURN (error_mark_node);
10231         TREE_TYPE (r) = type;
10232         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10233
10234         if (DECL_C_BIT_FIELD (r))
10235           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10236              non-bit-fields DECL_INITIAL is a non-static data member
10237              initializer, which gets deferred instantiation.  */
10238           DECL_INITIAL (r)
10239             = tsubst_expr (DECL_INITIAL (t), args,
10240                            complain, in_decl,
10241                            /*integral_constant_expression_p=*/true);
10242         else if (DECL_INITIAL (t))
10243           {
10244             /* Set up DECL_TEMPLATE_INFO so that we can get at the
10245                NSDMI in perform_member_init.  Still set DECL_INITIAL
10246                so that we know there is one.  */
10247             DECL_INITIAL (r) = void_zero_node;
10248             gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10249             retrofit_lang_decl (r);
10250             DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10251           }
10252         /* We don't have to set DECL_CONTEXT here; it is set by
10253            finish_member_declaration.  */
10254         DECL_CHAIN (r) = NULL_TREE;
10255         if (VOID_TYPE_P (type))
10256           error ("instantiation of %q+D as type %qT", r, type);
10257
10258         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10259                                         args, complain, in_decl);
10260       }
10261       break;
10262
10263     case USING_DECL:
10264       /* We reach here only for member using decls.  We also need to check
10265          uses_template_parms because DECL_DEPENDENT_P is not set for a
10266          using-declaration that designates a member of the current
10267          instantiation (c++/53549).  */
10268       if (DECL_DEPENDENT_P (t)
10269           || uses_template_parms (USING_DECL_SCOPE (t)))
10270         {
10271           r = do_class_using_decl
10272             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10273              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10274           if (!r)
10275             r = error_mark_node;
10276           else
10277             {
10278               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10279               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10280             }
10281         }
10282       else
10283         {
10284           r = copy_node (t);
10285           DECL_CHAIN (r) = NULL_TREE;
10286         }
10287       break;
10288
10289     case TYPE_DECL:
10290     case VAR_DECL:
10291       {
10292         tree argvec = NULL_TREE;
10293         tree gen_tmpl = NULL_TREE;
10294         tree spec;
10295         tree tmpl = NULL_TREE;
10296         tree ctx;
10297         tree type = NULL_TREE;
10298         bool local_p;
10299
10300         if (TREE_CODE (t) == TYPE_DECL
10301             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10302           {
10303             /* If this is the canonical decl, we don't have to
10304                mess with instantiations, and often we can't (for
10305                typename, template type parms and such).  Note that
10306                TYPE_NAME is not correct for the above test if
10307                we've copied the type for a typedef.  */
10308             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10309             if (type == error_mark_node)
10310               RETURN (error_mark_node);
10311             r = TYPE_NAME (type);
10312             break;
10313           }
10314
10315         /* Check to see if we already have the specialization we
10316            need.  */
10317         spec = NULL_TREE;
10318         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10319           {
10320             /* T is a static data member or namespace-scope entity.
10321                We have to substitute into namespace-scope variables
10322                (even though such entities are never templates) because
10323                of cases like:
10324                
10325                  template <class T> void f() { extern T t; }
10326
10327                where the entity referenced is not known until
10328                instantiation time.  */
10329             local_p = false;
10330             ctx = DECL_CONTEXT (t);
10331             if (DECL_CLASS_SCOPE_P (t))
10332               {
10333                 ctx = tsubst_aggr_type (ctx, args,
10334                                         complain,
10335                                         in_decl, /*entering_scope=*/1);
10336                 /* If CTX is unchanged, then T is in fact the
10337                    specialization we want.  That situation occurs when
10338                    referencing a static data member within in its own
10339                    class.  We can use pointer equality, rather than
10340                    same_type_p, because DECL_CONTEXT is always
10341                    canonical...  */
10342                 if (ctx == DECL_CONTEXT (t)
10343                     && (TREE_CODE (t) != TYPE_DECL
10344                         /* ... unless T is a member template; in which
10345                            case our caller can be willing to create a
10346                            specialization of that template represented
10347                            by T.  */
10348                         || !(DECL_TI_TEMPLATE (t)
10349                              && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t)))))
10350                   spec = t;
10351               }
10352
10353             if (!spec)
10354               {
10355                 tmpl = DECL_TI_TEMPLATE (t);
10356                 gen_tmpl = most_general_template (tmpl);
10357                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10358                 if (argvec == error_mark_node)
10359                   RETURN (error_mark_node);
10360                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10361                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10362               }
10363           }
10364         else
10365           {
10366             /* A local variable.  */
10367             local_p = true;
10368             /* Subsequent calls to pushdecl will fill this in.  */
10369             ctx = NULL_TREE;
10370             spec = retrieve_local_specialization (t);
10371           }
10372         /* If we already have the specialization we need, there is
10373            nothing more to do.  */ 
10374         if (spec)
10375           {
10376             r = spec;
10377             break;
10378           }
10379
10380         if (TREE_CODE (t) == VAR_DECL && DECL_ANON_UNION_VAR_P (t))
10381           {
10382             /* Just use name lookup to find a member alias for an anonymous
10383                union, but then add it to the hash table.  */
10384             r = lookup_name (DECL_NAME (t));
10385             gcc_assert (DECL_ANON_UNION_VAR_P (r));
10386             register_local_specialization (r, t);
10387             break;
10388           }
10389
10390         /* Create a new node for the specialization we need.  */
10391         r = copy_decl (t);
10392         if (type == NULL_TREE)
10393           {
10394             if (is_typedef_decl (t))
10395               type = DECL_ORIGINAL_TYPE (t);
10396             else
10397               type = TREE_TYPE (t);
10398             if (TREE_CODE (t) == VAR_DECL
10399                 && VAR_HAD_UNKNOWN_BOUND (t)
10400                 && type != error_mark_node)
10401               type = strip_array_domain (type);
10402             type = tsubst (type, args, complain, in_decl);
10403           }
10404         if (TREE_CODE (r) == VAR_DECL)
10405           {
10406             /* Even if the original location is out of scope, the
10407                newly substituted one is not.  */
10408             DECL_DEAD_FOR_LOCAL (r) = 0;
10409             DECL_INITIALIZED_P (r) = 0;
10410             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10411             if (type == error_mark_node)
10412               RETURN (error_mark_node);
10413             if (TREE_CODE (type) == FUNCTION_TYPE)
10414               {
10415                 /* It may seem that this case cannot occur, since:
10416
10417                      typedef void f();
10418                      void g() { f x; }
10419
10420                    declares a function, not a variable.  However:
10421       
10422                      typedef void f();
10423                      template <typename T> void g() { T t; }
10424                      template void g<f>();
10425
10426                    is an attempt to declare a variable with function
10427                    type.  */
10428                 error ("variable %qD has function type",
10429                        /* R is not yet sufficiently initialized, so we
10430                           just use its name.  */
10431                        DECL_NAME (r));
10432                 RETURN (error_mark_node);
10433               }
10434             type = complete_type (type);
10435             /* Wait until cp_finish_decl to set this again, to handle
10436                circular dependency (template/instantiate6.C). */
10437             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10438             type = check_var_type (DECL_NAME (r), type);
10439
10440             if (DECL_HAS_VALUE_EXPR_P (t))
10441               {
10442                 tree ve = DECL_VALUE_EXPR (t);
10443                 ve = tsubst_expr (ve, args, complain, in_decl,
10444                                   /*constant_expression_p=*/false);
10445                 if (REFERENCE_REF_P (ve))
10446                   {
10447                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10448                     ve = TREE_OPERAND (ve, 0);
10449                   }
10450                 SET_DECL_VALUE_EXPR (r, ve);
10451               }
10452           }
10453         else if (DECL_SELF_REFERENCE_P (t))
10454           SET_DECL_SELF_REFERENCE_P (r);
10455         TREE_TYPE (r) = type;
10456         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10457         DECL_CONTEXT (r) = ctx;
10458         /* Clear out the mangled name and RTL for the instantiation.  */
10459         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10460         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10461           SET_DECL_RTL (r, NULL);
10462         /* The initializer must not be expanded until it is required;
10463            see [temp.inst].  */
10464         DECL_INITIAL (r) = NULL_TREE;
10465         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10466           SET_DECL_RTL (r, NULL);
10467         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10468         if (TREE_CODE (r) == VAR_DECL)
10469           {
10470             /* Possibly limit visibility based on template args.  */
10471             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10472             if (DECL_VISIBILITY_SPECIFIED (t))
10473               {
10474                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10475                 DECL_ATTRIBUTES (r)
10476                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10477               }
10478             determine_visibility (r);
10479           }
10480
10481         if (!local_p)
10482           {
10483             /* A static data member declaration is always marked
10484                external when it is declared in-class, even if an
10485                initializer is present.  We mimic the non-template
10486                processing here.  */
10487             DECL_EXTERNAL (r) = 1;
10488
10489             register_specialization (r, gen_tmpl, argvec, false, hash);
10490             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10491             SET_DECL_IMPLICIT_INSTANTIATION (r);
10492           }
10493         else if (cp_unevaluated_operand)
10494           {
10495             /* We're substituting this var in a decltype outside of its
10496                scope, such as for a lambda return type.  Don't add it to
10497                local_specializations, do perform auto deduction.  */
10498             tree auto_node = type_uses_auto (type);
10499             if (auto_node)
10500               {
10501                 tree init
10502                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10503                                  /*constant_expression_p=*/false);
10504                 init = resolve_nondeduced_context (init);
10505                 TREE_TYPE (r) = type
10506                   = do_auto_deduction (type, init, auto_node);
10507               }
10508           }
10509         else
10510           register_local_specialization (r, t);
10511
10512         DECL_CHAIN (r) = NULL_TREE;
10513
10514         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10515                                         /*flags=*/0,
10516                                         args, complain, in_decl);
10517
10518         /* Preserve a typedef that names a type.  */
10519         if (is_typedef_decl (r))
10520           {
10521             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10522             set_underlying_type (r);
10523           }
10524
10525         layout_decl (r, 0);
10526       }
10527       break;
10528
10529     default:
10530       gcc_unreachable ();
10531     }
10532 #undef RETURN
10533
10534  out:
10535   /* Restore the file and line information.  */
10536   input_location = saved_loc;
10537
10538   return r;
10539 }
10540
10541 /* Substitute into the ARG_TYPES of a function type.
10542    If END is a TREE_CHAIN, leave it and any following types
10543    un-substituted.  */
10544
10545 static tree
10546 tsubst_arg_types (tree arg_types,
10547                   tree args,
10548                   tree end,
10549                   tsubst_flags_t complain,
10550                   tree in_decl)
10551 {
10552   tree remaining_arg_types;
10553   tree type = NULL_TREE;
10554   int i = 1;
10555   tree expanded_args = NULL_TREE;
10556   tree default_arg;
10557
10558   if (!arg_types || arg_types == void_list_node || arg_types == end)
10559     return arg_types;
10560
10561   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10562                                           args, end, complain, in_decl);
10563   if (remaining_arg_types == error_mark_node)
10564     return error_mark_node;
10565
10566   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10567     {
10568       /* For a pack expansion, perform substitution on the
10569          entire expression. Later on, we'll handle the arguments
10570          one-by-one.  */
10571       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10572                                             args, complain, in_decl);
10573
10574       if (TREE_CODE (expanded_args) == TREE_VEC)
10575         /* So that we'll spin through the parameters, one by one.  */
10576         i = TREE_VEC_LENGTH (expanded_args);
10577       else
10578         {
10579           /* We only partially substituted into the parameter
10580              pack. Our type is TYPE_PACK_EXPANSION.  */
10581           type = expanded_args;
10582           expanded_args = NULL_TREE;
10583         }
10584     }
10585
10586   while (i > 0) {
10587     --i;
10588     
10589     if (expanded_args)
10590       type = TREE_VEC_ELT (expanded_args, i);
10591     else if (!type)
10592       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10593
10594     if (type == error_mark_node)
10595       return error_mark_node;
10596     if (VOID_TYPE_P (type))
10597       {
10598         if (complain & tf_error)
10599           {
10600             error ("invalid parameter type %qT", type);
10601             if (in_decl)
10602               error ("in declaration %q+D", in_decl);
10603           }
10604         return error_mark_node;
10605     }
10606     
10607     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10608        top-level qualifiers as required.  */
10609     type = cv_unqualified (type_decays_to (type));
10610
10611     /* We do not substitute into default arguments here.  The standard
10612        mandates that they be instantiated only when needed, which is
10613        done in build_over_call.  */
10614     default_arg = TREE_PURPOSE (arg_types);
10615
10616     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10617       {
10618         /* We've instantiated a template before its default arguments
10619            have been parsed.  This can happen for a nested template
10620            class, and is not an error unless we require the default
10621            argument in a call of this function.  */
10622         remaining_arg_types = 
10623           tree_cons (default_arg, type, remaining_arg_types);
10624         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10625                        remaining_arg_types);
10626       }
10627     else
10628       remaining_arg_types = 
10629         hash_tree_cons (default_arg, type, remaining_arg_types);
10630   }
10631         
10632   return remaining_arg_types;
10633 }
10634
10635 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10636    *not* handle the exception-specification for FNTYPE, because the
10637    initial substitution of explicitly provided template parameters
10638    during argument deduction forbids substitution into the
10639    exception-specification:
10640
10641      [temp.deduct]
10642
10643      All references in the function type of the function template to  the
10644      corresponding template parameters are replaced by the specified tem-
10645      plate argument values.  If a substitution in a template parameter or
10646      in  the function type of the function template results in an invalid
10647      type, type deduction fails.  [Note: The equivalent  substitution  in
10648      exception specifications is done only when the function is instanti-
10649      ated, at which point a program is  ill-formed  if  the  substitution
10650      results in an invalid type.]  */
10651
10652 static tree
10653 tsubst_function_type (tree t,
10654                       tree args,
10655                       tsubst_flags_t complain,
10656                       tree in_decl)
10657 {
10658   tree return_type;
10659   tree arg_types;
10660   tree fntype;
10661
10662   /* The TYPE_CONTEXT is not used for function/method types.  */
10663   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10664
10665   /* Substitute the return type.  */
10666   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10667   if (return_type == error_mark_node)
10668     return error_mark_node;
10669   /* The standard does not presently indicate that creation of a
10670      function type with an invalid return type is a deduction failure.
10671      However, that is clearly analogous to creating an array of "void"
10672      or a reference to a reference.  This is core issue #486.  */
10673   if (TREE_CODE (return_type) == ARRAY_TYPE
10674       || TREE_CODE (return_type) == FUNCTION_TYPE)
10675     {
10676       if (complain & tf_error)
10677         {
10678           if (TREE_CODE (return_type) == ARRAY_TYPE)
10679             error ("function returning an array");
10680           else
10681             error ("function returning a function");
10682         }
10683       return error_mark_node;
10684     }
10685
10686   /* Substitute the argument types.  */
10687   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
10688                                 complain, in_decl);
10689   if (arg_types == error_mark_node)
10690     return error_mark_node;
10691
10692   /* Construct a new type node and return it.  */
10693   if (TREE_CODE (t) == FUNCTION_TYPE)
10694     {
10695       fntype = build_function_type (return_type, arg_types);
10696       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10697     }
10698   else
10699     {
10700       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10701       if (! MAYBE_CLASS_TYPE_P (r))
10702         {
10703           /* [temp.deduct]
10704
10705              Type deduction may fail for any of the following
10706              reasons:
10707
10708              -- Attempting to create "pointer to member of T" when T
10709              is not a class type.  */
10710           if (complain & tf_error)
10711             error ("creating pointer to member function of non-class type %qT",
10712                       r);
10713           return error_mark_node;
10714         }
10715
10716       fntype = build_method_type_directly (r, return_type,
10717                                            TREE_CHAIN (arg_types));
10718     }
10719   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10720
10721   return fntype;
10722 }
10723
10724 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10725    ARGS into that specification, and return the substituted
10726    specification.  If there is no specification, return NULL_TREE.  */
10727
10728 static tree
10729 tsubst_exception_specification (tree fntype,
10730                                 tree args,
10731                                 tsubst_flags_t complain,
10732                                 tree in_decl,
10733                                 bool defer_ok)
10734 {
10735   tree specs;
10736   tree new_specs;
10737
10738   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10739   new_specs = NULL_TREE;
10740   if (specs && TREE_PURPOSE (specs))
10741     {
10742       /* A noexcept-specifier.  */
10743       tree expr = TREE_PURPOSE (specs);
10744       if (expr == boolean_true_node || expr == boolean_false_node)
10745         new_specs = expr;
10746       else if (defer_ok)
10747         {
10748           /* Defer instantiation of noexcept-specifiers to avoid
10749              excessive instantiations (c++/49107).  */
10750           new_specs = make_node (DEFERRED_NOEXCEPT);
10751           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10752             {
10753               /* We already partially instantiated this member template,
10754                  so combine the new args with the old.  */
10755               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10756                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10757               DEFERRED_NOEXCEPT_ARGS (new_specs)
10758                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10759             }
10760           else
10761             {
10762               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10763               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10764             }
10765         }
10766       else
10767         new_specs = tsubst_copy_and_build
10768           (expr, args, complain, in_decl, /*function_p=*/false,
10769            /*integral_constant_expression_p=*/true);
10770       new_specs = build_noexcept_spec (new_specs, complain);
10771     }
10772   else if (specs)
10773     {
10774       if (! TREE_VALUE (specs))
10775         new_specs = specs;
10776       else
10777         while (specs)
10778           {
10779             tree spec;
10780             int i, len = 1;
10781             tree expanded_specs = NULL_TREE;
10782
10783             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10784               {
10785                 /* Expand the pack expansion type.  */
10786                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10787                                                        args, complain,
10788                                                        in_decl);
10789
10790                 if (expanded_specs == error_mark_node)
10791                   return error_mark_node;
10792                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10793                   len = TREE_VEC_LENGTH (expanded_specs);
10794                 else
10795                   {
10796                     /* We're substituting into a member template, so
10797                        we got a TYPE_PACK_EXPANSION back.  Add that
10798                        expansion and move on.  */
10799                     gcc_assert (TREE_CODE (expanded_specs) 
10800                                 == TYPE_PACK_EXPANSION);
10801                     new_specs = add_exception_specifier (new_specs,
10802                                                          expanded_specs,
10803                                                          complain);
10804                     specs = TREE_CHAIN (specs);
10805                     continue;
10806                   }
10807               }
10808
10809             for (i = 0; i < len; ++i)
10810               {
10811                 if (expanded_specs)
10812                   spec = TREE_VEC_ELT (expanded_specs, i);
10813                 else
10814                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10815                 if (spec == error_mark_node)
10816                   return spec;
10817                 new_specs = add_exception_specifier (new_specs, spec, 
10818                                                      complain);
10819               }
10820
10821             specs = TREE_CHAIN (specs);
10822           }
10823     }
10824   return new_specs;
10825 }
10826
10827 /* Take the tree structure T and replace template parameters used
10828    therein with the argument vector ARGS.  IN_DECL is an associated
10829    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10830    Issue error and warning messages under control of COMPLAIN.  Note
10831    that we must be relatively non-tolerant of extensions here, in
10832    order to preserve conformance; if we allow substitutions that
10833    should not be allowed, we may allow argument deductions that should
10834    not succeed, and therefore report ambiguous overload situations
10835    where there are none.  In theory, we could allow the substitution,
10836    but indicate that it should have failed, and allow our caller to
10837    make sure that the right thing happens, but we don't try to do this
10838    yet.
10839
10840    This function is used for dealing with types, decls and the like;
10841    for expressions, use tsubst_expr or tsubst_copy.  */
10842
10843 tree
10844 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10845 {
10846   enum tree_code code;
10847   tree type, r = NULL_TREE;
10848
10849   if (t == NULL_TREE || t == error_mark_node
10850       || t == integer_type_node
10851       || t == void_type_node
10852       || t == char_type_node
10853       || t == unknown_type_node
10854       || TREE_CODE (t) == NAMESPACE_DECL
10855       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10856     return t;
10857
10858   if (DECL_P (t))
10859     return tsubst_decl (t, args, complain);
10860
10861   if (args == NULL_TREE)
10862     return t;
10863
10864   code = TREE_CODE (t);
10865
10866   if (code == IDENTIFIER_NODE)
10867     type = IDENTIFIER_TYPE_VALUE (t);
10868   else
10869     type = TREE_TYPE (t);
10870
10871   gcc_assert (type != unknown_type_node);
10872
10873   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10874      such as attribute aligned.  */
10875   if (TYPE_P (t)
10876       && typedef_variant_p (t))
10877     {
10878       tree decl = TYPE_NAME (t);
10879
10880       if (TYPE_DECL_ALIAS_P (decl)
10881           && DECL_LANG_SPECIFIC (decl)
10882           && DECL_TEMPLATE_INFO (decl)
10883           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
10884         {
10885           /* DECL represents an alias template and we want to
10886              instantiate it.  Let's substitute our arguments for the
10887              template parameters into the declaration and get the
10888              resulting type.  */
10889           r = tsubst (decl, args, complain, decl);
10890         }
10891       else if (DECL_CLASS_SCOPE_P (decl)
10892                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10893                && uses_template_parms (DECL_CONTEXT (decl)))
10894         {
10895           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10896           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10897           r = retrieve_specialization (tmpl, gen_args, 0);
10898         }
10899       else if (DECL_FUNCTION_SCOPE_P (decl)
10900                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10901                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10902         r = retrieve_local_specialization (decl);
10903       else
10904         /* The typedef is from a non-template context.  */
10905         return t;
10906
10907       if (r)
10908         {
10909           r = TREE_TYPE (r);
10910           r = cp_build_qualified_type_real
10911             (r, cp_type_quals (t) | cp_type_quals (r),
10912              complain | tf_ignore_bad_quals);
10913           return r;
10914         }
10915       else
10916         /* We don't have an instantiation yet, so drop the typedef.  */
10917         t = DECL_ORIGINAL_TYPE (decl);
10918     }
10919
10920   if (type
10921       && code != TYPENAME_TYPE
10922       && code != TEMPLATE_TYPE_PARM
10923       && code != IDENTIFIER_NODE
10924       && code != FUNCTION_TYPE
10925       && code != METHOD_TYPE)
10926     type = tsubst (type, args, complain, in_decl);
10927   if (type == error_mark_node)
10928     return error_mark_node;
10929
10930   switch (code)
10931     {
10932     case RECORD_TYPE:
10933     case UNION_TYPE:
10934     case ENUMERAL_TYPE:
10935       return tsubst_aggr_type (t, args, complain, in_decl,
10936                                /*entering_scope=*/0);
10937
10938     case ERROR_MARK:
10939     case IDENTIFIER_NODE:
10940     case VOID_TYPE:
10941     case REAL_TYPE:
10942     case COMPLEX_TYPE:
10943     case VECTOR_TYPE:
10944     case BOOLEAN_TYPE:
10945     case NULLPTR_TYPE:
10946     case LANG_TYPE:
10947       return t;
10948
10949     case INTEGER_TYPE:
10950       if (t == integer_type_node)
10951         return t;
10952
10953       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10954           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10955         return t;
10956
10957       {
10958         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10959
10960         max = tsubst_expr (omax, args, complain, in_decl,
10961                            /*integral_constant_expression_p=*/false);
10962
10963         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10964            needed.  */
10965         if (TREE_CODE (max) == NOP_EXPR
10966             && TREE_SIDE_EFFECTS (omax)
10967             && !TREE_TYPE (max))
10968           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10969
10970         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10971            with TREE_SIDE_EFFECTS that indicates this is not an integral
10972            constant expression.  */
10973         if (processing_template_decl
10974             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10975           {
10976             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10977             TREE_SIDE_EFFECTS (max) = 1;
10978           }
10979
10980         return compute_array_index_type (NULL_TREE, max, complain);
10981       }
10982
10983     case TEMPLATE_TYPE_PARM:
10984     case TEMPLATE_TEMPLATE_PARM:
10985     case BOUND_TEMPLATE_TEMPLATE_PARM:
10986     case TEMPLATE_PARM_INDEX:
10987       {
10988         int idx;
10989         int level;
10990         int levels;
10991         tree arg = NULL_TREE;
10992
10993         r = NULL_TREE;
10994
10995         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10996         template_parm_level_and_index (t, &level, &idx); 
10997
10998         levels = TMPL_ARGS_DEPTH (args);
10999         if (level <= levels)
11000           {
11001             arg = TMPL_ARG (args, level, idx);
11002
11003             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11004               /* See through ARGUMENT_PACK_SELECT arguments. */
11005               arg = ARGUMENT_PACK_SELECT_ARG (arg);
11006           }
11007
11008         if (arg == error_mark_node)
11009           return error_mark_node;
11010         else if (arg != NULL_TREE)
11011           {
11012             if (ARGUMENT_PACK_P (arg))
11013               /* If ARG is an argument pack, we don't actually want to
11014                  perform a substitution here, because substitutions
11015                  for argument packs are only done
11016                  element-by-element. We can get to this point when
11017                  substituting the type of a non-type template
11018                  parameter pack, when that type actually contains
11019                  template parameter packs from an outer template, e.g.,
11020
11021                  template<typename... Types> struct A {
11022                    template<Types... Values> struct B { };
11023                  };  */
11024               return t;
11025
11026             if (code == TEMPLATE_TYPE_PARM)
11027               {
11028                 int quals;
11029                 gcc_assert (TYPE_P (arg));
11030
11031                 quals = cp_type_quals (arg) | cp_type_quals (t);
11032                   
11033                 return cp_build_qualified_type_real
11034                   (arg, quals, complain | tf_ignore_bad_quals);
11035               }
11036             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11037               {
11038                 /* We are processing a type constructed from a
11039                    template template parameter.  */
11040                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11041                                       args, complain, in_decl);
11042                 if (argvec == error_mark_node)
11043                   return error_mark_node;
11044
11045                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
11046                             || TREE_CODE (arg) == TEMPLATE_DECL
11047                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
11048
11049                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
11050                   /* Consider this code:
11051
11052                         template <template <class> class Template>
11053                         struct Internal {
11054                         template <class Arg> using Bind = Template<Arg>;
11055                         };
11056
11057                         template <template <class> class Template, class Arg>
11058                         using Instantiate = Template<Arg>; //#0
11059
11060                         template <template <class> class Template,
11061                                   class Argument>
11062                         using Bind =
11063                           Instantiate<Internal<Template>::template Bind,
11064                                       Argument>; //#1
11065
11066                      When #1 is parsed, the
11067                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
11068                      parameter `Template' in #0 matches the
11069                      UNBOUND_CLASS_TEMPLATE representing the argument
11070                      `Internal<Template>::template Bind'; We then want
11071                      to assemble the type `Bind<Argument>' that can't
11072                      be fully created right now, because
11073                      `Internal<Template>' not being complete, the Bind
11074                      template cannot be looked up in that context.  So
11075                      we need to "store" `Bind<Argument>' for later
11076                      when the context of Bind becomes complete.  Let's
11077                      store that in a TYPENAME_TYPE.  */
11078                   return make_typename_type (TYPE_CONTEXT (arg),
11079                                              build_nt (TEMPLATE_ID_EXPR,
11080                                                        TYPE_IDENTIFIER (arg),
11081                                                        argvec),
11082                                              typename_type,
11083                                              complain);
11084
11085                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11086                    are resolving nested-types in the signature of a
11087                    member function templates.  Otherwise ARG is a
11088                    TEMPLATE_DECL and is the real template to be
11089                    instantiated.  */
11090                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11091                   arg = TYPE_NAME (arg);
11092
11093                 r = lookup_template_class (arg,
11094                                            argvec, in_decl,
11095                                            DECL_CONTEXT (arg),
11096                                             /*entering_scope=*/0,
11097                                            complain);
11098                 return cp_build_qualified_type_real
11099                   (r, cp_type_quals (t), complain);
11100               }
11101             else
11102               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11103               return convert_from_reference (unshare_expr (arg));
11104           }
11105
11106         if (level == 1)
11107           /* This can happen during the attempted tsubst'ing in
11108              unify.  This means that we don't yet have any information
11109              about the template parameter in question.  */
11110           return t;
11111
11112         /* If we get here, we must have been looking at a parm for a
11113            more deeply nested template.  Make a new version of this
11114            template parameter, but with a lower level.  */
11115         switch (code)
11116           {
11117           case TEMPLATE_TYPE_PARM:
11118           case TEMPLATE_TEMPLATE_PARM:
11119           case BOUND_TEMPLATE_TEMPLATE_PARM:
11120             if (cp_type_quals (t))
11121               {
11122                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11123                 r = cp_build_qualified_type_real
11124                   (r, cp_type_quals (t),
11125                    complain | (code == TEMPLATE_TYPE_PARM
11126                                ? tf_ignore_bad_quals : 0));
11127               }
11128             else
11129               {
11130                 r = copy_type (t);
11131                 TEMPLATE_TYPE_PARM_INDEX (r)
11132                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11133                                                 r, levels, args, complain);
11134                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11135                 TYPE_MAIN_VARIANT (r) = r;
11136                 TYPE_POINTER_TO (r) = NULL_TREE;
11137                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11138
11139                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11140                   /* We have reduced the level of the template
11141                      template parameter, but not the levels of its
11142                      template parameters, so canonical_type_parameter
11143                      will not be able to find the canonical template
11144                      template parameter for this level. Thus, we
11145                      require structural equality checking to compare
11146                      TEMPLATE_TEMPLATE_PARMs. */
11147                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11148                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11149                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11150                 else
11151                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11152
11153                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11154                   {
11155                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11156                                           complain, in_decl);
11157                     if (argvec == error_mark_node)
11158                       return error_mark_node;
11159
11160                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11161                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11162                   }
11163               }
11164             break;
11165
11166           case TEMPLATE_PARM_INDEX:
11167             r = reduce_template_parm_level (t, type, levels, args, complain);
11168             break;
11169
11170           default:
11171             gcc_unreachable ();
11172           }
11173
11174         return r;
11175       }
11176
11177     case TREE_LIST:
11178       {
11179         tree purpose, value, chain;
11180
11181         if (t == void_list_node)
11182           return t;
11183
11184         purpose = TREE_PURPOSE (t);
11185         if (purpose)
11186           {
11187             purpose = tsubst (purpose, args, complain, in_decl);
11188             if (purpose == error_mark_node)
11189               return error_mark_node;
11190           }
11191         value = TREE_VALUE (t);
11192         if (value)
11193           {
11194             value = tsubst (value, args, complain, in_decl);
11195             if (value == error_mark_node)
11196               return error_mark_node;
11197           }
11198         chain = TREE_CHAIN (t);
11199         if (chain && chain != void_type_node)
11200           {
11201             chain = tsubst (chain, args, complain, in_decl);
11202             if (chain == error_mark_node)
11203               return error_mark_node;
11204           }
11205         if (purpose == TREE_PURPOSE (t)
11206             && value == TREE_VALUE (t)
11207             && chain == TREE_CHAIN (t))
11208           return t;
11209         return hash_tree_cons (purpose, value, chain);
11210       }
11211
11212     case TREE_BINFO:
11213       /* We should never be tsubsting a binfo.  */
11214       gcc_unreachable ();
11215
11216     case TREE_VEC:
11217       /* A vector of template arguments.  */
11218       gcc_assert (!type);
11219       return tsubst_template_args (t, args, complain, in_decl);
11220
11221     case POINTER_TYPE:
11222     case REFERENCE_TYPE:
11223       {
11224         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11225           return t;
11226
11227         /* [temp.deduct]
11228
11229            Type deduction may fail for any of the following
11230            reasons:
11231
11232            -- Attempting to create a pointer to reference type.
11233            -- Attempting to create a reference to a reference type or
11234               a reference to void.
11235
11236           Core issue 106 says that creating a reference to a reference
11237           during instantiation is no longer a cause for failure. We
11238           only enforce this check in strict C++98 mode.  */
11239         if ((TREE_CODE (type) == REFERENCE_TYPE
11240              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11241             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11242           {
11243             static location_t last_loc;
11244
11245             /* We keep track of the last time we issued this error
11246                message to avoid spewing a ton of messages during a
11247                single bad template instantiation.  */
11248             if (complain & tf_error
11249                 && last_loc != input_location)
11250               {
11251                 if (TREE_CODE (type) == VOID_TYPE)
11252                   error ("forming reference to void");
11253                else if (code == POINTER_TYPE)
11254                  error ("forming pointer to reference type %qT", type);
11255                else
11256                   error ("forming reference to reference type %qT", type);
11257                 last_loc = input_location;
11258               }
11259
11260             return error_mark_node;
11261           }
11262         else if (code == POINTER_TYPE)
11263           {
11264             r = build_pointer_type (type);
11265             if (TREE_CODE (type) == METHOD_TYPE)
11266               r = build_ptrmemfunc_type (r);
11267           }
11268         else if (TREE_CODE (type) == REFERENCE_TYPE)
11269           /* In C++0x, during template argument substitution, when there is an
11270              attempt to create a reference to a reference type, reference
11271              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11272
11273              "If a template-argument for a template-parameter T names a type
11274              that is a reference to a type A, an attempt to create the type
11275              'lvalue reference to cv T' creates the type 'lvalue reference to
11276              A,' while an attempt to create the type type rvalue reference to
11277              cv T' creates the type T"
11278           */
11279           r = cp_build_reference_type
11280               (TREE_TYPE (type),
11281                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11282         else
11283           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11284         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11285
11286         if (r != error_mark_node)
11287           /* Will this ever be needed for TYPE_..._TO values?  */
11288           layout_type (r);
11289
11290         return r;
11291       }
11292     case OFFSET_TYPE:
11293       {
11294         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11295         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11296           {
11297             /* [temp.deduct]
11298
11299                Type deduction may fail for any of the following
11300                reasons:
11301
11302                -- Attempting to create "pointer to member of T" when T
11303                   is not a class type.  */
11304             if (complain & tf_error)
11305               error ("creating pointer to member of non-class type %qT", r);
11306             return error_mark_node;
11307           }
11308         if (TREE_CODE (type) == REFERENCE_TYPE)
11309           {
11310             if (complain & tf_error)
11311               error ("creating pointer to member reference type %qT", type);
11312             return error_mark_node;
11313           }
11314         if (TREE_CODE (type) == VOID_TYPE)
11315           {
11316             if (complain & tf_error)
11317               error ("creating pointer to member of type void");
11318             return error_mark_node;
11319           }
11320         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11321         if (TREE_CODE (type) == FUNCTION_TYPE)
11322           {
11323             /* The type of the implicit object parameter gets its
11324                cv-qualifiers from the FUNCTION_TYPE. */
11325             tree memptr;
11326             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11327             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11328             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11329                                                  complain);
11330           }
11331         else
11332           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11333                                                cp_type_quals (t),
11334                                                complain);
11335       }
11336     case FUNCTION_TYPE:
11337     case METHOD_TYPE:
11338       {
11339         tree fntype;
11340         tree specs;
11341         fntype = tsubst_function_type (t, args, complain, in_decl);
11342         if (fntype == error_mark_node)
11343           return error_mark_node;
11344
11345         /* Substitute the exception specification.  */
11346         specs = tsubst_exception_specification (t, args, complain,
11347                                                 in_decl, /*defer_ok*/true);
11348         if (specs == error_mark_node)
11349           return error_mark_node;
11350         if (specs)
11351           fntype = build_exception_variant (fntype, specs);
11352         return fntype;
11353       }
11354     case ARRAY_TYPE:
11355       {
11356         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11357         if (domain == error_mark_node)
11358           return error_mark_node;
11359
11360         /* As an optimization, we avoid regenerating the array type if
11361            it will obviously be the same as T.  */
11362         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11363           return t;
11364
11365         /* These checks should match the ones in grokdeclarator.
11366
11367            [temp.deduct]
11368
11369            The deduction may fail for any of the following reasons:
11370
11371            -- Attempting to create an array with an element type that
11372               is void, a function type, or a reference type, or [DR337]
11373               an abstract class type.  */
11374         if (TREE_CODE (type) == VOID_TYPE
11375             || TREE_CODE (type) == FUNCTION_TYPE
11376             || TREE_CODE (type) == REFERENCE_TYPE)
11377           {
11378             if (complain & tf_error)
11379               error ("creating array of %qT", type);
11380             return error_mark_node;
11381           }
11382         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11383           {
11384             if (complain & tf_error)
11385               error ("creating array of %qT, which is an abstract class type",
11386                      type);
11387             return error_mark_node;
11388           }
11389
11390         r = build_cplus_array_type (type, domain);
11391
11392         if (TYPE_USER_ALIGN (t))
11393           {
11394             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11395             TYPE_USER_ALIGN (r) = 1;
11396           }
11397
11398         return r;
11399       }
11400
11401     case TYPENAME_TYPE:
11402       {
11403         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11404                                      in_decl, /*entering_scope=*/1);
11405         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11406                               complain, in_decl);
11407
11408         if (ctx == error_mark_node || f == error_mark_node)
11409           return error_mark_node;
11410
11411         if (!MAYBE_CLASS_TYPE_P (ctx))
11412           {
11413             if (complain & tf_error)
11414               error ("%qT is not a class, struct, or union type", ctx);
11415             return error_mark_node;
11416           }
11417         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11418           {
11419             /* Normally, make_typename_type does not require that the CTX
11420                have complete type in order to allow things like:
11421
11422                  template <class T> struct S { typename S<T>::X Y; };
11423
11424                But, such constructs have already been resolved by this
11425                point, so here CTX really should have complete type, unless
11426                it's a partial instantiation.  */
11427             ctx = complete_type (ctx);
11428             if (!COMPLETE_TYPE_P (ctx))
11429               {
11430                 if (complain & tf_error)
11431                   cxx_incomplete_type_error (NULL_TREE, ctx);
11432                 return error_mark_node;
11433               }
11434           }
11435
11436         f = make_typename_type (ctx, f, typename_type,
11437                                 (complain & tf_error) | tf_keep_type_decl);
11438         if (f == error_mark_node)
11439           return f;
11440         if (TREE_CODE (f) == TYPE_DECL)
11441           {
11442             complain |= tf_ignore_bad_quals;
11443             f = TREE_TYPE (f);
11444           }
11445
11446         if (TREE_CODE (f) != TYPENAME_TYPE)
11447           {
11448             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11449               {
11450                 if (complain & tf_error)
11451                   error ("%qT resolves to %qT, which is not an enumeration type",
11452                          t, f);
11453                 else
11454                   return error_mark_node;
11455               }
11456             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11457               {
11458                 if (complain & tf_error)
11459                   error ("%qT resolves to %qT, which is is not a class type",
11460                          t, f);
11461                 else
11462                   return error_mark_node;
11463               }
11464           }
11465
11466         return cp_build_qualified_type_real
11467           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11468       }
11469
11470     case UNBOUND_CLASS_TEMPLATE:
11471       {
11472         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11473                                      in_decl, /*entering_scope=*/1);
11474         tree name = TYPE_IDENTIFIER (t);
11475         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11476
11477         if (ctx == error_mark_node || name == error_mark_node)
11478           return error_mark_node;
11479
11480         if (parm_list)
11481           parm_list = tsubst_template_parms (parm_list, args, complain);
11482         return make_unbound_class_template (ctx, name, parm_list, complain);
11483       }
11484
11485     case TYPEOF_TYPE:
11486       {
11487         tree type;
11488
11489         ++cp_unevaluated_operand;
11490         ++c_inhibit_evaluation_warnings;
11491
11492         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11493                             complain, in_decl,
11494                             /*integral_constant_expression_p=*/false);
11495
11496         --cp_unevaluated_operand;
11497         --c_inhibit_evaluation_warnings;
11498
11499         type = finish_typeof (type);
11500         return cp_build_qualified_type_real (type,
11501                                              cp_type_quals (t)
11502                                              | cp_type_quals (type),
11503                                              complain);
11504       }
11505
11506     case DECLTYPE_TYPE:
11507       {
11508         tree type;
11509
11510         ++cp_unevaluated_operand;
11511         ++c_inhibit_evaluation_warnings;
11512
11513         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11514                             complain, in_decl,
11515                             /*integral_constant_expression_p=*/false);
11516
11517         --cp_unevaluated_operand;
11518         --c_inhibit_evaluation_warnings;
11519
11520         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11521           type = lambda_capture_field_type (type);
11522         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11523           type = lambda_proxy_type (type);
11524         else
11525           type = finish_decltype_type
11526             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11527         return cp_build_qualified_type_real (type,
11528                                              cp_type_quals (t)
11529                                              | cp_type_quals (type),
11530                                              complain);
11531       }
11532
11533     case UNDERLYING_TYPE:
11534       {
11535         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11536                             complain, in_decl);
11537         return finish_underlying_type (type);
11538       }
11539
11540     case TYPE_ARGUMENT_PACK:
11541     case NONTYPE_ARGUMENT_PACK:
11542       {
11543         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11544         tree packed_out = 
11545           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11546                                 args,
11547                                 complain,
11548                                 in_decl);
11549         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11550
11551         /* For template nontype argument packs, also substitute into
11552            the type.  */
11553         if (code == NONTYPE_ARGUMENT_PACK)
11554           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11555
11556         return r;
11557       }
11558       break;
11559
11560     case INTEGER_CST:
11561     case REAL_CST:
11562     case STRING_CST:
11563     case PLUS_EXPR:
11564     case MINUS_EXPR:
11565     case NEGATE_EXPR:
11566     case NOP_EXPR:
11567     case INDIRECT_REF:
11568     case ADDR_EXPR:
11569     case CALL_EXPR:
11570     case ARRAY_REF:
11571     case SCOPE_REF:
11572       /* We should use one of the expression tsubsts for these codes.  */
11573       gcc_unreachable ();
11574
11575     default:
11576       sorry ("use of %qs in template", tree_code_name [(int) code]);
11577       return error_mark_node;
11578     }
11579 }
11580
11581 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11582    type of the expression on the left-hand side of the "." or "->"
11583    operator.  */
11584
11585 static tree
11586 tsubst_baselink (tree baselink, tree object_type,
11587                  tree args, tsubst_flags_t complain, tree in_decl)
11588 {
11589     tree name;
11590     tree qualifying_scope;
11591     tree fns;
11592     tree optype;
11593     tree template_args = 0;
11594     bool template_id_p = false;
11595     bool qualified = BASELINK_QUALIFIED_P (baselink);
11596
11597     /* A baselink indicates a function from a base class.  Both the
11598        BASELINK_ACCESS_BINFO and the base class referenced may
11599        indicate bases of the template class, rather than the
11600        instantiated class.  In addition, lookups that were not
11601        ambiguous before may be ambiguous now.  Therefore, we perform
11602        the lookup again.  */
11603     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11604     qualifying_scope = tsubst (qualifying_scope, args,
11605                                complain, in_decl);
11606     fns = BASELINK_FUNCTIONS (baselink);
11607     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11608     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11609       {
11610         template_id_p = true;
11611         template_args = TREE_OPERAND (fns, 1);
11612         fns = TREE_OPERAND (fns, 0);
11613         if (template_args)
11614           template_args = tsubst_template_args (template_args, args,
11615                                                 complain, in_decl);
11616       }
11617     name = DECL_NAME (get_first_fn (fns));
11618     if (IDENTIFIER_TYPENAME_P (name))
11619       name = mangle_conv_op_name_for_type (optype);
11620     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11621     if (!baselink)
11622       return error_mark_node;
11623
11624     /* If lookup found a single function, mark it as used at this
11625        point.  (If it lookup found multiple functions the one selected
11626        later by overload resolution will be marked as used at that
11627        point.)  */
11628     if (BASELINK_P (baselink))
11629       fns = BASELINK_FUNCTIONS (baselink);
11630     if (!template_id_p && !really_overloaded_fn (fns))
11631       mark_used (OVL_CURRENT (fns));
11632
11633     /* Add back the template arguments, if present.  */
11634     if (BASELINK_P (baselink) && template_id_p)
11635       BASELINK_FUNCTIONS (baselink)
11636         = build_nt (TEMPLATE_ID_EXPR,
11637                     BASELINK_FUNCTIONS (baselink),
11638                     template_args);
11639     /* Update the conversion operator type.  */
11640     BASELINK_OPTYPE (baselink) = optype;
11641
11642     if (!object_type)
11643       object_type = current_class_type;
11644
11645     if (qualified)
11646       baselink = adjust_result_of_qualified_name_lookup (baselink,
11647                                                          qualifying_scope,
11648                                                          object_type);
11649     return baselink;
11650 }
11651
11652 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11653    true if the qualified-id will be a postfix-expression in-and-of
11654    itself; false if more of the postfix-expression follows the
11655    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11656    of "&".  */
11657
11658 static tree
11659 tsubst_qualified_id (tree qualified_id, tree args,
11660                      tsubst_flags_t complain, tree in_decl,
11661                      bool done, bool address_p)
11662 {
11663   tree expr;
11664   tree scope;
11665   tree name;
11666   bool is_template;
11667   tree template_args;
11668
11669   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11670
11671   /* Figure out what name to look up.  */
11672   name = TREE_OPERAND (qualified_id, 1);
11673   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11674     {
11675       is_template = true;
11676       template_args = TREE_OPERAND (name, 1);
11677       if (template_args)
11678         template_args = tsubst_template_args (template_args, args,
11679                                               complain, in_decl);
11680       name = TREE_OPERAND (name, 0);
11681     }
11682   else
11683     {
11684       is_template = false;
11685       template_args = NULL_TREE;
11686     }
11687
11688   /* Substitute into the qualifying scope.  When there are no ARGS, we
11689      are just trying to simplify a non-dependent expression.  In that
11690      case the qualifying scope may be dependent, and, in any case,
11691      substituting will not help.  */
11692   scope = TREE_OPERAND (qualified_id, 0);
11693   if (args)
11694     {
11695       scope = tsubst (scope, args, complain, in_decl);
11696       expr = tsubst_copy (name, args, complain, in_decl);
11697     }
11698   else
11699     expr = name;
11700
11701   if (dependent_scope_p (scope))
11702     {
11703       if (is_template)
11704         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11705       return build_qualified_name (NULL_TREE, scope, expr,
11706                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11707     }
11708
11709   if (!BASELINK_P (name) && !DECL_P (expr))
11710     {
11711       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11712         {
11713           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11714           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11715             {
11716               error ("qualifying type %qT does not match destructor name ~%qT",
11717                      scope, TREE_OPERAND (expr, 0));
11718               expr = error_mark_node;
11719             }
11720           else
11721             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11722                                           /*is_type_p=*/0, false);
11723         }
11724       else
11725         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11726       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11727                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11728         {
11729           if (complain & tf_error)
11730             {
11731               error ("dependent-name %qE is parsed as a non-type, but "
11732                      "instantiation yields a type", qualified_id);
11733               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11734             }
11735           return error_mark_node;
11736         }
11737     }
11738
11739   if (DECL_P (expr))
11740     {
11741       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11742                                            scope);
11743       /* Remember that there was a reference to this entity.  */
11744       mark_used (expr);
11745     }
11746
11747   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11748     {
11749       if (complain & tf_error)
11750         qualified_name_lookup_error (scope,
11751                                      TREE_OPERAND (qualified_id, 1),
11752                                      expr, input_location);
11753       return error_mark_node;
11754     }
11755
11756   if (is_template)
11757     expr = lookup_template_function (expr, template_args);
11758
11759   if (expr == error_mark_node && complain & tf_error)
11760     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11761                                  expr, input_location);
11762   else if (TYPE_P (scope))
11763     {
11764       expr = (adjust_result_of_qualified_name_lookup
11765               (expr, scope, current_class_type));
11766       expr = (finish_qualified_id_expr
11767               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11768                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11769                /*template_arg_p=*/false));
11770     }
11771
11772   /* Expressions do not generally have reference type.  */
11773   if (TREE_CODE (expr) != SCOPE_REF
11774       /* However, if we're about to form a pointer-to-member, we just
11775          want the referenced member referenced.  */
11776       && TREE_CODE (expr) != OFFSET_REF)
11777     expr = convert_from_reference (expr);
11778
11779   return expr;
11780 }
11781
11782 /* Like tsubst, but deals with expressions.  This function just replaces
11783    template parms; to finish processing the resultant expression, use
11784    tsubst_copy_and_build or tsubst_expr.  */
11785
11786 static tree
11787 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11788 {
11789   enum tree_code code;
11790   tree r;
11791
11792   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11793     return t;
11794
11795   code = TREE_CODE (t);
11796
11797   switch (code)
11798     {
11799     case PARM_DECL:
11800       r = retrieve_local_specialization (t);
11801
11802       if (r == NULL)
11803         {
11804           tree c;
11805
11806           /* We get here for a use of 'this' in an NSDMI.  */
11807           if (DECL_NAME (t) == this_identifier
11808               && at_function_scope_p ()
11809               && DECL_CONSTRUCTOR_P (current_function_decl))
11810             return current_class_ptr;
11811
11812           /* This can happen for a parameter name used later in a function
11813              declaration (such as in a late-specified return type).  Just
11814              make a dummy decl, since it's only used for its type.  */
11815           gcc_assert (cp_unevaluated_operand != 0);
11816           /* We copy T because want to tsubst the PARM_DECL only,
11817              not the following PARM_DECLs that are chained to T.  */
11818           c = copy_node (t);
11819           r = tsubst_decl (c, args, complain);
11820           /* Give it the template pattern as its context; its true context
11821              hasn't been instantiated yet and this is good enough for
11822              mangling.  */
11823           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11824         }
11825       
11826       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11827         r = ARGUMENT_PACK_SELECT_ARG (r);
11828       mark_used (r);
11829       return r;
11830
11831     case CONST_DECL:
11832       {
11833         tree enum_type;
11834         tree v;
11835
11836         if (DECL_TEMPLATE_PARM_P (t))
11837           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11838         /* There is no need to substitute into namespace-scope
11839            enumerators.  */
11840         if (DECL_NAMESPACE_SCOPE_P (t))
11841           return t;
11842         /* If ARGS is NULL, then T is known to be non-dependent.  */
11843         if (args == NULL_TREE)
11844           return integral_constant_value (t);
11845
11846         /* Unfortunately, we cannot just call lookup_name here.
11847            Consider:
11848
11849              template <int I> int f() {
11850              enum E { a = I };
11851              struct S { void g() { E e = a; } };
11852              };
11853
11854            When we instantiate f<7>::S::g(), say, lookup_name is not
11855            clever enough to find f<7>::a.  */
11856         enum_type
11857           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11858                               /*entering_scope=*/0);
11859
11860         for (v = TYPE_VALUES (enum_type);
11861              v != NULL_TREE;
11862              v = TREE_CHAIN (v))
11863           if (TREE_PURPOSE (v) == DECL_NAME (t))
11864             return TREE_VALUE (v);
11865
11866           /* We didn't find the name.  That should never happen; if
11867              name-lookup found it during preliminary parsing, we
11868              should find it again here during instantiation.  */
11869         gcc_unreachable ();
11870       }
11871       return t;
11872
11873     case FIELD_DECL:
11874       if (DECL_CONTEXT (t))
11875         {
11876           tree ctx;
11877
11878           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11879                                   /*entering_scope=*/1);
11880           if (ctx != DECL_CONTEXT (t))
11881             {
11882               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11883               if (!r)
11884                 {
11885                   if (complain & tf_error)
11886                     error ("using invalid field %qD", t);
11887                   return error_mark_node;
11888                 }
11889               return r;
11890             }
11891         }
11892
11893       return t;
11894
11895     case VAR_DECL:
11896     case FUNCTION_DECL:
11897       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11898           || local_variable_p (t))
11899         t = tsubst (t, args, complain, in_decl);
11900       mark_used (t);
11901       return t;
11902
11903     case NAMESPACE_DECL:
11904       return t;
11905
11906     case OVERLOAD:
11907       /* An OVERLOAD will always be a non-dependent overload set; an
11908          overload set from function scope will just be represented with an
11909          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11910       gcc_assert (!uses_template_parms (t));
11911       return t;
11912
11913     case BASELINK:
11914       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11915
11916     case TEMPLATE_DECL:
11917       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11918         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11919                        args, complain, in_decl);
11920       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11921         return tsubst (t, args, complain, in_decl);
11922       else if (DECL_CLASS_SCOPE_P (t)
11923                && uses_template_parms (DECL_CONTEXT (t)))
11924         {
11925           /* Template template argument like the following example need
11926              special treatment:
11927
11928                template <template <class> class TT> struct C {};
11929                template <class T> struct D {
11930                  template <class U> struct E {};
11931                  C<E> c;                                // #1
11932                };
11933                D<int> d;                                // #2
11934
11935              We are processing the template argument `E' in #1 for
11936              the template instantiation #2.  Originally, `E' is a
11937              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11938              have to substitute this with one having context `D<int>'.  */
11939
11940           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11941           return lookup_field (context, DECL_NAME(t), 0, false);
11942         }
11943       else
11944         /* Ordinary template template argument.  */
11945         return t;
11946
11947     case CAST_EXPR:
11948     case REINTERPRET_CAST_EXPR:
11949     case CONST_CAST_EXPR:
11950     case STATIC_CAST_EXPR:
11951     case DYNAMIC_CAST_EXPR:
11952     case IMPLICIT_CONV_EXPR:
11953     case CONVERT_EXPR:
11954     case NOP_EXPR:
11955       return build1
11956         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11957          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11958
11959     case SIZEOF_EXPR:
11960       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11961         {
11962
11963           tree expanded;
11964           int len = 0;
11965
11966           ++cp_unevaluated_operand;
11967           ++c_inhibit_evaluation_warnings;
11968           /* We only want to compute the number of arguments.  */
11969           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11970                                             complain, in_decl);
11971           --cp_unevaluated_operand;
11972           --c_inhibit_evaluation_warnings;
11973
11974           if (TREE_CODE (expanded) == TREE_VEC)
11975             len = TREE_VEC_LENGTH (expanded);
11976
11977           if (expanded == error_mark_node)
11978             return error_mark_node;
11979           else if (PACK_EXPANSION_P (expanded)
11980                    || (TREE_CODE (expanded) == TREE_VEC
11981                        && len > 0
11982                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11983             {
11984               if (TREE_CODE (expanded) == TREE_VEC)
11985                 expanded = TREE_VEC_ELT (expanded, len - 1);
11986
11987               if (TYPE_P (expanded))
11988                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11989                                                    complain & tf_error);
11990               else
11991                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11992                                                    complain & tf_error);
11993             }
11994           else
11995             return build_int_cst (size_type_node, len);
11996         }
11997       /* Fall through */
11998
11999     case INDIRECT_REF:
12000     case NEGATE_EXPR:
12001     case TRUTH_NOT_EXPR:
12002     case BIT_NOT_EXPR:
12003     case ADDR_EXPR:
12004     case UNARY_PLUS_EXPR:      /* Unary + */
12005     case ALIGNOF_EXPR:
12006     case AT_ENCODE_EXPR:
12007     case ARROW_EXPR:
12008     case THROW_EXPR:
12009     case TYPEID_EXPR:
12010     case REALPART_EXPR:
12011     case IMAGPART_EXPR:
12012       return build1
12013         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12014          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
12015
12016     case COMPONENT_REF:
12017       {
12018         tree object;
12019         tree name;
12020
12021         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
12022         name = TREE_OPERAND (t, 1);
12023         if (TREE_CODE (name) == BIT_NOT_EXPR)
12024           {
12025             name = tsubst_copy (TREE_OPERAND (name, 0), args,
12026                                 complain, in_decl);
12027             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12028           }
12029         else if (TREE_CODE (name) == SCOPE_REF
12030                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
12031           {
12032             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
12033                                      complain, in_decl);
12034             name = TREE_OPERAND (name, 1);
12035             name = tsubst_copy (TREE_OPERAND (name, 0), args,
12036                                 complain, in_decl);
12037             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12038             name = build_qualified_name (/*type=*/NULL_TREE,
12039                                          base, name,
12040                                          /*template_p=*/false);
12041           }
12042         else if (BASELINK_P (name))
12043           name = tsubst_baselink (name,
12044                                   non_reference (TREE_TYPE (object)),
12045                                   args, complain,
12046                                   in_decl);
12047         else
12048           name = tsubst_copy (name, args, complain, in_decl);
12049         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
12050       }
12051
12052     case PLUS_EXPR:
12053     case MINUS_EXPR:
12054     case MULT_EXPR:
12055     case TRUNC_DIV_EXPR:
12056     case CEIL_DIV_EXPR:
12057     case FLOOR_DIV_EXPR:
12058     case ROUND_DIV_EXPR:
12059     case EXACT_DIV_EXPR:
12060     case BIT_AND_EXPR:
12061     case BIT_IOR_EXPR:
12062     case BIT_XOR_EXPR:
12063     case TRUNC_MOD_EXPR:
12064     case FLOOR_MOD_EXPR:
12065     case TRUTH_ANDIF_EXPR:
12066     case TRUTH_ORIF_EXPR:
12067     case TRUTH_AND_EXPR:
12068     case TRUTH_OR_EXPR:
12069     case RSHIFT_EXPR:
12070     case LSHIFT_EXPR:
12071     case RROTATE_EXPR:
12072     case LROTATE_EXPR:
12073     case EQ_EXPR:
12074     case NE_EXPR:
12075     case MAX_EXPR:
12076     case MIN_EXPR:
12077     case LE_EXPR:
12078     case GE_EXPR:
12079     case LT_EXPR:
12080     case GT_EXPR:
12081     case COMPOUND_EXPR:
12082     case DOTSTAR_EXPR:
12083     case MEMBER_REF:
12084     case PREDECREMENT_EXPR:
12085     case PREINCREMENT_EXPR:
12086     case POSTDECREMENT_EXPR:
12087     case POSTINCREMENT_EXPR:
12088       return build_nt
12089         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12090          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12091
12092     case SCOPE_REF:
12093       return build_qualified_name (/*type=*/NULL_TREE,
12094                                    tsubst_copy (TREE_OPERAND (t, 0),
12095                                                 args, complain, in_decl),
12096                                    tsubst_copy (TREE_OPERAND (t, 1),
12097                                                 args, complain, in_decl),
12098                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12099
12100     case ARRAY_REF:
12101       return build_nt
12102         (ARRAY_REF,
12103          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12104          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12105          NULL_TREE, NULL_TREE);
12106
12107     case CALL_EXPR:
12108       {
12109         int n = VL_EXP_OPERAND_LENGTH (t);
12110         tree result = build_vl_exp (CALL_EXPR, n);
12111         int i;
12112         for (i = 0; i < n; i++)
12113           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12114                                              complain, in_decl);
12115         return result;
12116       }
12117
12118     case COND_EXPR:
12119     case MODOP_EXPR:
12120     case PSEUDO_DTOR_EXPR:
12121       {
12122         r = build_nt
12123           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12124            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12125            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12126         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12127         return r;
12128       }
12129
12130     case NEW_EXPR:
12131       {
12132         r = build_nt
12133         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12134          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12135          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12136         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12137         return r;
12138       }
12139
12140     case DELETE_EXPR:
12141       {
12142         r = build_nt
12143         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12144          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12145         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12146         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12147         return r;
12148       }
12149
12150     case TEMPLATE_ID_EXPR:
12151       {
12152         /* Substituted template arguments */
12153         tree fn = TREE_OPERAND (t, 0);
12154         tree targs = TREE_OPERAND (t, 1);
12155
12156         fn = tsubst_copy (fn, args, complain, in_decl);
12157         if (targs)
12158           targs = tsubst_template_args (targs, args, complain, in_decl);
12159
12160         return lookup_template_function (fn, targs);
12161       }
12162
12163     case TREE_LIST:
12164       {
12165         tree purpose, value, chain;
12166
12167         if (t == void_list_node)
12168           return t;
12169
12170         purpose = TREE_PURPOSE (t);
12171         if (purpose)
12172           purpose = tsubst_copy (purpose, args, complain, in_decl);
12173         value = TREE_VALUE (t);
12174         if (value)
12175           value = tsubst_copy (value, args, complain, in_decl);
12176         chain = TREE_CHAIN (t);
12177         if (chain && chain != void_type_node)
12178           chain = tsubst_copy (chain, args, complain, in_decl);
12179         if (purpose == TREE_PURPOSE (t)
12180             && value == TREE_VALUE (t)
12181             && chain == TREE_CHAIN (t))
12182           return t;
12183         return tree_cons (purpose, value, chain);
12184       }
12185
12186     case RECORD_TYPE:
12187     case UNION_TYPE:
12188     case ENUMERAL_TYPE:
12189     case INTEGER_TYPE:
12190     case TEMPLATE_TYPE_PARM:
12191     case TEMPLATE_TEMPLATE_PARM:
12192     case BOUND_TEMPLATE_TEMPLATE_PARM:
12193     case TEMPLATE_PARM_INDEX:
12194     case POINTER_TYPE:
12195     case REFERENCE_TYPE:
12196     case OFFSET_TYPE:
12197     case FUNCTION_TYPE:
12198     case METHOD_TYPE:
12199     case ARRAY_TYPE:
12200     case TYPENAME_TYPE:
12201     case UNBOUND_CLASS_TEMPLATE:
12202     case TYPEOF_TYPE:
12203     case DECLTYPE_TYPE:
12204     case TYPE_DECL:
12205       return tsubst (t, args, complain, in_decl);
12206
12207     case IDENTIFIER_NODE:
12208       if (IDENTIFIER_TYPENAME_P (t))
12209         {
12210           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12211           return mangle_conv_op_name_for_type (new_type);
12212         }
12213       else
12214         return t;
12215
12216     case CONSTRUCTOR:
12217       /* This is handled by tsubst_copy_and_build.  */
12218       gcc_unreachable ();
12219
12220     case VA_ARG_EXPR:
12221       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12222                                           in_decl),
12223                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12224
12225     case CLEANUP_POINT_EXPR:
12226       /* We shouldn't have built any of these during initial template
12227          generation.  Instead, they should be built during instantiation
12228          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12229       gcc_unreachable ();
12230
12231     case OFFSET_REF:
12232       r = build2
12233         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12234          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12235          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12236       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12237       mark_used (TREE_OPERAND (r, 1));
12238       return r;
12239
12240     case EXPR_PACK_EXPANSION:
12241       error ("invalid use of pack expansion expression");
12242       return error_mark_node;
12243
12244     case NONTYPE_ARGUMENT_PACK:
12245       error ("use %<...%> to expand argument pack");
12246       return error_mark_node;
12247
12248     case INTEGER_CST:
12249     case REAL_CST:
12250     case STRING_CST:
12251     case COMPLEX_CST:
12252       {
12253         /* Instantiate any typedefs in the type.  */
12254         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12255         r = fold_convert (type, t);
12256         gcc_assert (TREE_CODE (r) == code);
12257         return r;
12258       }
12259
12260     case PTRMEM_CST:
12261       /* These can sometimes show up in a partial instantiation, but never
12262          involve template parms.  */
12263       gcc_assert (!uses_template_parms (t));
12264       return t;
12265
12266     default:
12267       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12268       gcc_checking_assert (false);
12269       return t;
12270     }
12271 }
12272
12273 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12274
12275 static tree
12276 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12277                     tree in_decl)
12278 {
12279   tree new_clauses = NULL, nc, oc;
12280
12281   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12282     {
12283       nc = copy_node (oc);
12284       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12285       new_clauses = nc;
12286
12287       switch (OMP_CLAUSE_CODE (nc))
12288         {
12289         case OMP_CLAUSE_LASTPRIVATE:
12290           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12291             {
12292               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12293               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12294                            in_decl, /*integral_constant_expression_p=*/false);
12295               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12296                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12297             }
12298           /* FALLTHRU */
12299         case OMP_CLAUSE_PRIVATE:
12300         case OMP_CLAUSE_SHARED:
12301         case OMP_CLAUSE_FIRSTPRIVATE:
12302         case OMP_CLAUSE_REDUCTION:
12303         case OMP_CLAUSE_COPYIN:
12304         case OMP_CLAUSE_COPYPRIVATE:
12305         case OMP_CLAUSE_IF:
12306         case OMP_CLAUSE_NUM_THREADS:
12307         case OMP_CLAUSE_SCHEDULE:
12308         case OMP_CLAUSE_COLLAPSE:
12309         case OMP_CLAUSE_FINAL:
12310           OMP_CLAUSE_OPERAND (nc, 0)
12311             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12312                            in_decl, /*integral_constant_expression_p=*/false);
12313           break;
12314         case OMP_CLAUSE_NOWAIT:
12315         case OMP_CLAUSE_ORDERED:
12316         case OMP_CLAUSE_DEFAULT:
12317         case OMP_CLAUSE_UNTIED:
12318         case OMP_CLAUSE_MERGEABLE:
12319           break;
12320         default:
12321           gcc_unreachable ();
12322         }
12323     }
12324
12325   return finish_omp_clauses (nreverse (new_clauses));
12326 }
12327
12328 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12329
12330 static tree
12331 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12332                           tree in_decl)
12333 {
12334 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12335
12336   tree purpose, value, chain;
12337
12338   if (t == NULL)
12339     return t;
12340
12341   if (TREE_CODE (t) != TREE_LIST)
12342     return tsubst_copy_and_build (t, args, complain, in_decl,
12343                                   /*function_p=*/false,
12344                                   /*integral_constant_expression_p=*/false);
12345
12346   if (t == void_list_node)
12347     return t;
12348
12349   purpose = TREE_PURPOSE (t);
12350   if (purpose)
12351     purpose = RECUR (purpose);
12352   value = TREE_VALUE (t);
12353   if (value)
12354     {
12355       if (TREE_CODE (value) != LABEL_DECL)
12356         value = RECUR (value);
12357       else
12358         {
12359           value = lookup_label (DECL_NAME (value));
12360           gcc_assert (TREE_CODE (value) == LABEL_DECL);
12361           TREE_USED (value) = 1;
12362         }
12363     }
12364   chain = TREE_CHAIN (t);
12365   if (chain && chain != void_type_node)
12366     chain = RECUR (chain);
12367   return tree_cons (purpose, value, chain);
12368 #undef RECUR
12369 }
12370
12371 /* Substitute one OMP_FOR iterator.  */
12372
12373 static void
12374 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12375                          tree condv, tree incrv, tree *clauses,
12376                          tree args, tsubst_flags_t complain, tree in_decl,
12377                          bool integral_constant_expression_p)
12378 {
12379 #define RECUR(NODE)                             \
12380   tsubst_expr ((NODE), args, complain, in_decl, \
12381                integral_constant_expression_p)
12382   tree decl, init, cond, incr, auto_node;
12383
12384   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12385   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12386   decl = RECUR (TREE_OPERAND (init, 0));
12387   init = TREE_OPERAND (init, 1);
12388   auto_node = type_uses_auto (TREE_TYPE (decl));
12389   if (auto_node && init)
12390     {
12391       tree init_expr = init;
12392       if (TREE_CODE (init_expr) == DECL_EXPR)
12393         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12394       init_expr = RECUR (init_expr);
12395       TREE_TYPE (decl)
12396         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12397     }
12398   gcc_assert (!type_dependent_expression_p (decl));
12399
12400   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12401     {
12402       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12403       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12404       if (TREE_CODE (incr) == MODIFY_EXPR)
12405         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12406                                     RECUR (TREE_OPERAND (incr, 1)),
12407                                     complain);
12408       else
12409         incr = RECUR (incr);
12410       TREE_VEC_ELT (declv, i) = decl;
12411       TREE_VEC_ELT (initv, i) = init;
12412       TREE_VEC_ELT (condv, i) = cond;
12413       TREE_VEC_ELT (incrv, i) = incr;
12414       return;
12415     }
12416
12417   if (init && TREE_CODE (init) != DECL_EXPR)
12418     {
12419       tree c;
12420       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12421         {
12422           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12423                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12424               && OMP_CLAUSE_DECL (c) == decl)
12425             break;
12426           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12427                    && OMP_CLAUSE_DECL (c) == decl)
12428             error ("iteration variable %qD should not be firstprivate", decl);
12429           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12430                    && OMP_CLAUSE_DECL (c) == decl)
12431             error ("iteration variable %qD should not be reduction", decl);
12432         }
12433       if (c == NULL)
12434         {
12435           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12436           OMP_CLAUSE_DECL (c) = decl;
12437           c = finish_omp_clauses (c);
12438           if (c)
12439             {
12440               OMP_CLAUSE_CHAIN (c) = *clauses;
12441               *clauses = c;
12442             }
12443         }
12444     }
12445   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12446   if (COMPARISON_CLASS_P (cond))
12447     cond = build2 (TREE_CODE (cond), boolean_type_node,
12448                    RECUR (TREE_OPERAND (cond, 0)),
12449                    RECUR (TREE_OPERAND (cond, 1)));
12450   else
12451     cond = RECUR (cond);
12452   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12453   switch (TREE_CODE (incr))
12454     {
12455     case PREINCREMENT_EXPR:
12456     case PREDECREMENT_EXPR:
12457     case POSTINCREMENT_EXPR:
12458     case POSTDECREMENT_EXPR:
12459       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12460                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12461       break;
12462     case MODIFY_EXPR:
12463       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12464           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12465         {
12466           tree rhs = TREE_OPERAND (incr, 1);
12467           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12468                          RECUR (TREE_OPERAND (incr, 0)),
12469                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12470                                  RECUR (TREE_OPERAND (rhs, 0)),
12471                                  RECUR (TREE_OPERAND (rhs, 1))));
12472         }
12473       else
12474         incr = RECUR (incr);
12475       break;
12476     case MODOP_EXPR:
12477       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12478           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12479         {
12480           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12481           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12482                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12483                                  TREE_TYPE (decl), lhs,
12484                                  RECUR (TREE_OPERAND (incr, 2))));
12485         }
12486       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12487                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12488                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12489         {
12490           tree rhs = TREE_OPERAND (incr, 2);
12491           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12492                          RECUR (TREE_OPERAND (incr, 0)),
12493                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12494                                  RECUR (TREE_OPERAND (rhs, 0)),
12495                                  RECUR (TREE_OPERAND (rhs, 1))));
12496         }
12497       else
12498         incr = RECUR (incr);
12499       break;
12500     default:
12501       incr = RECUR (incr);
12502       break;
12503     }
12504
12505   TREE_VEC_ELT (declv, i) = decl;
12506   TREE_VEC_ELT (initv, i) = init;
12507   TREE_VEC_ELT (condv, i) = cond;
12508   TREE_VEC_ELT (incrv, i) = incr;
12509 #undef RECUR
12510 }
12511
12512 /* Like tsubst_copy for expressions, etc. but also does semantic
12513    processing.  */
12514
12515 static tree
12516 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12517              bool integral_constant_expression_p)
12518 {
12519 #define RECUR(NODE)                             \
12520   tsubst_expr ((NODE), args, complain, in_decl, \
12521                integral_constant_expression_p)
12522
12523   tree stmt, tmp;
12524
12525   if (t == NULL_TREE || t == error_mark_node)
12526     return t;
12527
12528   if (EXPR_HAS_LOCATION (t))
12529     input_location = EXPR_LOCATION (t);
12530   if (STATEMENT_CODE_P (TREE_CODE (t)))
12531     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12532
12533   switch (TREE_CODE (t))
12534     {
12535     case STATEMENT_LIST:
12536       {
12537         tree_stmt_iterator i;
12538         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12539           RECUR (tsi_stmt (i));
12540         break;
12541       }
12542
12543     case CTOR_INITIALIZER:
12544       finish_mem_initializers (tsubst_initializer_list
12545                                (TREE_OPERAND (t, 0), args));
12546       break;
12547
12548     case RETURN_EXPR:
12549       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12550       break;
12551
12552     case EXPR_STMT:
12553       tmp = RECUR (EXPR_STMT_EXPR (t));
12554       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12555         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12556       else
12557         finish_expr_stmt (tmp);
12558       break;
12559
12560     case USING_STMT:
12561       do_using_directive (USING_STMT_NAMESPACE (t));
12562       break;
12563
12564     case DECL_EXPR:
12565       {
12566         tree decl, pattern_decl;
12567         tree init;
12568
12569         pattern_decl = decl = DECL_EXPR_DECL (t);
12570         if (TREE_CODE (decl) == LABEL_DECL)
12571           finish_label_decl (DECL_NAME (decl));
12572         else if (TREE_CODE (decl) == USING_DECL)
12573           {
12574             tree scope = USING_DECL_SCOPE (decl);
12575             tree name = DECL_NAME (decl);
12576             tree decl;
12577
12578             scope = tsubst (scope, args, complain, in_decl);
12579             decl = lookup_qualified_name (scope, name,
12580                                           /*is_type_p=*/false,
12581                                           /*complain=*/false);
12582             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12583               qualified_name_lookup_error (scope, name, decl, input_location);
12584             else
12585               do_local_using_decl (decl, scope, name);
12586           }
12587         else
12588           {
12589             init = DECL_INITIAL (decl);
12590             decl = tsubst (decl, args, complain, in_decl);
12591             if (decl != error_mark_node)
12592               {
12593                 /* By marking the declaration as instantiated, we avoid
12594                    trying to instantiate it.  Since instantiate_decl can't
12595                    handle local variables, and since we've already done
12596                    all that needs to be done, that's the right thing to
12597                    do.  */
12598                 if (TREE_CODE (decl) == VAR_DECL)
12599                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12600                 if (TREE_CODE (decl) == VAR_DECL
12601                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12602                   /* Anonymous aggregates are a special case.  */
12603                   finish_anon_union (decl);
12604                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
12605                   {
12606                     DECL_CONTEXT (decl) = current_function_decl;
12607                     insert_capture_proxy (decl);
12608                   }
12609                 else
12610                   {
12611                     int const_init = false;
12612                     maybe_push_decl (decl);
12613                     if (TREE_CODE (decl) == VAR_DECL
12614                         && DECL_PRETTY_FUNCTION_P (decl))
12615                       {
12616                         /* For __PRETTY_FUNCTION__ we have to adjust the
12617                            initializer.  */
12618                         const char *const name
12619                           = cxx_printable_name (current_function_decl, 2);
12620                         init = cp_fname_init (name, &TREE_TYPE (decl));
12621                       }
12622                     else
12623                       {
12624                         tree t = RECUR (init);
12625
12626                         if (init && !t)
12627                           {
12628                             /* If we had an initializer but it
12629                                instantiated to nothing,
12630                                value-initialize the object.  This will
12631                                only occur when the initializer was a
12632                                pack expansion where the parameter packs
12633                                used in that expansion were of length
12634                                zero.  */
12635                             init = build_value_init (TREE_TYPE (decl),
12636                                                      complain);
12637                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12638                               init = get_target_expr_sfinae (init, complain);
12639                           }
12640                         else
12641                           init = t;
12642                       }
12643
12644                     if (TREE_CODE (decl) == VAR_DECL)
12645                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12646                                     (pattern_decl));
12647                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12648                   }
12649               }
12650           }
12651
12652         /* A DECL_EXPR can also be used as an expression, in the condition
12653            clause of an if/for/while construct.  */
12654         return decl;
12655       }
12656
12657     case FOR_STMT:
12658       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12659       RECUR (FOR_INIT_STMT (t));
12660       finish_for_init_stmt (stmt);
12661       tmp = RECUR (FOR_COND (t));
12662       finish_for_cond (tmp, stmt);
12663       tmp = RECUR (FOR_EXPR (t));
12664       finish_for_expr (tmp, stmt);
12665       RECUR (FOR_BODY (t));
12666       finish_for_stmt (stmt);
12667       break;
12668
12669     case RANGE_FOR_STMT:
12670       {
12671         tree decl, expr;
12672         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12673         decl = RANGE_FOR_DECL (t);
12674         decl = tsubst (decl, args, complain, in_decl);
12675         maybe_push_decl (decl);
12676         expr = RECUR (RANGE_FOR_EXPR (t));
12677         stmt = cp_convert_range_for (stmt, decl, expr);
12678         RECUR (RANGE_FOR_BODY (t));
12679         finish_for_stmt (stmt);
12680       }
12681       break;
12682
12683     case WHILE_STMT:
12684       stmt = begin_while_stmt ();
12685       tmp = RECUR (WHILE_COND (t));
12686       finish_while_stmt_cond (tmp, stmt);
12687       RECUR (WHILE_BODY (t));
12688       finish_while_stmt (stmt);
12689       break;
12690
12691     case DO_STMT:
12692       stmt = begin_do_stmt ();
12693       RECUR (DO_BODY (t));
12694       finish_do_body (stmt);
12695       tmp = RECUR (DO_COND (t));
12696       finish_do_stmt (tmp, stmt);
12697       break;
12698
12699     case IF_STMT:
12700       stmt = begin_if_stmt ();
12701       tmp = RECUR (IF_COND (t));
12702       finish_if_stmt_cond (tmp, stmt);
12703       RECUR (THEN_CLAUSE (t));
12704       finish_then_clause (stmt);
12705
12706       if (ELSE_CLAUSE (t))
12707         {
12708           begin_else_clause (stmt);
12709           RECUR (ELSE_CLAUSE (t));
12710           finish_else_clause (stmt);
12711         }
12712
12713       finish_if_stmt (stmt);
12714       break;
12715
12716     case BIND_EXPR:
12717       if (BIND_EXPR_BODY_BLOCK (t))
12718         stmt = begin_function_body ();
12719       else
12720         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12721                                     ? BCS_TRY_BLOCK : 0);
12722
12723       RECUR (BIND_EXPR_BODY (t));
12724
12725       if (BIND_EXPR_BODY_BLOCK (t))
12726         finish_function_body (stmt);
12727       else
12728         finish_compound_stmt (stmt);
12729       break;
12730
12731     case BREAK_STMT:
12732       finish_break_stmt ();
12733       break;
12734
12735     case CONTINUE_STMT:
12736       finish_continue_stmt ();
12737       break;
12738
12739     case SWITCH_STMT:
12740       stmt = begin_switch_stmt ();
12741       tmp = RECUR (SWITCH_STMT_COND (t));
12742       finish_switch_cond (tmp, stmt);
12743       RECUR (SWITCH_STMT_BODY (t));
12744       finish_switch_stmt (stmt);
12745       break;
12746
12747     case CASE_LABEL_EXPR:
12748       finish_case_label (EXPR_LOCATION (t),
12749                          RECUR (CASE_LOW (t)),
12750                          RECUR (CASE_HIGH (t)));
12751       break;
12752
12753     case LABEL_EXPR:
12754       {
12755         tree decl = LABEL_EXPR_LABEL (t);
12756         tree label;
12757
12758         label = finish_label_stmt (DECL_NAME (decl));
12759         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12760           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12761       }
12762       break;
12763
12764     case GOTO_EXPR:
12765       tmp = GOTO_DESTINATION (t);
12766       if (TREE_CODE (tmp) != LABEL_DECL)
12767         /* Computed goto's must be tsubst'd into.  On the other hand,
12768            non-computed gotos must not be; the identifier in question
12769            will have no binding.  */
12770         tmp = RECUR (tmp);
12771       else
12772         tmp = DECL_NAME (tmp);
12773       finish_goto_stmt (tmp);
12774       break;
12775
12776     case ASM_EXPR:
12777       tmp = finish_asm_stmt
12778         (ASM_VOLATILE_P (t),
12779          RECUR (ASM_STRING (t)),
12780          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12781          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12782          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12783          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12784       {
12785         tree asm_expr = tmp;
12786         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12787           asm_expr = TREE_OPERAND (asm_expr, 0);
12788         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12789       }
12790       break;
12791
12792     case TRY_BLOCK:
12793       if (CLEANUP_P (t))
12794         {
12795           stmt = begin_try_block ();
12796           RECUR (TRY_STMTS (t));
12797           finish_cleanup_try_block (stmt);
12798           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12799         }
12800       else
12801         {
12802           tree compound_stmt = NULL_TREE;
12803
12804           if (FN_TRY_BLOCK_P (t))
12805             stmt = begin_function_try_block (&compound_stmt);
12806           else
12807             stmt = begin_try_block ();
12808
12809           RECUR (TRY_STMTS (t));
12810
12811           if (FN_TRY_BLOCK_P (t))
12812             finish_function_try_block (stmt);
12813           else
12814             finish_try_block (stmt);
12815
12816           RECUR (TRY_HANDLERS (t));
12817           if (FN_TRY_BLOCK_P (t))
12818             finish_function_handler_sequence (stmt, compound_stmt);
12819           else
12820             finish_handler_sequence (stmt);
12821         }
12822       break;
12823
12824     case HANDLER:
12825       {
12826         tree decl = HANDLER_PARMS (t);
12827
12828         if (decl)
12829           {
12830             decl = tsubst (decl, args, complain, in_decl);
12831             /* Prevent instantiate_decl from trying to instantiate
12832                this variable.  We've already done all that needs to be
12833                done.  */
12834             if (decl != error_mark_node)
12835               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12836           }
12837         stmt = begin_handler ();
12838         finish_handler_parms (decl, stmt);
12839         RECUR (HANDLER_BODY (t));
12840         finish_handler (stmt);
12841       }
12842       break;
12843
12844     case TAG_DEFN:
12845       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12846       break;
12847
12848     case STATIC_ASSERT:
12849       {
12850         tree condition = 
12851           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12852                        args,
12853                        complain, in_decl,
12854                        /*integral_constant_expression_p=*/true);
12855         finish_static_assert (condition,
12856                               STATIC_ASSERT_MESSAGE (t),
12857                               STATIC_ASSERT_SOURCE_LOCATION (t),
12858                               /*member_p=*/false);
12859       }
12860       break;
12861
12862     case OMP_PARALLEL:
12863       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12864                                 args, complain, in_decl);
12865       stmt = begin_omp_parallel ();
12866       RECUR (OMP_PARALLEL_BODY (t));
12867       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12868         = OMP_PARALLEL_COMBINED (t);
12869       break;
12870
12871     case OMP_TASK:
12872       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12873                                 args, complain, in_decl);
12874       stmt = begin_omp_task ();
12875       RECUR (OMP_TASK_BODY (t));
12876       finish_omp_task (tmp, stmt);
12877       break;
12878
12879     case OMP_FOR:
12880       {
12881         tree clauses, body, pre_body;
12882         tree declv, initv, condv, incrv;
12883         int i;
12884
12885         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12886                                       args, complain, in_decl);
12887         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12888         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12889         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12890         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12891
12892         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12893           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12894                                    &clauses, args, complain, in_decl,
12895                                    integral_constant_expression_p);
12896
12897         stmt = begin_omp_structured_block ();
12898
12899         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12900           if (TREE_VEC_ELT (initv, i) == NULL
12901               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12902             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12903           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12904             {
12905               tree init = RECUR (TREE_VEC_ELT (initv, i));
12906               gcc_assert (init == TREE_VEC_ELT (declv, i));
12907               TREE_VEC_ELT (initv, i) = NULL_TREE;
12908             }
12909           else
12910             {
12911               tree decl_expr = TREE_VEC_ELT (initv, i);
12912               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12913               gcc_assert (init != NULL);
12914               TREE_VEC_ELT (initv, i) = RECUR (init);
12915               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12916               RECUR (decl_expr);
12917               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12918             }
12919
12920         pre_body = push_stmt_list ();
12921         RECUR (OMP_FOR_PRE_BODY (t));
12922         pre_body = pop_stmt_list (pre_body);
12923
12924         body = push_stmt_list ();
12925         RECUR (OMP_FOR_BODY (t));
12926         body = pop_stmt_list (body);
12927
12928         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12929                             body, pre_body, clauses);
12930
12931         add_stmt (finish_omp_structured_block (stmt));
12932       }
12933       break;
12934
12935     case OMP_SECTIONS:
12936     case OMP_SINGLE:
12937       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12938       stmt = push_stmt_list ();
12939       RECUR (OMP_BODY (t));
12940       stmt = pop_stmt_list (stmt);
12941
12942       t = copy_node (t);
12943       OMP_BODY (t) = stmt;
12944       OMP_CLAUSES (t) = tmp;
12945       add_stmt (t);
12946       break;
12947
12948     case OMP_SECTION:
12949     case OMP_CRITICAL:
12950     case OMP_MASTER:
12951     case OMP_ORDERED:
12952       stmt = push_stmt_list ();
12953       RECUR (OMP_BODY (t));
12954       stmt = pop_stmt_list (stmt);
12955
12956       t = copy_node (t);
12957       OMP_BODY (t) = stmt;
12958       add_stmt (t);
12959       break;
12960
12961     case OMP_ATOMIC:
12962       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12963       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12964         {
12965           tree op1 = TREE_OPERAND (t, 1);
12966           tree rhs1 = NULL_TREE;
12967           tree lhs, rhs;
12968           if (TREE_CODE (op1) == COMPOUND_EXPR)
12969             {
12970               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12971               op1 = TREE_OPERAND (op1, 1);
12972             }
12973           lhs = RECUR (TREE_OPERAND (op1, 0));
12974           rhs = RECUR (TREE_OPERAND (op1, 1));
12975           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12976                              NULL_TREE, NULL_TREE, rhs1);
12977         }
12978       else
12979         {
12980           tree op1 = TREE_OPERAND (t, 1);
12981           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12982           tree rhs1 = NULL_TREE;
12983           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
12984           enum tree_code opcode = NOP_EXPR;
12985           if (code == OMP_ATOMIC_READ)
12986             {
12987               v = RECUR (TREE_OPERAND (op1, 0));
12988               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12989             }
12990           else if (code == OMP_ATOMIC_CAPTURE_OLD
12991                    || code == OMP_ATOMIC_CAPTURE_NEW)
12992             {
12993               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
12994               v = RECUR (TREE_OPERAND (op1, 0));
12995               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
12996               if (TREE_CODE (op11) == COMPOUND_EXPR)
12997                 {
12998                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
12999                   op11 = TREE_OPERAND (op11, 1);
13000                 }
13001               lhs = RECUR (TREE_OPERAND (op11, 0));
13002               rhs = RECUR (TREE_OPERAND (op11, 1));
13003               opcode = TREE_CODE (op11);
13004             }
13005           else
13006             {
13007               code = OMP_ATOMIC;
13008               lhs = RECUR (TREE_OPERAND (op1, 0));
13009               rhs = RECUR (TREE_OPERAND (op1, 1));
13010             }
13011           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
13012         }
13013       break;
13014
13015     case TRANSACTION_EXPR:
13016       {
13017         int flags = 0;
13018         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
13019         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
13020
13021         if (TRANSACTION_EXPR_IS_STMT (t))
13022           {
13023             tree body = TRANSACTION_EXPR_BODY (t);
13024             tree noex = NULL_TREE;
13025             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
13026               {
13027                 noex = MUST_NOT_THROW_COND (body);
13028                 if (noex == NULL_TREE)
13029                   noex = boolean_true_node;
13030                 body = TREE_OPERAND (body, 0);
13031               }
13032             stmt = begin_transaction_stmt (input_location, NULL, flags);
13033             RECUR (body);
13034             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
13035           }
13036         else
13037           {
13038             stmt = build_transaction_expr (EXPR_LOCATION (t),
13039                                            RECUR (TRANSACTION_EXPR_BODY (t)),
13040                                            flags, NULL_TREE);
13041             return stmt;
13042           }
13043       }
13044       break;
13045
13046     case MUST_NOT_THROW_EXPR:
13047       return build_must_not_throw_expr (RECUR (TREE_OPERAND (t, 0)),
13048                                         RECUR (MUST_NOT_THROW_COND (t)));
13049
13050     case EXPR_PACK_EXPANSION:
13051       error ("invalid use of pack expansion expression");
13052       return error_mark_node;
13053
13054     case NONTYPE_ARGUMENT_PACK:
13055       error ("use %<...%> to expand argument pack");
13056       return error_mark_node;
13057
13058     default:
13059       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
13060
13061       return tsubst_copy_and_build (t, args, complain, in_decl,
13062                                     /*function_p=*/false,
13063                                     integral_constant_expression_p);
13064     }
13065
13066   return NULL_TREE;
13067 #undef RECUR
13068 }
13069
13070 /* T is a postfix-expression that is not being used in a function
13071    call.  Return the substituted version of T.  */
13072
13073 static tree
13074 tsubst_non_call_postfix_expression (tree t, tree args,
13075                                     tsubst_flags_t complain,
13076                                     tree in_decl)
13077 {
13078   if (TREE_CODE (t) == SCOPE_REF)
13079     t = tsubst_qualified_id (t, args, complain, in_decl,
13080                              /*done=*/false, /*address_p=*/false);
13081   else
13082     t = tsubst_copy_and_build (t, args, complain, in_decl,
13083                                /*function_p=*/false,
13084                                /*integral_constant_expression_p=*/false);
13085
13086   return t;
13087 }
13088
13089 /* Like tsubst but deals with expressions and performs semantic
13090    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
13091
13092 tree
13093 tsubst_copy_and_build (tree t,
13094                        tree args,
13095                        tsubst_flags_t complain,
13096                        tree in_decl,
13097                        bool function_p,
13098                        bool integral_constant_expression_p)
13099 {
13100 #define RECUR(NODE)                                             \
13101   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
13102                          /*function_p=*/false,                  \
13103                          integral_constant_expression_p)
13104
13105   tree op1;
13106
13107   if (t == NULL_TREE || t == error_mark_node)
13108     return t;
13109
13110   switch (TREE_CODE (t))
13111     {
13112     case USING_DECL:
13113       t = DECL_NAME (t);
13114       /* Fall through.  */
13115     case IDENTIFIER_NODE:
13116       {
13117         tree decl;
13118         cp_id_kind idk;
13119         bool non_integral_constant_expression_p;
13120         const char *error_msg;
13121
13122         if (IDENTIFIER_TYPENAME_P (t))
13123           {
13124             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13125             t = mangle_conv_op_name_for_type (new_type);
13126           }
13127
13128         /* Look up the name.  */
13129         decl = lookup_name (t);
13130
13131         /* By convention, expressions use ERROR_MARK_NODE to indicate
13132            failure, not NULL_TREE.  */
13133         if (decl == NULL_TREE)
13134           decl = error_mark_node;
13135
13136         decl = finish_id_expression (t, decl, NULL_TREE,
13137                                      &idk,
13138                                      integral_constant_expression_p,
13139           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx0x),
13140                                      &non_integral_constant_expression_p,
13141                                      /*template_p=*/false,
13142                                      /*done=*/true,
13143                                      /*address_p=*/false,
13144                                      /*template_arg_p=*/false,
13145                                      &error_msg,
13146                                      input_location);
13147         if (error_msg)
13148           error (error_msg);
13149         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13150           {
13151             if (complain & tf_error)
13152               unqualified_name_lookup_error (decl);
13153             decl = error_mark_node;
13154           }
13155         return decl;
13156       }
13157
13158     case TEMPLATE_ID_EXPR:
13159       {
13160         tree object;
13161         tree templ = RECUR (TREE_OPERAND (t, 0));
13162         tree targs = TREE_OPERAND (t, 1);
13163
13164         if (targs)
13165           targs = tsubst_template_args (targs, args, complain, in_decl);
13166
13167         if (TREE_CODE (templ) == COMPONENT_REF)
13168           {
13169             object = TREE_OPERAND (templ, 0);
13170             templ = TREE_OPERAND (templ, 1);
13171           }
13172         else
13173           object = NULL_TREE;
13174         templ = lookup_template_function (templ, targs);
13175
13176         if (object)
13177           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13178                          object, templ, NULL_TREE);
13179         else
13180           return baselink_for_fns (templ);
13181       }
13182
13183     case INDIRECT_REF:
13184       {
13185         tree r = RECUR (TREE_OPERAND (t, 0));
13186
13187         if (REFERENCE_REF_P (t))
13188           {
13189             /* A type conversion to reference type will be enclosed in
13190                such an indirect ref, but the substitution of the cast
13191                will have also added such an indirect ref.  */
13192             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13193               r = convert_from_reference (r);
13194           }
13195         else
13196           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13197         return r;
13198       }
13199
13200     case NOP_EXPR:
13201       return build_nop
13202         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13203          RECUR (TREE_OPERAND (t, 0)));
13204
13205     case IMPLICIT_CONV_EXPR:
13206       {
13207         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13208         tree expr = RECUR (TREE_OPERAND (t, 0));
13209         int flags = LOOKUP_IMPLICIT;
13210         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13211           flags = LOOKUP_NORMAL;
13212         return perform_implicit_conversion_flags (type, expr, complain,
13213                                                   flags);
13214       }
13215
13216     case CONVERT_EXPR:
13217       return build1
13218         (CONVERT_EXPR,
13219          tsubst (TREE_TYPE (t), args, complain, in_decl),
13220          RECUR (TREE_OPERAND (t, 0)));
13221
13222     case CAST_EXPR:
13223     case REINTERPRET_CAST_EXPR:
13224     case CONST_CAST_EXPR:
13225     case DYNAMIC_CAST_EXPR:
13226     case STATIC_CAST_EXPR:
13227       {
13228         tree type;
13229         tree op;
13230
13231         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13232         if (integral_constant_expression_p
13233             && !cast_valid_in_integral_constant_expression_p (type))
13234           {
13235             if (complain & tf_error)
13236               error ("a cast to a type other than an integral or "
13237                      "enumeration type cannot appear in a constant-expression");
13238             return error_mark_node; 
13239           }
13240
13241         op = RECUR (TREE_OPERAND (t, 0));
13242
13243         switch (TREE_CODE (t))
13244           {
13245           case CAST_EXPR:
13246             return build_functional_cast (type, op, complain);
13247           case REINTERPRET_CAST_EXPR:
13248             return build_reinterpret_cast (type, op, complain);
13249           case CONST_CAST_EXPR:
13250             return build_const_cast (type, op, complain);
13251           case DYNAMIC_CAST_EXPR:
13252             return build_dynamic_cast (type, op, complain);
13253           case STATIC_CAST_EXPR:
13254             return build_static_cast (type, op, complain);
13255           default:
13256             gcc_unreachable ();
13257           }
13258       }
13259
13260     case POSTDECREMENT_EXPR:
13261     case POSTINCREMENT_EXPR:
13262       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13263                                                 args, complain, in_decl);
13264       return build_x_unary_op (TREE_CODE (t), op1, complain);
13265
13266     case PREDECREMENT_EXPR:
13267     case PREINCREMENT_EXPR:
13268     case NEGATE_EXPR:
13269     case BIT_NOT_EXPR:
13270     case ABS_EXPR:
13271     case TRUTH_NOT_EXPR:
13272     case UNARY_PLUS_EXPR:  /* Unary + */
13273     case REALPART_EXPR:
13274     case IMAGPART_EXPR:
13275       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13276                                complain);
13277
13278     case FIX_TRUNC_EXPR:
13279       return cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
13280                                 0, complain);
13281
13282     case ADDR_EXPR:
13283       op1 = TREE_OPERAND (t, 0);
13284       if (TREE_CODE (op1) == LABEL_DECL)
13285         return finish_label_address_expr (DECL_NAME (op1),
13286                                           EXPR_LOCATION (op1));
13287       if (TREE_CODE (op1) == SCOPE_REF)
13288         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13289                                    /*done=*/true, /*address_p=*/true);
13290       else
13291         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13292                                                   in_decl);
13293       return build_x_unary_op (ADDR_EXPR, op1, complain);
13294
13295     case PLUS_EXPR:
13296     case MINUS_EXPR:
13297     case MULT_EXPR:
13298     case TRUNC_DIV_EXPR:
13299     case CEIL_DIV_EXPR:
13300     case FLOOR_DIV_EXPR:
13301     case ROUND_DIV_EXPR:
13302     case EXACT_DIV_EXPR:
13303     case BIT_AND_EXPR:
13304     case BIT_IOR_EXPR:
13305     case BIT_XOR_EXPR:
13306     case TRUNC_MOD_EXPR:
13307     case FLOOR_MOD_EXPR:
13308     case TRUTH_ANDIF_EXPR:
13309     case TRUTH_ORIF_EXPR:
13310     case TRUTH_AND_EXPR:
13311     case TRUTH_OR_EXPR:
13312     case RSHIFT_EXPR:
13313     case LSHIFT_EXPR:
13314     case RROTATE_EXPR:
13315     case LROTATE_EXPR:
13316     case EQ_EXPR:
13317     case NE_EXPR:
13318     case MAX_EXPR:
13319     case MIN_EXPR:
13320     case LE_EXPR:
13321     case GE_EXPR:
13322     case LT_EXPR:
13323     case GT_EXPR:
13324     case MEMBER_REF:
13325     case DOTSTAR_EXPR:
13326       {
13327         tree r = build_x_binary_op
13328           (TREE_CODE (t),
13329            RECUR (TREE_OPERAND (t, 0)),
13330            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13331             ? ERROR_MARK
13332             : TREE_CODE (TREE_OPERAND (t, 0))),
13333            RECUR (TREE_OPERAND (t, 1)),
13334            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13335             ? ERROR_MARK
13336             : TREE_CODE (TREE_OPERAND (t, 1))),
13337            /*overload=*/NULL,
13338            complain);
13339         if (EXPR_P (r) && TREE_NO_WARNING (t))
13340           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13341         return r;
13342       }
13343
13344     case SCOPE_REF:
13345       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13346                                   /*address_p=*/false);
13347     case ARRAY_REF:
13348       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13349                                                 args, complain, in_decl);
13350       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13351
13352     case SIZEOF_EXPR:
13353       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13354         return tsubst_copy (t, args, complain, in_decl);
13355       /* Fall through */
13356       
13357     case ALIGNOF_EXPR:
13358       op1 = TREE_OPERAND (t, 0);
13359       if (!args)
13360         {
13361           /* When there are no ARGS, we are trying to evaluate a
13362              non-dependent expression from the parser.  Trying to do
13363              the substitutions may not work.  */
13364           if (!TYPE_P (op1))
13365             op1 = TREE_TYPE (op1);
13366         }
13367       else
13368         {
13369           ++cp_unevaluated_operand;
13370           ++c_inhibit_evaluation_warnings;
13371           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13372                                        /*function_p=*/false,
13373                                        /*integral_constant_expression_p=*/false);
13374           --cp_unevaluated_operand;
13375           --c_inhibit_evaluation_warnings;
13376         }
13377       if (TYPE_P (op1))
13378         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13379                                            complain & tf_error);
13380       else
13381         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13382                                            complain & tf_error);
13383
13384     case AT_ENCODE_EXPR:
13385       {
13386         op1 = TREE_OPERAND (t, 0);
13387         ++cp_unevaluated_operand;
13388         ++c_inhibit_evaluation_warnings;
13389         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13390                                      /*function_p=*/false,
13391                                      /*integral_constant_expression_p=*/false);
13392         --cp_unevaluated_operand;
13393         --c_inhibit_evaluation_warnings;
13394         return objc_build_encode_expr (op1);
13395       }
13396
13397     case NOEXCEPT_EXPR:
13398       op1 = TREE_OPERAND (t, 0);
13399       ++cp_unevaluated_operand;
13400       ++c_inhibit_evaluation_warnings;
13401       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13402                                    /*function_p=*/false,
13403                                    /*integral_constant_expression_p=*/false);
13404       --cp_unevaluated_operand;
13405       --c_inhibit_evaluation_warnings;
13406       return finish_noexcept_expr (op1, complain);
13407
13408     case MODOP_EXPR:
13409       {
13410         tree r = build_x_modify_expr
13411           (RECUR (TREE_OPERAND (t, 0)),
13412            TREE_CODE (TREE_OPERAND (t, 1)),
13413            RECUR (TREE_OPERAND (t, 2)),
13414            complain);
13415         /* TREE_NO_WARNING must be set if either the expression was
13416            parenthesized or it uses an operator such as >>= rather
13417            than plain assignment.  In the former case, it was already
13418            set and must be copied.  In the latter case,
13419            build_x_modify_expr sets it and it must not be reset
13420            here.  */
13421         if (TREE_NO_WARNING (t))
13422           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13423         return r;
13424       }
13425
13426     case ARROW_EXPR:
13427       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13428                                                 args, complain, in_decl);
13429       /* Remember that there was a reference to this entity.  */
13430       if (DECL_P (op1))
13431         mark_used (op1);
13432       return build_x_arrow (op1);
13433
13434     case NEW_EXPR:
13435       {
13436         tree placement = RECUR (TREE_OPERAND (t, 0));
13437         tree init = RECUR (TREE_OPERAND (t, 3));
13438         VEC(tree,gc) *placement_vec;
13439         VEC(tree,gc) *init_vec;
13440         tree ret;
13441
13442         if (placement == NULL_TREE)
13443           placement_vec = NULL;
13444         else
13445           {
13446             placement_vec = make_tree_vector ();
13447             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13448               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13449           }
13450
13451         /* If there was an initializer in the original tree, but it
13452            instantiated to an empty list, then we should pass a
13453            non-NULL empty vector to tell build_new that it was an
13454            empty initializer() rather than no initializer.  This can
13455            only happen when the initializer is a pack expansion whose
13456            parameter packs are of length zero.  */
13457         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13458           init_vec = NULL;
13459         else
13460           {
13461             init_vec = make_tree_vector ();
13462             if (init == void_zero_node)
13463               gcc_assert (init_vec != NULL);
13464             else
13465               {
13466                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13467                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13468               }
13469           }
13470
13471         ret = build_new (&placement_vec,
13472                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13473                          RECUR (TREE_OPERAND (t, 2)),
13474                          &init_vec,
13475                          NEW_EXPR_USE_GLOBAL (t),
13476                          complain);
13477
13478         if (placement_vec != NULL)
13479           release_tree_vector (placement_vec);
13480         if (init_vec != NULL)
13481           release_tree_vector (init_vec);
13482
13483         return ret;
13484       }
13485
13486     case DELETE_EXPR:
13487      return delete_sanity
13488        (RECUR (TREE_OPERAND (t, 0)),
13489         RECUR (TREE_OPERAND (t, 1)),
13490         DELETE_EXPR_USE_VEC (t),
13491         DELETE_EXPR_USE_GLOBAL (t),
13492         complain);
13493
13494     case COMPOUND_EXPR:
13495       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13496                                     RECUR (TREE_OPERAND (t, 1)),
13497                                     complain);
13498
13499     case CALL_EXPR:
13500       {
13501         tree function;
13502         VEC(tree,gc) *call_args;
13503         unsigned int nargs, i;
13504         bool qualified_p;
13505         bool koenig_p;
13506         tree ret;
13507
13508         function = CALL_EXPR_FN (t);
13509         /* When we parsed the expression,  we determined whether or
13510            not Koenig lookup should be performed.  */
13511         koenig_p = KOENIG_LOOKUP_P (t);
13512         if (TREE_CODE (function) == SCOPE_REF)
13513           {
13514             qualified_p = true;
13515             function = tsubst_qualified_id (function, args, complain, in_decl,
13516                                             /*done=*/false,
13517                                             /*address_p=*/false);
13518           }
13519         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13520           {
13521             /* Do nothing; calling tsubst_copy_and_build on an identifier
13522                would incorrectly perform unqualified lookup again.
13523
13524                Note that we can also have an IDENTIFIER_NODE if the earlier
13525                unqualified lookup found a member function; in that case
13526                koenig_p will be false and we do want to do the lookup
13527                again to find the instantiated member function.
13528
13529                FIXME but doing that causes c++/15272, so we need to stop
13530                using IDENTIFIER_NODE in that situation.  */
13531             qualified_p = false;
13532           }
13533         else
13534           {
13535             if (TREE_CODE (function) == COMPONENT_REF)
13536               {
13537                 tree op = TREE_OPERAND (function, 1);
13538
13539                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13540                                || (BASELINK_P (op)
13541                                    && BASELINK_QUALIFIED_P (op)));
13542               }
13543             else
13544               qualified_p = false;
13545
13546             function = tsubst_copy_and_build (function, args, complain,
13547                                               in_decl,
13548                                               !qualified_p,
13549                                               integral_constant_expression_p);
13550
13551             if (BASELINK_P (function))
13552               qualified_p = true;
13553           }
13554
13555         nargs = call_expr_nargs (t);
13556         call_args = make_tree_vector ();
13557         for (i = 0; i < nargs; ++i)
13558           {
13559             tree arg = CALL_EXPR_ARG (t, i);
13560
13561             if (!PACK_EXPANSION_P (arg))
13562               VEC_safe_push (tree, gc, call_args,
13563                              RECUR (CALL_EXPR_ARG (t, i)));
13564             else
13565               {
13566                 /* Expand the pack expansion and push each entry onto
13567                    CALL_ARGS.  */
13568                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13569                 if (TREE_CODE (arg) == TREE_VEC)
13570                   {
13571                     unsigned int len, j;
13572
13573                     len = TREE_VEC_LENGTH (arg);
13574                     for (j = 0; j < len; ++j)
13575                       {
13576                         tree value = TREE_VEC_ELT (arg, j);
13577                         if (value != NULL_TREE)
13578                           value = convert_from_reference (value);
13579                         VEC_safe_push (tree, gc, call_args, value);
13580                       }
13581                   }
13582                 else
13583                   {
13584                     /* A partial substitution.  Add one entry.  */
13585                     VEC_safe_push (tree, gc, call_args, arg);
13586                   }
13587               }
13588           }
13589
13590         /* We do not perform argument-dependent lookup if normal
13591            lookup finds a non-function, in accordance with the
13592            expected resolution of DR 218.  */
13593         if (koenig_p
13594             && ((is_overloaded_fn (function)
13595                  /* If lookup found a member function, the Koenig lookup is
13596                     not appropriate, even if an unqualified-name was used
13597                     to denote the function.  */
13598                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13599                 || TREE_CODE (function) == IDENTIFIER_NODE)
13600             /* Only do this when substitution turns a dependent call
13601                into a non-dependent call.  */
13602             && type_dependent_expression_p_push (t)
13603             && !any_type_dependent_arguments_p (call_args))
13604           function = perform_koenig_lookup (function, call_args, false,
13605                                             tf_none);
13606
13607         if (TREE_CODE (function) == IDENTIFIER_NODE
13608             && !any_type_dependent_arguments_p (call_args))
13609           {
13610             if (koenig_p && (complain & tf_warning_or_error))
13611               {
13612                 /* For backwards compatibility and good diagnostics, try
13613                    the unqualified lookup again if we aren't in SFINAE
13614                    context.  */
13615                 tree unq = (tsubst_copy_and_build
13616                             (function, args, complain, in_decl, true,
13617                              integral_constant_expression_p));
13618                 if (unq == error_mark_node)
13619                   return error_mark_node;
13620
13621                 if (unq != function)
13622                   {
13623                     tree fn = unq;
13624                     if (TREE_CODE (fn) == INDIRECT_REF)
13625                       fn = TREE_OPERAND (fn, 0);
13626                     if (TREE_CODE (fn) == COMPONENT_REF)
13627                       fn = TREE_OPERAND (fn, 1);
13628                     if (is_overloaded_fn (fn))
13629                       fn = get_first_fn (fn);
13630                     permerror (EXPR_LOC_OR_HERE (t),
13631                                "%qD was not declared in this scope, "
13632                                "and no declarations were found by "
13633                                "argument-dependent lookup at the point "
13634                                "of instantiation", function);
13635                     if (!DECL_P (fn))
13636                       /* Can't say anything more.  */;
13637                     else if (DECL_CLASS_SCOPE_P (fn))
13638                       {
13639                         inform (EXPR_LOC_OR_HERE (t),
13640                                 "declarations in dependent base %qT are "
13641                                 "not found by unqualified lookup",
13642                                 DECL_CLASS_CONTEXT (fn));
13643                         if (current_class_ptr)
13644                           inform (EXPR_LOC_OR_HERE (t),
13645                                   "use %<this->%D%> instead", function);
13646                         else
13647                           inform (EXPR_LOC_OR_HERE (t),
13648                                   "use %<%T::%D%> instead",
13649                                   current_class_name, function);
13650                       }
13651                     else
13652                       inform (0, "%q+D declared here, later in the "
13653                                 "translation unit", fn);
13654                     function = unq;
13655                   }
13656               }
13657             if (TREE_CODE (function) == IDENTIFIER_NODE)
13658               {
13659                 unqualified_name_lookup_error (function);
13660                 release_tree_vector (call_args);
13661                 return error_mark_node;
13662               }
13663           }
13664
13665         /* Remember that there was a reference to this entity.  */
13666         if (DECL_P (function))
13667           mark_used (function);
13668
13669         if (TREE_CODE (function) == OFFSET_REF)
13670           ret = build_offset_ref_call_from_tree (function, &call_args);
13671         else if (TREE_CODE (function) == COMPONENT_REF)
13672           {
13673             tree instance = TREE_OPERAND (function, 0);
13674             tree fn = TREE_OPERAND (function, 1);
13675
13676             if (processing_template_decl
13677                 && (type_dependent_expression_p (instance)
13678                     || (!BASELINK_P (fn)
13679                         && TREE_CODE (fn) != FIELD_DECL)
13680                     || type_dependent_expression_p (fn)
13681                     || any_type_dependent_arguments_p (call_args)))
13682               ret = build_nt_call_vec (function, call_args);
13683             else if (!BASELINK_P (fn))
13684               ret = finish_call_expr (function, &call_args,
13685                                        /*disallow_virtual=*/false,
13686                                        /*koenig_p=*/false,
13687                                        complain);
13688             else
13689               ret = (build_new_method_call
13690                       (instance, fn,
13691                        &call_args, NULL_TREE,
13692                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13693                        /*fn_p=*/NULL,
13694                        complain));
13695           }
13696         else
13697           ret = finish_call_expr (function, &call_args,
13698                                   /*disallow_virtual=*/qualified_p,
13699                                   koenig_p,
13700                                   complain);
13701
13702         release_tree_vector (call_args);
13703
13704         return ret;
13705       }
13706
13707     case COND_EXPR:
13708       return build_x_conditional_expr
13709         (RECUR (TREE_OPERAND (t, 0)),
13710          RECUR (TREE_OPERAND (t, 1)),
13711          RECUR (TREE_OPERAND (t, 2)),
13712          complain);
13713
13714     case PSEUDO_DTOR_EXPR:
13715       return finish_pseudo_destructor_expr
13716         (RECUR (TREE_OPERAND (t, 0)),
13717          RECUR (TREE_OPERAND (t, 1)),
13718          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13719
13720     case TREE_LIST:
13721       {
13722         tree purpose, value, chain;
13723
13724         if (t == void_list_node)
13725           return t;
13726
13727         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13728             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13729           {
13730             /* We have pack expansions, so expand those and
13731                create a new list out of it.  */
13732             tree purposevec = NULL_TREE;
13733             tree valuevec = NULL_TREE;
13734             tree chain;
13735             int i, len = -1;
13736
13737             /* Expand the argument expressions.  */
13738             if (TREE_PURPOSE (t))
13739               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13740                                                  complain, in_decl);
13741             if (TREE_VALUE (t))
13742               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13743                                                complain, in_decl);
13744
13745             /* Build the rest of the list.  */
13746             chain = TREE_CHAIN (t);
13747             if (chain && chain != void_type_node)
13748               chain = RECUR (chain);
13749
13750             /* Determine the number of arguments.  */
13751             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13752               {
13753                 len = TREE_VEC_LENGTH (purposevec);
13754                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13755               }
13756             else if (TREE_CODE (valuevec) == TREE_VEC)
13757               len = TREE_VEC_LENGTH (valuevec);
13758             else
13759               {
13760                 /* Since we only performed a partial substitution into
13761                    the argument pack, we only return a single list
13762                    node.  */
13763                 if (purposevec == TREE_PURPOSE (t)
13764                     && valuevec == TREE_VALUE (t)
13765                     && chain == TREE_CHAIN (t))
13766                   return t;
13767
13768                 return tree_cons (purposevec, valuevec, chain);
13769               }
13770             
13771             /* Convert the argument vectors into a TREE_LIST */
13772             i = len;
13773             while (i > 0)
13774               {
13775                 /* Grab the Ith values.  */
13776                 i--;
13777                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13778                                      : NULL_TREE;
13779                 value 
13780                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13781                              : NULL_TREE;
13782
13783                 /* Build the list (backwards).  */
13784                 chain = tree_cons (purpose, value, chain);
13785               }
13786
13787             return chain;
13788           }
13789
13790         purpose = TREE_PURPOSE (t);
13791         if (purpose)
13792           purpose = RECUR (purpose);
13793         value = TREE_VALUE (t);
13794         if (value)
13795           value = RECUR (value);
13796         chain = TREE_CHAIN (t);
13797         if (chain && chain != void_type_node)
13798           chain = RECUR (chain);
13799         if (purpose == TREE_PURPOSE (t)
13800             && value == TREE_VALUE (t)
13801             && chain == TREE_CHAIN (t))
13802           return t;
13803         return tree_cons (purpose, value, chain);
13804       }
13805
13806     case COMPONENT_REF:
13807       {
13808         tree object;
13809         tree object_type;
13810         tree member;
13811
13812         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13813                                                      args, complain, in_decl);
13814         /* Remember that there was a reference to this entity.  */
13815         if (DECL_P (object))
13816           mark_used (object);
13817         object_type = TREE_TYPE (object);
13818
13819         member = TREE_OPERAND (t, 1);
13820         if (BASELINK_P (member))
13821           member = tsubst_baselink (member,
13822                                     non_reference (TREE_TYPE (object)),
13823                                     args, complain, in_decl);
13824         else
13825           member = tsubst_copy (member, args, complain, in_decl);
13826         if (member == error_mark_node)
13827           return error_mark_node;
13828
13829         if (type_dependent_expression_p (object))
13830           /* We can't do much here.  */;
13831         else if (!CLASS_TYPE_P (object_type))
13832           {
13833             if (SCALAR_TYPE_P (object_type))
13834               {
13835                 tree s = NULL_TREE;
13836                 tree dtor = member;
13837
13838                 if (TREE_CODE (dtor) == SCOPE_REF)
13839                   {
13840                     s = TREE_OPERAND (dtor, 0);
13841                     dtor = TREE_OPERAND (dtor, 1);
13842                   }
13843                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13844                   {
13845                     dtor = TREE_OPERAND (dtor, 0);
13846                     if (TYPE_P (dtor))
13847                       return finish_pseudo_destructor_expr (object, s, dtor);
13848                   }
13849               }
13850           }
13851         else if (TREE_CODE (member) == SCOPE_REF
13852                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13853           {
13854             /* Lookup the template functions now that we know what the
13855                scope is.  */
13856             tree scope = TREE_OPERAND (member, 0);
13857             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13858             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13859             member = lookup_qualified_name (scope, tmpl,
13860                                             /*is_type_p=*/false,
13861                                             /*complain=*/false);
13862             if (BASELINK_P (member))
13863               {
13864                 BASELINK_FUNCTIONS (member)
13865                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13866                               args);
13867                 member = (adjust_result_of_qualified_name_lookup
13868                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13869                            object_type));
13870               }
13871             else
13872               {
13873                 qualified_name_lookup_error (scope, tmpl, member,
13874                                              input_location);
13875                 return error_mark_node;
13876               }
13877           }
13878         else if (TREE_CODE (member) == SCOPE_REF
13879                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13880                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13881           {
13882             if (complain & tf_error)
13883               {
13884                 if (TYPE_P (TREE_OPERAND (member, 0)))
13885                   error ("%qT is not a class or namespace",
13886                          TREE_OPERAND (member, 0));
13887                 else
13888                   error ("%qD is not a class or namespace",
13889                          TREE_OPERAND (member, 0));
13890               }
13891             return error_mark_node;
13892           }
13893         else if (TREE_CODE (member) == FIELD_DECL)
13894           return finish_non_static_data_member (member, object, NULL_TREE);
13895
13896         return finish_class_member_access_expr (object, member,
13897                                                 /*template_p=*/false,
13898                                                 complain);
13899       }
13900
13901     case THROW_EXPR:
13902       return build_throw
13903         (RECUR (TREE_OPERAND (t, 0)));
13904
13905     case CONSTRUCTOR:
13906       {
13907         VEC(constructor_elt,gc) *n;
13908         constructor_elt *ce;
13909         unsigned HOST_WIDE_INT idx;
13910         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13911         bool process_index_p;
13912         int newlen;
13913         bool need_copy_p = false;
13914         tree r;
13915
13916         if (type == error_mark_node)
13917           return error_mark_node;
13918
13919         /* digest_init will do the wrong thing if we let it.  */
13920         if (type && TYPE_PTRMEMFUNC_P (type))
13921           return t;
13922
13923         /* We do not want to process the index of aggregate
13924            initializers as they are identifier nodes which will be
13925            looked up by digest_init.  */
13926         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13927
13928         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13929         newlen = VEC_length (constructor_elt, n);
13930         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13931           {
13932             if (ce->index && process_index_p)
13933               ce->index = RECUR (ce->index);
13934
13935             if (PACK_EXPANSION_P (ce->value))
13936               {
13937                 /* Substitute into the pack expansion.  */
13938                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13939                                                   in_decl);
13940
13941                 if (ce->value == error_mark_node
13942                     || PACK_EXPANSION_P (ce->value))
13943                   ;
13944                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13945                   /* Just move the argument into place.  */
13946                   ce->value = TREE_VEC_ELT (ce->value, 0);
13947                 else
13948                   {
13949                     /* Update the length of the final CONSTRUCTOR
13950                        arguments vector, and note that we will need to
13951                        copy.*/
13952                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13953                     need_copy_p = true;
13954                   }
13955               }
13956             else
13957               ce->value = RECUR (ce->value);
13958           }
13959
13960         if (need_copy_p)
13961           {
13962             VEC(constructor_elt,gc) *old_n = n;
13963
13964             n = VEC_alloc (constructor_elt, gc, newlen);
13965             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13966               {
13967                 if (TREE_CODE (ce->value) == TREE_VEC)
13968                   {
13969                     int i, len = TREE_VEC_LENGTH (ce->value);
13970                     for (i = 0; i < len; ++i)
13971                       CONSTRUCTOR_APPEND_ELT (n, 0,
13972                                               TREE_VEC_ELT (ce->value, i));
13973                   }
13974                 else
13975                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13976               }
13977           }
13978
13979         r = build_constructor (init_list_type_node, n);
13980         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13981
13982         if (TREE_HAS_CONSTRUCTOR (t))
13983           return finish_compound_literal (type, r, complain);
13984
13985         TREE_TYPE (r) = type;
13986         return r;
13987       }
13988
13989     case TYPEID_EXPR:
13990       {
13991         tree operand_0 = TREE_OPERAND (t, 0);
13992         if (TYPE_P (operand_0))
13993           {
13994             operand_0 = tsubst (operand_0, args, complain, in_decl);
13995             return get_typeid (operand_0);
13996           }
13997         else
13998           {
13999             operand_0 = RECUR (operand_0);
14000             return build_typeid (operand_0);
14001           }
14002       }
14003
14004     case VAR_DECL:
14005       if (!args)
14006         return t;
14007       /* Fall through */
14008
14009     case PARM_DECL:
14010       {
14011         tree r = tsubst_copy (t, args, complain, in_decl);
14012
14013         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
14014           /* If the original type was a reference, we'll be wrapped in
14015              the appropriate INDIRECT_REF.  */
14016           r = convert_from_reference (r);
14017         return r;
14018       }
14019
14020     case VA_ARG_EXPR:
14021       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
14022                              tsubst (TREE_TYPE (t), args, complain, in_decl));
14023
14024     case OFFSETOF_EXPR:
14025       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
14026
14027     case TRAIT_EXPR:
14028       {
14029         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
14030                                   complain, in_decl);
14031
14032         tree type2 = TRAIT_EXPR_TYPE2 (t);
14033         if (type2)
14034           type2 = tsubst_copy (type2, args, complain, in_decl);
14035         
14036         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
14037       }
14038
14039     case STMT_EXPR:
14040       {
14041         tree old_stmt_expr = cur_stmt_expr;
14042         tree stmt_expr = begin_stmt_expr ();
14043
14044         cur_stmt_expr = stmt_expr;
14045         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
14046                      integral_constant_expression_p);
14047         stmt_expr = finish_stmt_expr (stmt_expr, false);
14048         cur_stmt_expr = old_stmt_expr;
14049
14050         /* If the resulting list of expression statement is empty,
14051            fold it further into void_zero_node.  */
14052         if (empty_expr_stmt_p (stmt_expr))
14053           stmt_expr = void_zero_node;
14054
14055         return stmt_expr;
14056       }
14057
14058     case CONST_DECL:
14059       t = tsubst_copy (t, args, complain, in_decl);
14060       /* As in finish_id_expression, we resolve enumeration constants
14061          to their underlying values.  */
14062       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
14063         {
14064           used_types_insert (TREE_TYPE (t));
14065           return DECL_INITIAL (t);
14066         }
14067       return t;
14068
14069     case LAMBDA_EXPR:
14070       {
14071         tree r = build_lambda_expr ();
14072
14073         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
14074         LAMBDA_EXPR_CLOSURE (r) = type;
14075         CLASSTYPE_LAMBDA_EXPR (type) = r;
14076
14077         LAMBDA_EXPR_LOCATION (r)
14078           = LAMBDA_EXPR_LOCATION (t);
14079         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
14080           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
14081         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
14082         LAMBDA_EXPR_DISCRIMINATOR (r)
14083           = (LAMBDA_EXPR_DISCRIMINATOR (t));
14084         LAMBDA_EXPR_EXTRA_SCOPE (r)
14085           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
14086         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
14087           {
14088             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
14089             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
14090           }
14091         else
14092           LAMBDA_EXPR_RETURN_TYPE (r)
14093             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
14094
14095         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
14096                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
14097
14098         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
14099         determine_visibility (TYPE_NAME (type));
14100         /* Now that we know visibility, instantiate the type so we have a
14101            declaration of the op() for later calls to lambda_function.  */
14102         complete_type (type);
14103
14104         /* The capture list refers to closure members, so this needs to
14105            wait until after we finish instantiating the type.  */
14106         LAMBDA_EXPR_CAPTURE_LIST (r)
14107           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
14108
14109         return build_lambda_object (r);
14110       }
14111
14112     case TARGET_EXPR:
14113       /* We can get here for a constant initializer of non-dependent type.
14114          FIXME stop folding in cp_parser_initializer_clause.  */
14115       gcc_assert (TREE_CONSTANT (t));
14116       {
14117         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
14118         TREE_CONSTANT (r) = true;
14119         return r;
14120       }
14121
14122     case TRANSACTION_EXPR:
14123       return tsubst_expr(t, args, complain, in_decl,
14124              integral_constant_expression_p);
14125
14126     default:
14127       /* Handle Objective-C++ constructs, if appropriate.  */
14128       {
14129         tree subst
14130           = objcp_tsubst_copy_and_build (t, args, complain,
14131                                          in_decl, /*function_p=*/false);
14132         if (subst)
14133           return subst;
14134       }
14135       return tsubst_copy (t, args, complain, in_decl);
14136     }
14137
14138 #undef RECUR
14139 }
14140
14141 /* Verify that the instantiated ARGS are valid. For type arguments,
14142    make sure that the type's linkage is ok. For non-type arguments,
14143    make sure they are constants if they are integral or enumerations.
14144    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14145
14146 static bool
14147 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14148 {
14149   if (ARGUMENT_PACK_P (t))
14150     {
14151       tree vec = ARGUMENT_PACK_ARGS (t);
14152       int len = TREE_VEC_LENGTH (vec);
14153       bool result = false;
14154       int i;
14155
14156       for (i = 0; i < len; ++i)
14157         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14158           result = true;
14159       return result;
14160     }
14161   else if (TYPE_P (t))
14162     {
14163       /* [basic.link]: A name with no linkage (notably, the name
14164          of a class or enumeration declared in a local scope)
14165          shall not be used to declare an entity with linkage.
14166          This implies that names with no linkage cannot be used as
14167          template arguments
14168
14169          DR 757 relaxes this restriction for C++0x.  */
14170       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14171                  : no_linkage_check (t, /*relaxed_p=*/false));
14172
14173       if (nt)
14174         {
14175           /* DR 488 makes use of a type with no linkage cause
14176              type deduction to fail.  */
14177           if (complain & tf_error)
14178             {
14179               if (TYPE_ANONYMOUS_P (nt))
14180                 error ("%qT is/uses anonymous type", t);
14181               else
14182                 error ("template argument for %qD uses local type %qT",
14183                        tmpl, t);
14184             }
14185           return true;
14186         }
14187       /* In order to avoid all sorts of complications, we do not
14188          allow variably-modified types as template arguments.  */
14189       else if (variably_modified_type_p (t, NULL_TREE))
14190         {
14191           if (complain & tf_error)
14192             error ("%qT is a variably modified type", t);
14193           return true;
14194         }
14195     }
14196   /* A non-type argument of integral or enumerated type must be a
14197      constant.  */
14198   else if (TREE_TYPE (t)
14199            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14200            && !TREE_CONSTANT (t))
14201     {
14202       if (complain & tf_error)
14203         error ("integral expression %qE is not constant", t);
14204       return true;
14205     }
14206   return false;
14207 }
14208
14209 static bool
14210 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14211 {
14212   int ix, len = DECL_NTPARMS (tmpl);
14213   bool result = false;
14214
14215   for (ix = 0; ix != len; ix++)
14216     {
14217       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14218         result = true;
14219     }
14220   if (result && (complain & tf_error))
14221     error ("  trying to instantiate %qD", tmpl);
14222   return result;
14223 }
14224
14225 /* In C++0x, it's possible to have a function template whose type depends
14226    on itself recursively.  This is most obvious with decltype, but can also
14227    occur with enumeration scope (c++/48969).  So we need to catch infinite
14228    recursion and reject the substitution at deduction time; this function
14229    will return error_mark_node for any repeated substitution.
14230
14231    This also catches excessive recursion such as when f<N> depends on
14232    f<N-1> across all integers, and returns error_mark_node for all the
14233    substitutions back up to the initial one.
14234
14235    This is, of course, not reentrant.  */
14236
14237 static tree
14238 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14239 {
14240   static bool excessive_deduction_depth;
14241   static int deduction_depth;
14242   struct pending_template *old_last_pend = last_pending_template;
14243   struct tinst_level *old_error_tinst = last_error_tinst_level;
14244
14245   tree fntype = TREE_TYPE (fn);
14246   tree tinst;
14247   tree r;
14248
14249   if (excessive_deduction_depth)
14250     return error_mark_node;
14251
14252   tinst = build_tree_list (fn, targs);
14253   if (!push_tinst_level (tinst))
14254     {
14255       excessive_deduction_depth = true;
14256       ggc_free (tinst);
14257       return error_mark_node;
14258     }
14259
14260   input_location = DECL_SOURCE_LOCATION (fn);
14261   ++deduction_depth;
14262   push_deduction_access_scope (fn);
14263   r = tsubst (fntype, targs, complain, NULL_TREE);
14264   pop_deduction_access_scope (fn);
14265   --deduction_depth;
14266
14267   if (excessive_deduction_depth)
14268     {
14269       r = error_mark_node;
14270       if (deduction_depth == 0)
14271         /* Reset once we're all the way out.  */
14272         excessive_deduction_depth = false;
14273     }
14274
14275   pop_tinst_level ();
14276   /* We can't free this if a pending_template entry or last_error_tinst_level
14277      is pointing at it.  */
14278   if (last_pending_template == old_last_pend
14279       && last_error_tinst_level == old_error_tinst)
14280     ggc_free (tinst);
14281   return r;
14282 }
14283
14284 /* Instantiate the indicated variable or function template TMPL with
14285    the template arguments in TARG_PTR.  */
14286
14287 static tree
14288 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14289 {
14290   tree targ_ptr = orig_args;
14291   tree fndecl;
14292   tree gen_tmpl;
14293   tree spec;
14294
14295   if (tmpl == error_mark_node)
14296     return error_mark_node;
14297
14298   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14299
14300   /* If this function is a clone, handle it specially.  */
14301   if (DECL_CLONED_FUNCTION_P (tmpl))
14302     {
14303       tree spec;
14304       tree clone;
14305
14306       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14307          DECL_CLONED_FUNCTION.  */
14308       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14309                                    targ_ptr, complain);
14310       if (spec == error_mark_node)
14311         return error_mark_node;
14312
14313       /* Look for the clone.  */
14314       FOR_EACH_CLONE (clone, spec)
14315         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14316           return clone;
14317       /* We should always have found the clone by now.  */
14318       gcc_unreachable ();
14319       return NULL_TREE;
14320     }
14321
14322   /* Check to see if we already have this specialization.  */
14323   gen_tmpl = most_general_template (tmpl);
14324   if (tmpl != gen_tmpl)
14325     /* The TMPL is a partial instantiation.  To get a full set of
14326        arguments we must add the arguments used to perform the
14327        partial instantiation.  */
14328     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14329                                             targ_ptr);
14330
14331   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14332      but it doesn't seem to be on the hot path.  */
14333   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14334
14335   gcc_assert (tmpl == gen_tmpl
14336               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14337                   == spec)
14338               || fndecl == NULL_TREE);
14339
14340   if (spec != NULL_TREE)
14341     return spec;
14342
14343   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14344                                complain))
14345     return error_mark_node;
14346
14347   /* We are building a FUNCTION_DECL, during which the access of its
14348      parameters and return types have to be checked.  However this
14349      FUNCTION_DECL which is the desired context for access checking
14350      is not built yet.  We solve this chicken-and-egg problem by
14351      deferring all checks until we have the FUNCTION_DECL.  */
14352   push_deferring_access_checks (dk_deferred);
14353
14354   /* Instantiation of the function happens in the context of the function
14355      template, not the context of the overload resolution we're doing.  */
14356   push_to_top_level ();
14357   if (DECL_CLASS_SCOPE_P (gen_tmpl))
14358     {
14359       tree ctx = tsubst (DECL_CONTEXT (gen_tmpl), targ_ptr,
14360                          complain, gen_tmpl);
14361       push_nested_class (ctx);
14362     }
14363   /* Substitute template parameters to obtain the specialization.  */
14364   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14365                    targ_ptr, complain, gen_tmpl);
14366   if (DECL_CLASS_SCOPE_P (gen_tmpl))
14367     pop_nested_class ();
14368   pop_from_top_level ();
14369
14370   if (fndecl == error_mark_node)
14371     return error_mark_node;
14372
14373   /* Now we know the specialization, compute access previously
14374      deferred.  */
14375   push_access_scope (fndecl);
14376
14377   /* Some typedefs referenced from within the template code need to be access
14378      checked at template instantiation time, i.e now. These types were
14379      added to the template at parsing time. Let's get those and perfom
14380      the acces checks then.  */
14381   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14382   perform_deferred_access_checks ();
14383   pop_access_scope (fndecl);
14384   pop_deferring_access_checks ();
14385
14386   /* The DECL_TI_TEMPLATE should always be the immediate parent
14387      template, not the most general template.  */
14388   DECL_TI_TEMPLATE (fndecl) = tmpl;
14389
14390   /* If we've just instantiated the main entry point for a function,
14391      instantiate all the alternate entry points as well.  We do this
14392      by cloning the instantiation of the main entry point, not by
14393      instantiating the template clones.  */
14394   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14395     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14396
14397   return fndecl;
14398 }
14399
14400 /* Wrapper for instantiate_template_1.  */
14401
14402 tree
14403 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14404 {
14405   tree ret;
14406   timevar_push (TV_TEMPLATE_INST);
14407   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14408   timevar_pop (TV_TEMPLATE_INST);
14409   return ret;
14410 }
14411
14412 /* We're going to do deduction substitution on the type of TMPL, a function
14413    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14414    disable access checking.  */
14415
14416 static void
14417 push_deduction_access_scope (tree tmpl)
14418 {
14419   if (cxx_dialect >= cxx0x)
14420     {
14421       int ptd = processing_template_decl;
14422       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14423       /* Preserve processing_template_decl across push_to_top_level.  */
14424       if (ptd && !processing_template_decl)
14425         ++processing_template_decl;
14426     }
14427   else
14428     push_deferring_access_checks (dk_no_check);
14429 }
14430
14431 /* And pop back out.  */
14432
14433 static void
14434 pop_deduction_access_scope (tree tmpl)
14435 {
14436   if (cxx_dialect >= cxx0x)
14437     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14438   else
14439     pop_deferring_access_checks ();
14440 }
14441
14442 /* PARM is a template parameter pack for FN.  Returns true iff
14443    PARM is used in a deducible way in the argument list of FN.  */
14444
14445 static bool
14446 pack_deducible_p (tree parm, tree fn)
14447 {
14448   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14449   for (; t; t = TREE_CHAIN (t))
14450     {
14451       tree type = TREE_VALUE (t);
14452       tree packs;
14453       if (!PACK_EXPANSION_P (type))
14454         continue;
14455       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14456            packs; packs = TREE_CHAIN (packs))
14457         if (TREE_VALUE (packs) == parm)
14458           {
14459             /* The template parameter pack is used in a function parameter
14460                pack.  If this is the end of the parameter list, the
14461                template parameter pack is deducible.  */
14462             if (TREE_CHAIN (t) == void_list_node)
14463               return true;
14464             else
14465               /* Otherwise, not.  Well, it could be deduced from
14466                  a non-pack parameter, but doing so would end up with
14467                  a deduction mismatch, so don't bother.  */
14468               return false;
14469           }
14470     }
14471   /* The template parameter pack isn't used in any function parameter
14472      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14473   return true;
14474 }
14475
14476 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14477    NARGS elements of the arguments that are being used when calling
14478    it.  TARGS is a vector into which the deduced template arguments
14479    are placed.
14480
14481    Return zero for success, 2 for an incomplete match that doesn't resolve
14482    all the types, and 1 for complete failure.  An error message will be
14483    printed only for an incomplete match.
14484
14485    If FN is a conversion operator, or we are trying to produce a specific
14486    specialization, RETURN_TYPE is the return type desired.
14487
14488    The EXPLICIT_TARGS are explicit template arguments provided via a
14489    template-id.
14490
14491    The parameter STRICT is one of:
14492
14493    DEDUCE_CALL:
14494      We are deducing arguments for a function call, as in
14495      [temp.deduct.call].
14496
14497    DEDUCE_CONV:
14498      We are deducing arguments for a conversion function, as in
14499      [temp.deduct.conv].
14500
14501    DEDUCE_EXACT:
14502      We are deducing arguments when doing an explicit instantiation
14503      as in [temp.explicit], when determining an explicit specialization
14504      as in [temp.expl.spec], or when taking the address of a function
14505      template, as in [temp.deduct.funcaddr].  */
14506
14507 int
14508 fn_type_unification (tree fn,
14509                      tree explicit_targs,
14510                      tree targs,
14511                      const tree *args,
14512                      unsigned int nargs,
14513                      tree return_type,
14514                      unification_kind_t strict,
14515                      int flags,
14516                      bool explain_p)
14517 {
14518   tree parms;
14519   tree fntype;
14520   int result;
14521
14522   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14523
14524   fntype = TREE_TYPE (fn);
14525   if (explicit_targs)
14526     {
14527       /* [temp.deduct]
14528
14529          The specified template arguments must match the template
14530          parameters in kind (i.e., type, nontype, template), and there
14531          must not be more arguments than there are parameters;
14532          otherwise type deduction fails.
14533
14534          Nontype arguments must match the types of the corresponding
14535          nontype template parameters, or must be convertible to the
14536          types of the corresponding nontype parameters as specified in
14537          _temp.arg.nontype_, otherwise type deduction fails.
14538
14539          All references in the function type of the function template
14540          to the corresponding template parameters are replaced by the
14541          specified template argument values.  If a substitution in a
14542          template parameter or in the function type of the function
14543          template results in an invalid type, type deduction fails.  */
14544       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14545       int i, len = TREE_VEC_LENGTH (tparms);
14546       tree converted_args;
14547       bool incomplete = false;
14548
14549       if (explicit_targs == error_mark_node)
14550         return unify_invalid (explain_p);
14551
14552       converted_args
14553         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14554                                   (explain_p
14555                                    ? tf_warning_or_error
14556                                    : tf_none),
14557                                    /*require_all_args=*/false,
14558                                    /*use_default_args=*/false));
14559       if (converted_args == error_mark_node)
14560         return 1;
14561
14562       /* Substitute the explicit args into the function type.  This is
14563          necessary so that, for instance, explicitly declared function
14564          arguments can match null pointed constants.  If we were given
14565          an incomplete set of explicit args, we must not do semantic
14566          processing during substitution as we could create partial
14567          instantiations.  */
14568       for (i = 0; i < len; i++)
14569         {
14570           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14571           bool parameter_pack = false;
14572           tree targ = TREE_VEC_ELT (converted_args, i);
14573
14574           /* Dig out the actual parm.  */
14575           if (TREE_CODE (parm) == TYPE_DECL
14576               || TREE_CODE (parm) == TEMPLATE_DECL)
14577             {
14578               parm = TREE_TYPE (parm);
14579               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14580             }
14581           else if (TREE_CODE (parm) == PARM_DECL)
14582             {
14583               parm = DECL_INITIAL (parm);
14584               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14585             }
14586
14587           if (!parameter_pack && targ == NULL_TREE)
14588             /* No explicit argument for this template parameter.  */
14589             incomplete = true;
14590
14591           if (parameter_pack && pack_deducible_p (parm, fn))
14592             {
14593               /* Mark the argument pack as "incomplete". We could
14594                  still deduce more arguments during unification.
14595                  We remove this mark in type_unification_real.  */
14596               if (targ)
14597                 {
14598                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14599                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14600                     = ARGUMENT_PACK_ARGS (targ);
14601                 }
14602
14603               /* We have some incomplete argument packs.  */
14604               incomplete = true;
14605             }
14606         }
14607
14608       processing_template_decl += incomplete;
14609       fntype = deduction_tsubst_fntype (fn, converted_args,
14610                                         (explain_p
14611                                          ? tf_warning_or_error
14612                                          : tf_none));
14613       processing_template_decl -= incomplete;
14614
14615       if (fntype == error_mark_node)
14616         return 1;
14617
14618       /* Place the explicitly specified arguments in TARGS.  */
14619       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14620         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14621     }
14622
14623   /* Never do unification on the 'this' parameter.  */
14624   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14625
14626   if (return_type)
14627     {
14628       tree *new_args;
14629
14630       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14631       new_args = XALLOCAVEC (tree, nargs + 1);
14632       new_args[0] = return_type;
14633       memcpy (new_args + 1, args, nargs * sizeof (tree));
14634       args = new_args;
14635       ++nargs;
14636     }
14637
14638   /* We allow incomplete unification without an error message here
14639      because the standard doesn't seem to explicitly prohibit it.  Our
14640      callers must be ready to deal with unification failures in any
14641      event.  */
14642   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14643                                   targs, parms, args, nargs, /*subr=*/0,
14644                                   strict, flags, explain_p);
14645
14646   /* Now that we have bindings for all of the template arguments,
14647      ensure that the arguments deduced for the template template
14648      parameters have compatible template parameter lists.  We cannot
14649      check this property before we have deduced all template
14650      arguments, because the template parameter types of a template
14651      template parameter might depend on prior template parameters
14652      deduced after the template template parameter.  The following
14653      ill-formed example illustrates this issue:
14654
14655        template<typename T, template<T> class C> void f(C<5>, T);
14656
14657        template<int N> struct X {};
14658
14659        void g() {
14660          f(X<5>(), 5l); // error: template argument deduction fails
14661        }
14662
14663      The template parameter list of 'C' depends on the template type
14664      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14665      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14666      time that we deduce 'C'.  */
14667   if (result == 0
14668       && !template_template_parm_bindings_ok_p 
14669            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14670     return unify_inconsistent_template_template_parameters (explain_p);
14671
14672   if (result == 0)
14673     /* All is well so far.  Now, check:
14674
14675        [temp.deduct]
14676
14677        When all template arguments have been deduced, all uses of
14678        template parameters in nondeduced contexts are replaced with
14679        the corresponding deduced argument values.  If the
14680        substitution results in an invalid type, as described above,
14681        type deduction fails.  */
14682     {
14683       tree substed = deduction_tsubst_fntype (fn, targs,
14684                                               (explain_p
14685                                                ? tf_warning_or_error
14686                                                : tf_none));
14687       if (substed == error_mark_node)
14688         return 1;
14689
14690       /* If we're looking for an exact match, check that what we got
14691          is indeed an exact match.  It might not be if some template
14692          parameters are used in non-deduced contexts.  */
14693       if (strict == DEDUCE_EXACT)
14694         {
14695           unsigned int i;
14696
14697           tree sarg
14698             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14699           if (return_type)
14700             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14701           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14702             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14703               return unify_type_mismatch (explain_p, args[i],
14704                                           TREE_VALUE (sarg));
14705         }
14706     }
14707
14708   return result;
14709 }
14710
14711 /* Adjust types before performing type deduction, as described in
14712    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14713    sections are symmetric.  PARM is the type of a function parameter
14714    or the return type of the conversion function.  ARG is the type of
14715    the argument passed to the call, or the type of the value
14716    initialized with the result of the conversion function.
14717    ARG_EXPR is the original argument expression, which may be null.  */
14718
14719 static int
14720 maybe_adjust_types_for_deduction (unification_kind_t strict,
14721                                   tree* parm,
14722                                   tree* arg,
14723                                   tree arg_expr)
14724 {
14725   int result = 0;
14726
14727   switch (strict)
14728     {
14729     case DEDUCE_CALL:
14730       break;
14731
14732     case DEDUCE_CONV:
14733       {
14734         /* Swap PARM and ARG throughout the remainder of this
14735            function; the handling is precisely symmetric since PARM
14736            will initialize ARG rather than vice versa.  */
14737         tree* temp = parm;
14738         parm = arg;
14739         arg = temp;
14740         break;
14741       }
14742
14743     case DEDUCE_EXACT:
14744       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14745          too, but here handle it by stripping the reference from PARM
14746          rather than by adding it to ARG.  */
14747       if (TREE_CODE (*parm) == REFERENCE_TYPE
14748           && TYPE_REF_IS_RVALUE (*parm)
14749           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14750           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14751           && TREE_CODE (*arg) == REFERENCE_TYPE
14752           && !TYPE_REF_IS_RVALUE (*arg))
14753         *parm = TREE_TYPE (*parm);
14754       /* Nothing else to do in this case.  */
14755       return 0;
14756
14757     default:
14758       gcc_unreachable ();
14759     }
14760
14761   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14762     {
14763       /* [temp.deduct.call]
14764
14765          If P is not a reference type:
14766
14767          --If A is an array type, the pointer type produced by the
14768          array-to-pointer standard conversion (_conv.array_) is
14769          used in place of A for type deduction; otherwise,
14770
14771          --If A is a function type, the pointer type produced by
14772          the function-to-pointer standard conversion
14773          (_conv.func_) is used in place of A for type deduction;
14774          otherwise,
14775
14776          --If A is a cv-qualified type, the top level
14777          cv-qualifiers of A's type are ignored for type
14778          deduction.  */
14779       if (TREE_CODE (*arg) == ARRAY_TYPE)
14780         *arg = build_pointer_type (TREE_TYPE (*arg));
14781       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14782         *arg = build_pointer_type (*arg);
14783       else
14784         *arg = TYPE_MAIN_VARIANT (*arg);
14785     }
14786
14787   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14788      of the form T&&, where T is a template parameter, and the argument
14789      is an lvalue, T is deduced as A& */
14790   if (TREE_CODE (*parm) == REFERENCE_TYPE
14791       && TYPE_REF_IS_RVALUE (*parm)
14792       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14793       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14794       && (arg_expr ? real_lvalue_p (arg_expr)
14795           /* try_one_overload doesn't provide an arg_expr, but
14796              functions are always lvalues.  */
14797           : TREE_CODE (*arg) == FUNCTION_TYPE))
14798     *arg = build_reference_type (*arg);
14799
14800   /* [temp.deduct.call]
14801
14802      If P is a cv-qualified type, the top level cv-qualifiers
14803      of P's type are ignored for type deduction.  If P is a
14804      reference type, the type referred to by P is used for
14805      type deduction.  */
14806   *parm = TYPE_MAIN_VARIANT (*parm);
14807   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14808     {
14809       *parm = TREE_TYPE (*parm);
14810       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14811     }
14812
14813   /* DR 322. For conversion deduction, remove a reference type on parm
14814      too (which has been swapped into ARG).  */
14815   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14816     *arg = TREE_TYPE (*arg);
14817
14818   return result;
14819 }
14820
14821 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14822    template which does contain any deducible template parameters; check if
14823    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14824    unify_one_argument.  */
14825
14826 static int
14827 check_non_deducible_conversion (tree parm, tree arg, int strict,
14828                                 int flags, bool explain_p)
14829 {
14830   tree type;
14831
14832   if (!TYPE_P (arg))
14833     type = TREE_TYPE (arg);
14834   else
14835     type = arg;
14836
14837   if (same_type_p (parm, type))
14838     return unify_success (explain_p);
14839
14840   if (strict == DEDUCE_CONV)
14841     {
14842       if (can_convert_arg (type, parm, NULL_TREE, flags))
14843         return unify_success (explain_p);
14844     }
14845   else if (strict != DEDUCE_EXACT)
14846     {
14847       if (can_convert_arg (parm, type,
14848                            TYPE_P (arg) ? NULL_TREE : arg,
14849                            flags))
14850         return unify_success (explain_p);
14851     }
14852
14853   if (strict == DEDUCE_EXACT)
14854     return unify_type_mismatch (explain_p, parm, arg);
14855   else
14856     return unify_arg_conversion (explain_p, parm, type, arg);
14857 }
14858
14859 /* Subroutine of type_unification_real and unify_pack_expansion to
14860    handle unification of a single P/A pair.  Parameters are as
14861    for those functions.  */
14862
14863 static int
14864 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14865                     int subr, unification_kind_t strict, int flags,
14866                     bool explain_p)
14867 {
14868   tree arg_expr = NULL_TREE;
14869   int arg_strict;
14870
14871   if (arg == error_mark_node || parm == error_mark_node)
14872     return unify_invalid (explain_p);
14873   if (arg == unknown_type_node)
14874     /* We can't deduce anything from this, but we might get all the
14875        template args from other function args.  */
14876     return unify_success (explain_p);
14877
14878   /* FIXME uses_deducible_template_parms */
14879   if (TYPE_P (parm) && !uses_template_parms (parm))
14880     return check_non_deducible_conversion (parm, arg, strict, flags,
14881                                            explain_p);
14882
14883   switch (strict)
14884     {
14885     case DEDUCE_CALL:
14886       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14887                     | UNIFY_ALLOW_MORE_CV_QUAL
14888                     | UNIFY_ALLOW_DERIVED);
14889       break;
14890
14891     case DEDUCE_CONV:
14892       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14893       break;
14894
14895     case DEDUCE_EXACT:
14896       arg_strict = UNIFY_ALLOW_NONE;
14897       break;
14898
14899     default:
14900       gcc_unreachable ();
14901     }
14902
14903   /* We only do these transformations if this is the top-level
14904      parameter_type_list in a call or declaration matching; in other
14905      situations (nested function declarators, template argument lists) we
14906      won't be comparing a type to an expression, and we don't do any type
14907      adjustments.  */
14908   if (!subr)
14909     {
14910       if (!TYPE_P (arg))
14911         {
14912           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14913           if (type_unknown_p (arg))
14914             {
14915               /* [temp.deduct.type] A template-argument can be
14916                  deduced from a pointer to function or pointer
14917                  to member function argument if the set of
14918                  overloaded functions does not contain function
14919                  templates and at most one of a set of
14920                  overloaded functions provides a unique
14921                  match.  */
14922
14923               if (resolve_overloaded_unification
14924                   (tparms, targs, parm, arg, strict,
14925                    arg_strict, explain_p))
14926                 return unify_success (explain_p);
14927               return unify_overload_resolution_failure (explain_p, arg);
14928             }
14929
14930           arg_expr = arg;
14931           arg = unlowered_expr_type (arg);
14932           if (arg == error_mark_node)
14933             return unify_invalid (explain_p);
14934         }
14935
14936       arg_strict |=
14937         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
14938     }
14939   else
14940     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
14941                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
14942
14943   /* For deduction from an init-list we need the actual list.  */
14944   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14945     arg = arg_expr;
14946   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
14947 }
14948
14949 /* Most parms like fn_type_unification.
14950
14951    If SUBR is 1, we're being called recursively (to unify the
14952    arguments of a function or method parameter of a function
14953    template). */
14954
14955 static int
14956 type_unification_real (tree tparms,
14957                        tree targs,
14958                        tree xparms,
14959                        const tree *xargs,
14960                        unsigned int xnargs,
14961                        int subr,
14962                        unification_kind_t strict,
14963                        int flags,
14964                        bool explain_p)
14965 {
14966   tree parm, arg;
14967   int i;
14968   int ntparms = TREE_VEC_LENGTH (tparms);
14969   int saw_undeduced = 0;
14970   tree parms;
14971   const tree *args;
14972   unsigned int nargs;
14973   unsigned int ia;
14974
14975   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14976   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14977   gcc_assert (ntparms > 0);
14978
14979   /* Reset the number of non-defaulted template arguments contained
14980      in TARGS.  */
14981   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14982
14983  again:
14984   parms = xparms;
14985   args = xargs;
14986   nargs = xnargs;
14987
14988   ia = 0;
14989   while (parms && parms != void_list_node
14990          && ia < nargs)
14991     {
14992       parm = TREE_VALUE (parms);
14993
14994       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
14995           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
14996         /* For a function parameter pack that occurs at the end of the
14997            parameter-declaration-list, the type A of each remaining
14998            argument of the call is compared with the type P of the
14999            declarator-id of the function parameter pack.  */
15000         break;
15001
15002       parms = TREE_CHAIN (parms);
15003
15004       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
15005         /* For a function parameter pack that does not occur at the
15006            end of the parameter-declaration-list, the type of the
15007            parameter pack is a non-deduced context.  */
15008         continue;
15009
15010       arg = args[ia];
15011       ++ia;
15012
15013       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15014                               flags, explain_p))
15015         return 1;
15016     }
15017
15018   if (parms 
15019       && parms != void_list_node
15020       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
15021     {
15022       /* Unify the remaining arguments with the pack expansion type.  */
15023       tree argvec;
15024       tree parmvec = make_tree_vec (1);
15025
15026       /* Allocate a TREE_VEC and copy in all of the arguments */ 
15027       argvec = make_tree_vec (nargs - ia);
15028       for (i = 0; ia < nargs; ++ia, ++i)
15029         TREE_VEC_ELT (argvec, i) = args[ia];
15030
15031       /* Copy the parameter into parmvec.  */
15032       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
15033       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
15034                                 /*subr=*/subr, explain_p))
15035         return 1;
15036
15037       /* Advance to the end of the list of parameters.  */
15038       parms = TREE_CHAIN (parms);
15039     }
15040
15041   /* Fail if we've reached the end of the parm list, and more args
15042      are present, and the parm list isn't variadic.  */
15043   if (ia < nargs && parms == void_list_node)
15044     return unify_too_many_arguments (explain_p, nargs, ia);
15045   /* Fail if parms are left and they don't have default values.  */
15046   if (parms && parms != void_list_node
15047       && TREE_PURPOSE (parms) == NULL_TREE)
15048     {
15049       unsigned int count = nargs;
15050       tree p = parms;
15051       while (p && p != void_list_node)
15052         {
15053           count++;
15054           p = TREE_CHAIN (p);
15055         }
15056       return unify_too_few_arguments (explain_p, ia, count);
15057     }
15058
15059   if (!subr)
15060     {
15061       tsubst_flags_t complain = (explain_p
15062                                  ? tf_warning_or_error
15063                                  : tf_none);
15064
15065       /* Check to see if we need another pass before we start clearing
15066          ARGUMENT_PACK_INCOMPLETE_P.  */
15067       for (i = 0; i < ntparms; i++)
15068         {
15069           tree targ = TREE_VEC_ELT (targs, i);
15070           tree tparm = TREE_VEC_ELT (tparms, i);
15071
15072           if (targ || tparm == error_mark_node)
15073             continue;
15074           tparm = TREE_VALUE (tparm);
15075
15076           /* If this is an undeduced nontype parameter that depends on
15077              a type parameter, try another pass; its type may have been
15078              deduced from a later argument than the one from which
15079              this parameter can be deduced.  */
15080           if (TREE_CODE (tparm) == PARM_DECL
15081               && uses_template_parms (TREE_TYPE (tparm))
15082               && !saw_undeduced++)
15083             goto again;
15084         }
15085
15086       for (i = 0; i < ntparms; i++)
15087         {
15088           tree targ = TREE_VEC_ELT (targs, i);
15089           tree tparm = TREE_VEC_ELT (tparms, i);
15090
15091           /* Clear the "incomplete" flags on all argument packs now so that
15092              substituting them into later default arguments works.  */
15093           if (targ && ARGUMENT_PACK_P (targ))
15094             {
15095               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
15096               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
15097             }
15098
15099           if (targ || tparm == error_mark_node)
15100             continue;
15101           tparm = TREE_VALUE (tparm);
15102
15103           /* Core issue #226 (C++0x) [temp.deduct]:
15104
15105              If a template argument has not been deduced, its
15106              default template argument, if any, is used. 
15107
15108              When we are in C++98 mode, TREE_PURPOSE will either
15109              be NULL_TREE or ERROR_MARK_NODE, so we do not need
15110              to explicitly check cxx_dialect here.  */
15111           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
15112             {
15113               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
15114               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
15115               location_t save_loc = input_location;
15116               if (DECL_P (parm))
15117                 input_location = DECL_SOURCE_LOCATION (parm);
15118               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
15119               arg = convert_template_argument (parm, arg, targs, complain,
15120                                                i, NULL_TREE);
15121               input_location = save_loc;
15122               if (arg == error_mark_node)
15123                 return 1;
15124               else
15125                 {
15126                   TREE_VEC_ELT (targs, i) = arg;
15127                   /* The position of the first default template argument,
15128                      is also the number of non-defaulted arguments in TARGS.
15129                      Record that.  */
15130                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15131                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
15132                   continue;
15133                 }
15134             }
15135
15136           /* If the type parameter is a parameter pack, then it will
15137              be deduced to an empty parameter pack.  */
15138           if (template_parameter_pack_p (tparm))
15139             {
15140               tree arg;
15141
15142               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15143                 {
15144                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15145                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15146                   TREE_CONSTANT (arg) = 1;
15147                 }
15148               else
15149                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15150
15151               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15152
15153               TREE_VEC_ELT (targs, i) = arg;
15154               continue;
15155             }
15156
15157           return unify_parameter_deduction_failure (explain_p, tparm);
15158         }
15159     }
15160 #ifdef ENABLE_CHECKING
15161   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15162     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15163 #endif
15164
15165   return unify_success (explain_p);
15166 }
15167
15168 /* Subroutine of type_unification_real.  Args are like the variables
15169    at the call site.  ARG is an overloaded function (or template-id);
15170    we try deducing template args from each of the overloads, and if
15171    only one succeeds, we go with that.  Modifies TARGS and returns
15172    true on success.  */
15173
15174 static bool
15175 resolve_overloaded_unification (tree tparms,
15176                                 tree targs,
15177                                 tree parm,
15178                                 tree arg,
15179                                 unification_kind_t strict,
15180                                 int sub_strict,
15181                                 bool explain_p)
15182 {
15183   tree tempargs = copy_node (targs);
15184   int good = 0;
15185   tree goodfn = NULL_TREE;
15186   bool addr_p;
15187
15188   if (TREE_CODE (arg) == ADDR_EXPR)
15189     {
15190       arg = TREE_OPERAND (arg, 0);
15191       addr_p = true;
15192     }
15193   else
15194     addr_p = false;
15195
15196   if (TREE_CODE (arg) == COMPONENT_REF)
15197     /* Handle `&x' where `x' is some static or non-static member
15198        function name.  */
15199     arg = TREE_OPERAND (arg, 1);
15200
15201   if (TREE_CODE (arg) == OFFSET_REF)
15202     arg = TREE_OPERAND (arg, 1);
15203
15204   /* Strip baselink information.  */
15205   if (BASELINK_P (arg))
15206     arg = BASELINK_FUNCTIONS (arg);
15207
15208   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15209     {
15210       /* If we got some explicit template args, we need to plug them into
15211          the affected templates before we try to unify, in case the
15212          explicit args will completely resolve the templates in question.  */
15213
15214       int ok = 0;
15215       tree expl_subargs = TREE_OPERAND (arg, 1);
15216       arg = TREE_OPERAND (arg, 0);
15217
15218       for (; arg; arg = OVL_NEXT (arg))
15219         {
15220           tree fn = OVL_CURRENT (arg);
15221           tree subargs, elem;
15222
15223           if (TREE_CODE (fn) != TEMPLATE_DECL)
15224             continue;
15225
15226           ++processing_template_decl;
15227           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15228                                   expl_subargs, /*check_ret=*/false);
15229           if (subargs && !any_dependent_template_arguments_p (subargs))
15230             {
15231               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15232               if (try_one_overload (tparms, targs, tempargs, parm,
15233                                     elem, strict, sub_strict, addr_p, explain_p)
15234                   && (!goodfn || !same_type_p (goodfn, elem)))
15235                 {
15236                   goodfn = elem;
15237                   ++good;
15238                 }
15239             }
15240           else if (subargs)
15241             ++ok;
15242           --processing_template_decl;
15243         }
15244       /* If no templates (or more than one) are fully resolved by the
15245          explicit arguments, this template-id is a non-deduced context; it
15246          could still be OK if we deduce all template arguments for the
15247          enclosing call through other arguments.  */
15248       if (good != 1)
15249         good = ok;
15250     }
15251   else if (TREE_CODE (arg) != OVERLOAD
15252            && TREE_CODE (arg) != FUNCTION_DECL)
15253     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15254        -- but the deduction does not succeed because the expression is
15255        not just the function on its own.  */
15256     return false;
15257   else
15258     for (; arg; arg = OVL_NEXT (arg))
15259       if (try_one_overload (tparms, targs, tempargs, parm,
15260                             TREE_TYPE (OVL_CURRENT (arg)),
15261                             strict, sub_strict, addr_p, explain_p)
15262           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15263         {
15264           goodfn = OVL_CURRENT (arg);
15265           ++good;
15266         }
15267
15268   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15269      to function or pointer to member function argument if the set of
15270      overloaded functions does not contain function templates and at most
15271      one of a set of overloaded functions provides a unique match.
15272
15273      So if we found multiple possibilities, we return success but don't
15274      deduce anything.  */
15275
15276   if (good == 1)
15277     {
15278       int i = TREE_VEC_LENGTH (targs);
15279       for (; i--; )
15280         if (TREE_VEC_ELT (tempargs, i))
15281           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15282     }
15283   if (good)
15284     return true;
15285
15286   return false;
15287 }
15288
15289 /* Core DR 115: In contexts where deduction is done and fails, or in
15290    contexts where deduction is not done, if a template argument list is
15291    specified and it, along with any default template arguments, identifies
15292    a single function template specialization, then the template-id is an
15293    lvalue for the function template specialization.  */
15294
15295 tree
15296 resolve_nondeduced_context (tree orig_expr)
15297 {
15298   tree expr, offset, baselink;
15299   bool addr;
15300
15301   if (!type_unknown_p (orig_expr))
15302     return orig_expr;
15303
15304   expr = orig_expr;
15305   addr = false;
15306   offset = NULL_TREE;
15307   baselink = NULL_TREE;
15308
15309   if (TREE_CODE (expr) == ADDR_EXPR)
15310     {
15311       expr = TREE_OPERAND (expr, 0);
15312       addr = true;
15313     }
15314   if (TREE_CODE (expr) == OFFSET_REF)
15315     {
15316       offset = expr;
15317       expr = TREE_OPERAND (expr, 1);
15318     }
15319   if (BASELINK_P (expr))
15320     {
15321       baselink = expr;
15322       expr = BASELINK_FUNCTIONS (expr);
15323     }
15324
15325   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15326     {
15327       int good = 0;
15328       tree goodfn = NULL_TREE;
15329
15330       /* If we got some explicit template args, we need to plug them into
15331          the affected templates before we try to unify, in case the
15332          explicit args will completely resolve the templates in question.  */
15333
15334       tree expl_subargs = TREE_OPERAND (expr, 1);
15335       tree arg = TREE_OPERAND (expr, 0);
15336       tree badfn = NULL_TREE;
15337       tree badargs = NULL_TREE;
15338
15339       for (; arg; arg = OVL_NEXT (arg))
15340         {
15341           tree fn = OVL_CURRENT (arg);
15342           tree subargs, elem;
15343
15344           if (TREE_CODE (fn) != TEMPLATE_DECL)
15345             continue;
15346
15347           ++processing_template_decl;
15348           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15349                                   expl_subargs, /*check_ret=*/false);
15350           if (subargs && !any_dependent_template_arguments_p (subargs))
15351             {
15352               elem = instantiate_template (fn, subargs, tf_none);
15353               if (elem == error_mark_node)
15354                 {
15355                   badfn = fn;
15356                   badargs = subargs;
15357                 }
15358               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15359                 {
15360                   goodfn = elem;
15361                   ++good;
15362                 }
15363             }
15364           --processing_template_decl;
15365         }
15366       if (good == 1)
15367         {
15368           mark_used (goodfn);
15369           expr = goodfn;
15370           if (baselink)
15371             expr = build_baselink (BASELINK_BINFO (baselink),
15372                                    BASELINK_ACCESS_BINFO (baselink),
15373                                    expr, BASELINK_OPTYPE (baselink));
15374           if (offset)
15375             {
15376               tree base
15377                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15378               expr = build_offset_ref (base, expr, addr);
15379             }
15380           if (addr)
15381             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15382           return expr;
15383         }
15384       else if (good == 0 && badargs)
15385         /* There were no good options and at least one bad one, so let the
15386            user know what the problem is.  */
15387         instantiate_template (badfn, badargs, tf_warning_or_error);
15388     }
15389   return orig_expr;
15390 }
15391
15392 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15393    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15394    different overloads deduce different arguments for a given parm.
15395    ADDR_P is true if the expression for which deduction is being
15396    performed was of the form "& fn" rather than simply "fn".
15397
15398    Returns 1 on success.  */
15399
15400 static int
15401 try_one_overload (tree tparms,
15402                   tree orig_targs,
15403                   tree targs,
15404                   tree parm,
15405                   tree arg,
15406                   unification_kind_t strict,
15407                   int sub_strict,
15408                   bool addr_p,
15409                   bool explain_p)
15410 {
15411   int nargs;
15412   tree tempargs;
15413   int i;
15414
15415   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15416      to function or pointer to member function argument if the set of
15417      overloaded functions does not contain function templates and at most
15418      one of a set of overloaded functions provides a unique match.
15419
15420      So if this is a template, just return success.  */
15421
15422   if (uses_template_parms (arg))
15423     return 1;
15424
15425   if (TREE_CODE (arg) == METHOD_TYPE)
15426     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15427   else if (addr_p)
15428     arg = build_pointer_type (arg);
15429
15430   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15431
15432   /* We don't copy orig_targs for this because if we have already deduced
15433      some template args from previous args, unify would complain when we
15434      try to deduce a template parameter for the same argument, even though
15435      there isn't really a conflict.  */
15436   nargs = TREE_VEC_LENGTH (targs);
15437   tempargs = make_tree_vec (nargs);
15438
15439   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15440     return 0;
15441
15442   /* First make sure we didn't deduce anything that conflicts with
15443      explicitly specified args.  */
15444   for (i = nargs; i--; )
15445     {
15446       tree elt = TREE_VEC_ELT (tempargs, i);
15447       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15448
15449       if (!elt)
15450         /*NOP*/;
15451       else if (uses_template_parms (elt))
15452         /* Since we're unifying against ourselves, we will fill in
15453            template args used in the function parm list with our own
15454            template parms.  Discard them.  */
15455         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15456       else if (oldelt && !template_args_equal (oldelt, elt))
15457         return 0;
15458     }
15459
15460   for (i = nargs; i--; )
15461     {
15462       tree elt = TREE_VEC_ELT (tempargs, i);
15463
15464       if (elt)
15465         TREE_VEC_ELT (targs, i) = elt;
15466     }
15467
15468   return 1;
15469 }
15470
15471 /* PARM is a template class (perhaps with unbound template
15472    parameters).  ARG is a fully instantiated type.  If ARG can be
15473    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15474    TARGS are as for unify.  */
15475
15476 static tree
15477 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15478                        bool explain_p)
15479 {
15480   tree copy_of_targs;
15481
15482   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15483       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15484           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15485     return NULL_TREE;
15486
15487   /* We need to make a new template argument vector for the call to
15488      unify.  If we used TARGS, we'd clutter it up with the result of
15489      the attempted unification, even if this class didn't work out.
15490      We also don't want to commit ourselves to all the unifications
15491      we've already done, since unification is supposed to be done on
15492      an argument-by-argument basis.  In other words, consider the
15493      following pathological case:
15494
15495        template <int I, int J, int K>
15496        struct S {};
15497
15498        template <int I, int J>
15499        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15500
15501        template <int I, int J, int K>
15502        void f(S<I, J, K>, S<I, I, I>);
15503
15504        void g() {
15505          S<0, 0, 0> s0;
15506          S<0, 1, 2> s2;
15507
15508          f(s0, s2);
15509        }
15510
15511      Now, by the time we consider the unification involving `s2', we
15512      already know that we must have `f<0, 0, 0>'.  But, even though
15513      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15514      because there are two ways to unify base classes of S<0, 1, 2>
15515      with S<I, I, I>.  If we kept the already deduced knowledge, we
15516      would reject the possibility I=1.  */
15517   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15518
15519   /* If unification failed, we're done.  */
15520   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15521              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15522     return NULL_TREE;
15523
15524   return arg;
15525 }
15526
15527 /* Given a template type PARM and a class type ARG, find the unique
15528    base type in ARG that is an instance of PARM.  We do not examine
15529    ARG itself; only its base-classes.  If there is not exactly one
15530    appropriate base class, return NULL_TREE.  PARM may be the type of
15531    a partial specialization, as well as a plain template type.  Used
15532    by unify.  */
15533
15534 static enum template_base_result
15535 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15536                    bool explain_p, tree *result)
15537 {
15538   tree rval = NULL_TREE;
15539   tree binfo;
15540
15541   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15542
15543   binfo = TYPE_BINFO (complete_type (arg));
15544   if (!binfo)
15545     {
15546       /* The type could not be completed.  */
15547       *result = NULL_TREE;
15548       return tbr_incomplete_type;
15549     }
15550
15551   /* Walk in inheritance graph order.  The search order is not
15552      important, and this avoids multiple walks of virtual bases.  */
15553   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15554     {
15555       tree r = try_class_unification (tparms, targs, parm,
15556                                       BINFO_TYPE (binfo), explain_p);
15557
15558       if (r)
15559         {
15560           /* If there is more than one satisfactory baseclass, then:
15561
15562                [temp.deduct.call]
15563
15564               If they yield more than one possible deduced A, the type
15565               deduction fails.
15566
15567              applies.  */
15568           if (rval && !same_type_p (r, rval))
15569             {
15570               *result = NULL_TREE;
15571               return tbr_ambiguous_baseclass;
15572             }
15573
15574           rval = r;
15575         }
15576     }
15577
15578   *result = rval;
15579   return tbr_success;
15580 }
15581
15582 /* Returns the level of DECL, which declares a template parameter.  */
15583
15584 static int
15585 template_decl_level (tree decl)
15586 {
15587   switch (TREE_CODE (decl))
15588     {
15589     case TYPE_DECL:
15590     case TEMPLATE_DECL:
15591       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15592
15593     case PARM_DECL:
15594       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15595
15596     default:
15597       gcc_unreachable ();
15598     }
15599   return 0;
15600 }
15601
15602 /* Decide whether ARG can be unified with PARM, considering only the
15603    cv-qualifiers of each type, given STRICT as documented for unify.
15604    Returns nonzero iff the unification is OK on that basis.  */
15605
15606 static int
15607 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15608 {
15609   int arg_quals = cp_type_quals (arg);
15610   int parm_quals = cp_type_quals (parm);
15611
15612   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15613       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15614     {
15615       /*  Although a CVR qualifier is ignored when being applied to a
15616           substituted template parameter ([8.3.2]/1 for example), that
15617           does not allow us to unify "const T" with "int&" because both
15618           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15619           It is ok when we're allowing additional CV qualifiers
15620           at the outer level [14.8.2.1]/3,1st bullet.  */
15621       if ((TREE_CODE (arg) == REFERENCE_TYPE
15622            || TREE_CODE (arg) == FUNCTION_TYPE
15623            || TREE_CODE (arg) == METHOD_TYPE)
15624           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15625         return 0;
15626
15627       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15628           && (parm_quals & TYPE_QUAL_RESTRICT))
15629         return 0;
15630     }
15631
15632   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15633       && (arg_quals & parm_quals) != parm_quals)
15634     return 0;
15635
15636   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15637       && (parm_quals & arg_quals) != arg_quals)
15638     return 0;
15639
15640   return 1;
15641 }
15642
15643 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15644 void 
15645 template_parm_level_and_index (tree parm, int* level, int* index)
15646 {
15647   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15648       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15649       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15650     {
15651       *index = TEMPLATE_TYPE_IDX (parm);
15652       *level = TEMPLATE_TYPE_LEVEL (parm);
15653     }
15654   else
15655     {
15656       *index = TEMPLATE_PARM_IDX (parm);
15657       *level = TEMPLATE_PARM_LEVEL (parm);
15658     }
15659 }
15660
15661 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15662   do {                                                                  \
15663     if (unify (TP, TA, P, A, S, EP))                                    \
15664       return 1;                                                         \
15665   } while (0);
15666
15667 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15668    expansion at the end of PACKED_PARMS. Returns 0 if the type
15669    deduction succeeds, 1 otherwise. STRICT is the same as in
15670    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15671    call argument list. We'll need to adjust the arguments to make them
15672    types. SUBR tells us if this is from a recursive call to
15673    type_unification_real, or for comparing two template argument
15674    lists. */
15675
15676 static int
15677 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15678                       tree packed_args, unification_kind_t strict,
15679                       bool subr, bool explain_p)
15680 {
15681   tree parm 
15682     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15683   tree pattern = PACK_EXPANSION_PATTERN (parm);
15684   tree pack, packs = NULL_TREE;
15685   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15686   int len = TREE_VEC_LENGTH (packed_args);
15687
15688   /* Determine the parameter packs we will be deducing from the
15689      pattern, and record their current deductions.  */
15690   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15691        pack; pack = TREE_CHAIN (pack))
15692     {
15693       tree parm_pack = TREE_VALUE (pack);
15694       int idx, level;
15695
15696       /* Determine the index and level of this parameter pack.  */
15697       template_parm_level_and_index (parm_pack, &level, &idx);
15698
15699       /* Keep track of the parameter packs and their corresponding
15700          argument packs.  */
15701       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15702       TREE_TYPE (packs) = make_tree_vec (len - start);
15703     }
15704   
15705   /* Loop through all of the arguments that have not yet been
15706      unified and unify each with the pattern.  */
15707   for (i = start; i < len; i++)
15708     {
15709       tree parm;
15710       bool any_explicit = false;
15711       tree arg = TREE_VEC_ELT (packed_args, i);
15712
15713       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15714          or the element of its argument pack at the current index if
15715          this argument was explicitly specified.  */
15716       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15717         {
15718           int idx, level;
15719           tree arg, pargs;
15720           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15721
15722           arg = NULL_TREE;
15723           if (TREE_VALUE (pack)
15724               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15725               && (i < TREE_VEC_LENGTH (pargs)))
15726             {
15727               any_explicit = true;
15728               arg = TREE_VEC_ELT (pargs, i);
15729             }
15730           TMPL_ARG (targs, level, idx) = arg;
15731         }
15732
15733       /* If we had explicit template arguments, substitute them into the
15734          pattern before deduction.  */
15735       if (any_explicit)
15736         {
15737           /* Some arguments might still be unspecified or dependent.  */
15738           bool dependent;
15739           ++processing_template_decl;
15740           dependent = any_dependent_template_arguments_p (targs);
15741           if (!dependent)
15742             --processing_template_decl;
15743           parm = tsubst (pattern, targs,
15744                          explain_p ? tf_warning_or_error : tf_none,
15745                          NULL_TREE);
15746           if (dependent)
15747             --processing_template_decl;
15748           if (parm == error_mark_node)
15749             return 1;
15750         }
15751       else
15752         parm = pattern;
15753
15754       /* Unify the pattern with the current argument.  */
15755       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15756                               LOOKUP_IMPLICIT, explain_p))
15757         return 1;
15758
15759       /* For each parameter pack, collect the deduced value.  */
15760       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15761         {
15762           int idx, level;
15763           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15764
15765           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15766             TMPL_ARG (targs, level, idx);
15767         }
15768     }
15769
15770   /* Verify that the results of unification with the parameter packs
15771      produce results consistent with what we've seen before, and make
15772      the deduced argument packs available.  */
15773   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15774     {
15775       tree old_pack = TREE_VALUE (pack);
15776       tree new_args = TREE_TYPE (pack);
15777       int i, len = TREE_VEC_LENGTH (new_args);
15778       int idx, level;
15779       bool nondeduced_p = false;
15780
15781       /* By default keep the original deduced argument pack.
15782          If necessary, more specific code is going to update the
15783          resulting deduced argument later down in this function.  */
15784       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15785       TMPL_ARG (targs, level, idx) = old_pack;
15786
15787       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15788          actually deduce anything.  */
15789       for (i = 0; i < len && !nondeduced_p; ++i)
15790         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15791           nondeduced_p = true;
15792       if (nondeduced_p)
15793         continue;
15794
15795       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15796         {
15797           /* If we had fewer function args than explicit template args,
15798              just use the explicits.  */
15799           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15800           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15801           if (len < explicit_len)
15802             new_args = explicit_args;
15803         }
15804
15805       if (!old_pack)
15806         {
15807           tree result;
15808           /* Build the deduced *_ARGUMENT_PACK.  */
15809           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15810             {
15811               result = make_node (NONTYPE_ARGUMENT_PACK);
15812               TREE_TYPE (result) = 
15813                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15814               TREE_CONSTANT (result) = 1;
15815             }
15816           else
15817             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15818
15819           SET_ARGUMENT_PACK_ARGS (result, new_args);
15820
15821           /* Note the deduced argument packs for this parameter
15822              pack.  */
15823           TMPL_ARG (targs, level, idx) = result;
15824         }
15825       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15826                && (ARGUMENT_PACK_ARGS (old_pack) 
15827                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15828         {
15829           /* We only had the explicitly-provided arguments before, but
15830              now we have a complete set of arguments.  */
15831           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15832
15833           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15834           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15835           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15836         }
15837       else
15838         {
15839           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
15840           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15841
15842           if (!comp_template_args_with_info (old_args, new_args,
15843                                              &bad_old_arg, &bad_new_arg))
15844             /* Inconsistent unification of this parameter pack.  */
15845             return unify_parameter_pack_inconsistent (explain_p,
15846                                                       bad_old_arg,
15847                                                       bad_new_arg);
15848         }
15849     }
15850
15851   return unify_success (explain_p);
15852 }
15853
15854 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15855    set of template parameters to a template.  TARGS is the bindings
15856    for those template parameters, as determined thus far; TARGS may
15857    include template arguments for outer levels of template parameters
15858    as well.  PARM is a parameter to a template function, or a
15859    subcomponent of that parameter; ARG is the corresponding argument.
15860    This function attempts to match PARM with ARG in a manner
15861    consistent with the existing assignments in TARGS.  If more values
15862    are deduced, then TARGS is updated.
15863
15864    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15865    parameter STRICT is a bitwise or of the following flags:
15866
15867      UNIFY_ALLOW_NONE:
15868        Require an exact match between PARM and ARG.
15869      UNIFY_ALLOW_MORE_CV_QUAL:
15870        Allow the deduced ARG to be more cv-qualified (by qualification
15871        conversion) than ARG.
15872      UNIFY_ALLOW_LESS_CV_QUAL:
15873        Allow the deduced ARG to be less cv-qualified than ARG.
15874      UNIFY_ALLOW_DERIVED:
15875        Allow the deduced ARG to be a template base class of ARG,
15876        or a pointer to a template base class of the type pointed to by
15877        ARG.
15878      UNIFY_ALLOW_INTEGER:
15879        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15880        case for more information.
15881      UNIFY_ALLOW_OUTER_LEVEL:
15882        This is the outermost level of a deduction. Used to determine validity
15883        of qualification conversions. A valid qualification conversion must
15884        have const qualified pointers leading up to the inner type which
15885        requires additional CV quals, except at the outer level, where const
15886        is not required [conv.qual]. It would be normal to set this flag in
15887        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15888      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15889        This is the outermost level of a deduction, and PARM can be more CV
15890        qualified at this point.
15891      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15892        This is the outermost level of a deduction, and PARM can be less CV
15893        qualified at this point.  */
15894
15895 static int
15896 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15897        bool explain_p)
15898 {
15899   int idx;
15900   tree targ;
15901   tree tparm;
15902   int strict_in = strict;
15903
15904   /* I don't think this will do the right thing with respect to types.
15905      But the only case I've seen it in so far has been array bounds, where
15906      signedness is the only information lost, and I think that will be
15907      okay.  */
15908   while (TREE_CODE (parm) == NOP_EXPR)
15909     parm = TREE_OPERAND (parm, 0);
15910
15911   if (arg == error_mark_node)
15912     return unify_invalid (explain_p);
15913   if (arg == unknown_type_node
15914       || arg == init_list_type_node)
15915     /* We can't deduce anything from this, but we might get all the
15916        template args from other function args.  */
15917     return unify_success (explain_p);
15918
15919   /* If PARM uses template parameters, then we can't bail out here,
15920      even if ARG == PARM, since we won't record unifications for the
15921      template parameters.  We might need them if we're trying to
15922      figure out which of two things is more specialized.  */
15923   if (arg == parm && !uses_template_parms (parm))
15924     return unify_success (explain_p);
15925
15926   /* Handle init lists early, so the rest of the function can assume
15927      we're dealing with a type. */
15928   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15929     {
15930       tree elt, elttype;
15931       unsigned i;
15932       tree orig_parm = parm;
15933
15934       /* Replace T with std::initializer_list<T> for deduction.  */
15935       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15936           && flag_deduce_init_list)
15937         parm = listify (parm);
15938
15939       if (!is_std_init_list (parm))
15940         /* We can only deduce from an initializer list argument if the
15941            parameter is std::initializer_list; otherwise this is a
15942            non-deduced context. */
15943         return unify_success (explain_p);
15944
15945       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15946
15947       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15948         {
15949           int elt_strict = strict;
15950
15951           if (elt == error_mark_node)
15952             return unify_invalid (explain_p);
15953
15954           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15955             {
15956               tree type = TREE_TYPE (elt);
15957               /* It should only be possible to get here for a call.  */
15958               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15959               elt_strict |= maybe_adjust_types_for_deduction
15960                 (DEDUCE_CALL, &elttype, &type, elt);
15961               elt = type;
15962             }
15963
15964           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15965                                    explain_p);
15966         }
15967
15968       /* If the std::initializer_list<T> deduction worked, replace the
15969          deduced A with std::initializer_list<A>.  */
15970       if (orig_parm != parm)
15971         {
15972           idx = TEMPLATE_TYPE_IDX (orig_parm);
15973           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15974           targ = listify (targ);
15975           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15976         }
15977       return unify_success (explain_p);
15978     }
15979
15980   /* Immediately reject some pairs that won't unify because of
15981      cv-qualification mismatches.  */
15982   if (TREE_CODE (arg) == TREE_CODE (parm)
15983       && TYPE_P (arg)
15984       /* It is the elements of the array which hold the cv quals of an array
15985          type, and the elements might be template type parms. We'll check
15986          when we recurse.  */
15987       && TREE_CODE (arg) != ARRAY_TYPE
15988       /* We check the cv-qualifiers when unifying with template type
15989          parameters below.  We want to allow ARG `const T' to unify with
15990          PARM `T' for example, when computing which of two templates
15991          is more specialized, for example.  */
15992       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15993       && !check_cv_quals_for_unify (strict_in, arg, parm))
15994     return unify_cv_qual_mismatch (explain_p, parm, arg);
15995
15996   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
15997       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15998     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15999   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
16000   strict &= ~UNIFY_ALLOW_DERIVED;
16001   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
16002   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
16003
16004   switch (TREE_CODE (parm))
16005     {
16006     case TYPENAME_TYPE:
16007     case SCOPE_REF:
16008     case UNBOUND_CLASS_TEMPLATE:
16009       /* In a type which contains a nested-name-specifier, template
16010          argument values cannot be deduced for template parameters used
16011          within the nested-name-specifier.  */
16012       return unify_success (explain_p);
16013
16014     case TEMPLATE_TYPE_PARM:
16015     case TEMPLATE_TEMPLATE_PARM:
16016     case BOUND_TEMPLATE_TEMPLATE_PARM:
16017       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16018       if (tparm == error_mark_node)
16019         return unify_invalid (explain_p);
16020
16021       if (TEMPLATE_TYPE_LEVEL (parm)
16022           != template_decl_level (tparm))
16023         /* The PARM is not one we're trying to unify.  Just check
16024            to see if it matches ARG.  */
16025         {
16026           if (TREE_CODE (arg) == TREE_CODE (parm)
16027               && same_type_p (parm, arg))
16028             return unify_success (explain_p);
16029           else
16030             return unify_type_mismatch (explain_p, parm, arg);
16031         }
16032       idx = TEMPLATE_TYPE_IDX (parm);
16033       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16034       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
16035       if (tparm == error_mark_node)
16036         return unify_invalid (explain_p);
16037
16038       /* Check for mixed types and values.  */
16039       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16040            && TREE_CODE (tparm) != TYPE_DECL)
16041           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16042               && TREE_CODE (tparm) != TEMPLATE_DECL))
16043         gcc_unreachable ();
16044
16045       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16046         {
16047           /* ARG must be constructed from a template class or a template
16048              template parameter.  */
16049           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
16050               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
16051             return unify_template_deduction_failure (explain_p, parm, arg);
16052
16053           {
16054             tree parmvec = TYPE_TI_ARGS (parm);
16055             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
16056             tree full_argvec = add_to_template_args (targs, argvec);
16057             tree parm_parms 
16058               = DECL_INNERMOST_TEMPLATE_PARMS
16059                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
16060             int i, len;
16061             int parm_variadic_p = 0;
16062
16063             /* The resolution to DR150 makes clear that default
16064                arguments for an N-argument may not be used to bind T
16065                to a template template parameter with fewer than N
16066                parameters.  It is not safe to permit the binding of
16067                default arguments as an extension, as that may change
16068                the meaning of a conforming program.  Consider:
16069
16070                   struct Dense { static const unsigned int dim = 1; };
16071
16072                   template <template <typename> class View,
16073                             typename Block>
16074                   void operator+(float, View<Block> const&);
16075
16076                   template <typename Block,
16077                             unsigned int Dim = Block::dim>
16078                   struct Lvalue_proxy { operator float() const; };
16079
16080                   void
16081                   test_1d (void) {
16082                     Lvalue_proxy<Dense> p;
16083                     float b;
16084                     b + p;
16085                   }
16086
16087               Here, if Lvalue_proxy is permitted to bind to View, then
16088               the global operator+ will be used; if they are not, the
16089               Lvalue_proxy will be converted to float.  */
16090             if (coerce_template_parms (parm_parms,
16091                                        full_argvec,
16092                                        TYPE_TI_TEMPLATE (parm),
16093                                        (explain_p
16094                                         ? tf_warning_or_error
16095                                         : tf_none),
16096                                        /*require_all_args=*/true,
16097                                        /*use_default_args=*/false)
16098                 == error_mark_node)
16099               return 1;
16100
16101             /* Deduce arguments T, i from TT<T> or TT<i>.
16102                We check each element of PARMVEC and ARGVEC individually
16103                rather than the whole TREE_VEC since they can have
16104                different number of elements.  */
16105
16106             parmvec = expand_template_argument_pack (parmvec);
16107             argvec = expand_template_argument_pack (argvec);
16108
16109             len = TREE_VEC_LENGTH (parmvec);
16110
16111             /* Check if the parameters end in a pack, making them
16112                variadic.  */
16113             if (len > 0
16114                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
16115               parm_variadic_p = 1;
16116             
16117             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
16118               return unify_too_few_arguments (explain_p,
16119                                               TREE_VEC_LENGTH (argvec), len);
16120
16121              for (i = 0; i < len - parm_variadic_p; ++i)
16122               {
16123                 RECUR_AND_CHECK_FAILURE (tparms, targs,
16124                                          TREE_VEC_ELT (parmvec, i),
16125                                          TREE_VEC_ELT (argvec, i),
16126                                          UNIFY_ALLOW_NONE, explain_p);
16127               }
16128
16129             if (parm_variadic_p
16130                 && unify_pack_expansion (tparms, targs,
16131                                          parmvec, argvec,
16132                                          DEDUCE_EXACT,
16133                                          /*subr=*/true, explain_p))
16134               return 1;
16135           }
16136           arg = TYPE_TI_TEMPLATE (arg);
16137
16138           /* Fall through to deduce template name.  */
16139         }
16140
16141       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16142           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16143         {
16144           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16145
16146           /* Simple cases: Value already set, does match or doesn't.  */
16147           if (targ != NULL_TREE && template_args_equal (targ, arg))
16148             return unify_success (explain_p);
16149           else if (targ)
16150             return unify_inconsistency (explain_p, parm, targ, arg);
16151         }
16152       else
16153         {
16154           /* If PARM is `const T' and ARG is only `int', we don't have
16155              a match unless we are allowing additional qualification.
16156              If ARG is `const int' and PARM is just `T' that's OK;
16157              that binds `const int' to `T'.  */
16158           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16159                                          arg, parm))
16160             return unify_cv_qual_mismatch (explain_p, parm, arg);
16161
16162           /* Consider the case where ARG is `const volatile int' and
16163              PARM is `const T'.  Then, T should be `volatile int'.  */
16164           arg = cp_build_qualified_type_real
16165             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16166           if (arg == error_mark_node)
16167             return unify_invalid (explain_p);
16168
16169           /* Simple cases: Value already set, does match or doesn't.  */
16170           if (targ != NULL_TREE && same_type_p (targ, arg))
16171             return unify_success (explain_p);
16172           else if (targ)
16173             return unify_inconsistency (explain_p, parm, targ, arg);
16174
16175           /* Make sure that ARG is not a variable-sized array.  (Note
16176              that were talking about variable-sized arrays (like
16177              `int[n]'), rather than arrays of unknown size (like
16178              `int[]').)  We'll get very confused by such a type since
16179              the bound of the array is not constant, and therefore
16180              not mangleable.  Besides, such types are not allowed in
16181              ISO C++, so we can do as we please here.  We do allow
16182              them for 'auto' deduction, since that isn't ABI-exposed.  */
16183           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16184             return unify_vla_arg (explain_p, arg);
16185
16186           /* Strip typedefs as in convert_template_argument.  */
16187           arg = canonicalize_type_argument (arg, tf_none);
16188         }
16189
16190       /* If ARG is a parameter pack or an expansion, we cannot unify
16191          against it unless PARM is also a parameter pack.  */
16192       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16193           && !template_parameter_pack_p (parm))
16194         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16195
16196       /* If the argument deduction results is a METHOD_TYPE,
16197          then there is a problem.
16198          METHOD_TYPE doesn't map to any real C++ type the result of
16199          the deduction can not be of that type.  */
16200       if (TREE_CODE (arg) == METHOD_TYPE)
16201         return unify_method_type_error (explain_p, arg);
16202
16203       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16204       return unify_success (explain_p);
16205
16206     case TEMPLATE_PARM_INDEX:
16207       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16208       if (tparm == error_mark_node)
16209         return unify_invalid (explain_p);
16210
16211       if (TEMPLATE_PARM_LEVEL (parm)
16212           != template_decl_level (tparm))
16213         {
16214           /* The PARM is not one we're trying to unify.  Just check
16215              to see if it matches ARG.  */
16216           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16217                          && cp_tree_equal (parm, arg));
16218           if (result)
16219             unify_expression_unequal (explain_p, parm, arg);
16220           return result;
16221         }
16222
16223       idx = TEMPLATE_PARM_IDX (parm);
16224       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16225
16226       if (targ)
16227         {
16228           int x = !cp_tree_equal (targ, arg);
16229           if (x)
16230             unify_inconsistency (explain_p, parm, targ, arg);
16231           return x;
16232         }
16233
16234       /* [temp.deduct.type] If, in the declaration of a function template
16235          with a non-type template-parameter, the non-type
16236          template-parameter is used in an expression in the function
16237          parameter-list and, if the corresponding template-argument is
16238          deduced, the template-argument type shall match the type of the
16239          template-parameter exactly, except that a template-argument
16240          deduced from an array bound may be of any integral type.
16241          The non-type parameter might use already deduced type parameters.  */
16242       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16243       if (!TREE_TYPE (arg))
16244         /* Template-parameter dependent expression.  Just accept it for now.
16245            It will later be processed in convert_template_argument.  */
16246         ;
16247       else if (same_type_p (TREE_TYPE (arg), tparm))
16248         /* OK */;
16249       else if ((strict & UNIFY_ALLOW_INTEGER)
16250                && (TREE_CODE (tparm) == INTEGER_TYPE
16251                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16252         /* Convert the ARG to the type of PARM; the deduced non-type
16253            template argument must exactly match the types of the
16254            corresponding parameter.  */
16255         arg = fold (build_nop (tparm, arg));
16256       else if (uses_template_parms (tparm))
16257         /* We haven't deduced the type of this parameter yet.  Try again
16258            later.  */
16259         return unify_success (explain_p);
16260       else
16261         return unify_type_mismatch (explain_p, tparm, arg);
16262
16263       /* If ARG is a parameter pack or an expansion, we cannot unify
16264          against it unless PARM is also a parameter pack.  */
16265       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16266           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16267         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16268
16269       arg = strip_typedefs_expr (arg);
16270       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16271       return unify_success (explain_p);
16272
16273     case PTRMEM_CST:
16274      {
16275         /* A pointer-to-member constant can be unified only with
16276          another constant.  */
16277       if (TREE_CODE (arg) != PTRMEM_CST)
16278         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16279
16280       /* Just unify the class member. It would be useless (and possibly
16281          wrong, depending on the strict flags) to unify also
16282          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16283          arg refer to the same variable, even if through different
16284          classes. For instance:
16285
16286          struct A { int x; };
16287          struct B : A { };
16288
16289          Unification of &A::x and &B::x must succeed.  */
16290       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16291                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16292      }
16293
16294     case POINTER_TYPE:
16295       {
16296         if (TREE_CODE (arg) != POINTER_TYPE)
16297           return unify_type_mismatch (explain_p, parm, arg);
16298
16299         /* [temp.deduct.call]
16300
16301            A can be another pointer or pointer to member type that can
16302            be converted to the deduced A via a qualification
16303            conversion (_conv.qual_).
16304
16305            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16306            This will allow for additional cv-qualification of the
16307            pointed-to types if appropriate.  */
16308
16309         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16310           /* The derived-to-base conversion only persists through one
16311              level of pointers.  */
16312           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16313
16314         return unify (tparms, targs, TREE_TYPE (parm),
16315                       TREE_TYPE (arg), strict, explain_p);
16316       }
16317
16318     case REFERENCE_TYPE:
16319       if (TREE_CODE (arg) != REFERENCE_TYPE)
16320         return unify_type_mismatch (explain_p, parm, arg);
16321       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16322                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16323
16324     case ARRAY_TYPE:
16325       if (TREE_CODE (arg) != ARRAY_TYPE)
16326         return unify_type_mismatch (explain_p, parm, arg);
16327       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16328           != (TYPE_DOMAIN (arg) == NULL_TREE))
16329         return unify_type_mismatch (explain_p, parm, arg);
16330       if (TYPE_DOMAIN (parm) != NULL_TREE)
16331         {
16332           tree parm_max;
16333           tree arg_max;
16334           bool parm_cst;
16335           bool arg_cst;
16336
16337           /* Our representation of array types uses "N - 1" as the
16338              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16339              not an integer constant.  We cannot unify arbitrarily
16340              complex expressions, so we eliminate the MINUS_EXPRs
16341              here.  */
16342           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16343           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16344           if (!parm_cst)
16345             {
16346               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16347               parm_max = TREE_OPERAND (parm_max, 0);
16348             }
16349           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16350           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16351           if (!arg_cst)
16352             {
16353               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16354                  trying to unify the type of a variable with the type
16355                  of a template parameter.  For example:
16356
16357                    template <unsigned int N>
16358                    void f (char (&) [N]);
16359                    int g(); 
16360                    void h(int i) {
16361                      char a[g(i)];
16362                      f(a); 
16363                    }
16364
16365                 Here, the type of the ARG will be "int [g(i)]", and
16366                 may be a SAVE_EXPR, etc.  */
16367               if (TREE_CODE (arg_max) != MINUS_EXPR)
16368                 return unify_vla_arg (explain_p, arg);
16369               arg_max = TREE_OPERAND (arg_max, 0);
16370             }
16371
16372           /* If only one of the bounds used a MINUS_EXPR, compensate
16373              by adding one to the other bound.  */
16374           if (parm_cst && !arg_cst)
16375             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16376                                     integer_type_node,
16377                                     parm_max,
16378                                     integer_one_node);
16379           else if (arg_cst && !parm_cst)
16380             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16381                                    integer_type_node,
16382                                    arg_max,
16383                                    integer_one_node);
16384
16385           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16386                                    UNIFY_ALLOW_INTEGER, explain_p);
16387         }
16388       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16389                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16390
16391     case REAL_TYPE:
16392     case COMPLEX_TYPE:
16393     case VECTOR_TYPE:
16394     case INTEGER_TYPE:
16395     case BOOLEAN_TYPE:
16396     case ENUMERAL_TYPE:
16397     case VOID_TYPE:
16398     case NULLPTR_TYPE:
16399       if (TREE_CODE (arg) != TREE_CODE (parm))
16400         return unify_type_mismatch (explain_p, parm, arg);
16401
16402       /* We have already checked cv-qualification at the top of the
16403          function.  */
16404       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16405         return unify_type_mismatch (explain_p, parm, arg);
16406
16407       /* As far as unification is concerned, this wins.  Later checks
16408          will invalidate it if necessary.  */
16409       return unify_success (explain_p);
16410
16411       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16412       /* Type INTEGER_CST can come from ordinary constant template args.  */
16413     case INTEGER_CST:
16414       while (TREE_CODE (arg) == NOP_EXPR)
16415         arg = TREE_OPERAND (arg, 0);
16416
16417       if (TREE_CODE (arg) != INTEGER_CST)
16418         return unify_template_argument_mismatch (explain_p, parm, arg);
16419       return (tree_int_cst_equal (parm, arg)
16420               ? unify_success (explain_p)
16421               : unify_template_argument_mismatch (explain_p, parm, arg));
16422
16423     case TREE_VEC:
16424       {
16425         int i, len, argslen;
16426         int parm_variadic_p = 0;
16427
16428         if (TREE_CODE (arg) != TREE_VEC)
16429           return unify_template_argument_mismatch (explain_p, parm, arg);
16430
16431         len = TREE_VEC_LENGTH (parm);
16432         argslen = TREE_VEC_LENGTH (arg);
16433
16434         /* Check for pack expansions in the parameters.  */
16435         for (i = 0; i < len; ++i)
16436           {
16437             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16438               {
16439                 if (i == len - 1)
16440                   /* We can unify against something with a trailing
16441                      parameter pack.  */
16442                   parm_variadic_p = 1;
16443                 else
16444                   /* [temp.deduct.type]/9: If the template argument list of
16445                      P contains a pack expansion that is not the last
16446                      template argument, the entire template argument list
16447                      is a non-deduced context.  */
16448                   return unify_success (explain_p);
16449               }
16450           }
16451
16452         /* If we don't have enough arguments to satisfy the parameters
16453            (not counting the pack expression at the end), or we have
16454            too many arguments for a parameter list that doesn't end in
16455            a pack expression, we can't unify.  */
16456         if (parm_variadic_p
16457             ? argslen < len - parm_variadic_p
16458             : argslen != len)
16459           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16460
16461         /* Unify all of the parameters that precede the (optional)
16462            pack expression.  */
16463         for (i = 0; i < len - parm_variadic_p; ++i)
16464           {
16465             RECUR_AND_CHECK_FAILURE (tparms, targs,
16466                                      TREE_VEC_ELT (parm, i),
16467                                      TREE_VEC_ELT (arg, i),
16468                                      UNIFY_ALLOW_NONE, explain_p);
16469           }
16470         if (parm_variadic_p)
16471           return unify_pack_expansion (tparms, targs, parm, arg,
16472                                        DEDUCE_EXACT,
16473                                        /*subr=*/true, explain_p);
16474         return unify_success (explain_p);
16475       }
16476
16477     case RECORD_TYPE:
16478     case UNION_TYPE:
16479       if (TREE_CODE (arg) != TREE_CODE (parm))
16480         return unify_type_mismatch (explain_p, parm, arg);
16481
16482       if (TYPE_PTRMEMFUNC_P (parm))
16483         {
16484           if (!TYPE_PTRMEMFUNC_P (arg))
16485             return unify_type_mismatch (explain_p, parm, arg);
16486
16487           return unify (tparms, targs,
16488                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16489                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16490                         strict, explain_p);
16491         }
16492
16493       if (CLASSTYPE_TEMPLATE_INFO (parm))
16494         {
16495           tree t = NULL_TREE;
16496
16497           if (strict_in & UNIFY_ALLOW_DERIVED)
16498             {
16499               /* First, we try to unify the PARM and ARG directly.  */
16500               t = try_class_unification (tparms, targs,
16501                                          parm, arg, explain_p);
16502
16503               if (!t)
16504                 {
16505                   /* Fallback to the special case allowed in
16506                      [temp.deduct.call]:
16507
16508                        If P is a class, and P has the form
16509                        template-id, then A can be a derived class of
16510                        the deduced A.  Likewise, if P is a pointer to
16511                        a class of the form template-id, A can be a
16512                        pointer to a derived class pointed to by the
16513                        deduced A.  */
16514                   enum template_base_result r;
16515                   r = get_template_base (tparms, targs, parm, arg,
16516                                          explain_p, &t);
16517
16518                   if (!t)
16519                     return unify_no_common_base (explain_p, r, parm, arg);
16520                 }
16521             }
16522           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16523                    && (CLASSTYPE_TI_TEMPLATE (parm)
16524                        == CLASSTYPE_TI_TEMPLATE (arg)))
16525             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16526                Then, we should unify `int' and `U'.  */
16527             t = arg;
16528           else
16529             /* There's no chance of unification succeeding.  */
16530             return unify_type_mismatch (explain_p, parm, arg);
16531
16532           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16533                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16534         }
16535       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16536         return unify_type_mismatch (explain_p, parm, arg);
16537       return unify_success (explain_p);
16538
16539     case METHOD_TYPE:
16540     case FUNCTION_TYPE:
16541       {
16542         unsigned int nargs;
16543         tree *args;
16544         tree a;
16545         unsigned int i;
16546
16547         if (TREE_CODE (arg) != TREE_CODE (parm))
16548           return unify_type_mismatch (explain_p, parm, arg);
16549
16550         /* CV qualifications for methods can never be deduced, they must
16551            match exactly.  We need to check them explicitly here,
16552            because type_unification_real treats them as any other
16553            cv-qualified parameter.  */
16554         if (TREE_CODE (parm) == METHOD_TYPE
16555             && (!check_cv_quals_for_unify
16556                 (UNIFY_ALLOW_NONE,
16557                  class_of_this_parm (arg),
16558                  class_of_this_parm (parm))))
16559           return unify_cv_qual_mismatch (explain_p, parm, arg);
16560
16561         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16562                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16563
16564         nargs = list_length (TYPE_ARG_TYPES (arg));
16565         args = XALLOCAVEC (tree, nargs);
16566         for (a = TYPE_ARG_TYPES (arg), i = 0;
16567              a != NULL_TREE && a != void_list_node;
16568              a = TREE_CHAIN (a), ++i)
16569           args[i] = TREE_VALUE (a);
16570         nargs = i;
16571
16572         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16573                                       args, nargs, 1, DEDUCE_EXACT,
16574                                       LOOKUP_NORMAL, explain_p);
16575       }
16576
16577     case OFFSET_TYPE:
16578       /* Unify a pointer to member with a pointer to member function, which
16579          deduces the type of the member as a function type. */
16580       if (TYPE_PTRMEMFUNC_P (arg))
16581         {
16582           tree method_type;
16583           tree fntype;
16584
16585           /* Check top-level cv qualifiers */
16586           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16587             return unify_cv_qual_mismatch (explain_p, parm, arg);
16588
16589           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16590                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16591                                    UNIFY_ALLOW_NONE, explain_p);
16592
16593           /* Determine the type of the function we are unifying against. */
16594           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16595           fntype =
16596             build_function_type (TREE_TYPE (method_type),
16597                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16598
16599           /* Extract the cv-qualifiers of the member function from the
16600              implicit object parameter and place them on the function
16601              type to be restored later. */
16602           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16603           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16604         }
16605
16606       if (TREE_CODE (arg) != OFFSET_TYPE)
16607         return unify_type_mismatch (explain_p, parm, arg);
16608       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16609                                TYPE_OFFSET_BASETYPE (arg),
16610                                UNIFY_ALLOW_NONE, explain_p);
16611       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16612                     strict, explain_p);
16613
16614     case CONST_DECL:
16615       if (DECL_TEMPLATE_PARM_P (parm))
16616         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16617       if (arg != integral_constant_value (parm))
16618         return unify_template_argument_mismatch (explain_p, parm, arg);
16619       return unify_success (explain_p);
16620
16621     case FIELD_DECL:
16622     case TEMPLATE_DECL:
16623       /* Matched cases are handled by the ARG == PARM test above.  */
16624       return unify_template_argument_mismatch (explain_p, parm, arg);
16625
16626     case VAR_DECL:
16627       /* A non-type template parameter that is a variable should be a
16628          an integral constant, in which case, it whould have been
16629          folded into its (constant) value. So we should not be getting
16630          a variable here.  */
16631       gcc_unreachable ();
16632
16633     case TYPE_ARGUMENT_PACK:
16634     case NONTYPE_ARGUMENT_PACK:
16635       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16636                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16637
16638     case TYPEOF_TYPE:
16639     case DECLTYPE_TYPE:
16640     case UNDERLYING_TYPE:
16641       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16642          or UNDERLYING_TYPE nodes.  */
16643       return unify_success (explain_p);
16644
16645     case ERROR_MARK:
16646       /* Unification fails if we hit an error node.  */
16647       return unify_invalid (explain_p);
16648
16649     default:
16650       /* An unresolved overload is a nondeduced context.  */
16651       if (is_overloaded_fn (parm) || type_unknown_p (parm))
16652         return unify_success (explain_p);
16653       gcc_assert (EXPR_P (parm));
16654
16655       /* We must be looking at an expression.  This can happen with
16656          something like:
16657
16658            template <int I>
16659            void foo(S<I>, S<I + 2>);
16660
16661          This is a "nondeduced context":
16662
16663            [deduct.type]
16664
16665            The nondeduced contexts are:
16666
16667            --A type that is a template-id in which one or more of
16668              the template-arguments is an expression that references
16669              a template-parameter.
16670
16671          In these cases, we assume deduction succeeded, but don't
16672          actually infer any unifications.  */
16673
16674       if (!uses_template_parms (parm)
16675           && !template_args_equal (parm, arg))
16676         return unify_expression_unequal (explain_p, parm, arg);
16677       else
16678         return unify_success (explain_p);
16679     }
16680 }
16681 #undef RECUR_AND_CHECK_FAILURE
16682 \f
16683 /* Note that DECL can be defined in this translation unit, if
16684    required.  */
16685
16686 static void
16687 mark_definable (tree decl)
16688 {
16689   tree clone;
16690   DECL_NOT_REALLY_EXTERN (decl) = 1;
16691   FOR_EACH_CLONE (clone, decl)
16692     DECL_NOT_REALLY_EXTERN (clone) = 1;
16693 }
16694
16695 /* Called if RESULT is explicitly instantiated, or is a member of an
16696    explicitly instantiated class.  */
16697
16698 void
16699 mark_decl_instantiated (tree result, int extern_p)
16700 {
16701   SET_DECL_EXPLICIT_INSTANTIATION (result);
16702
16703   /* If this entity has already been written out, it's too late to
16704      make any modifications.  */
16705   if (TREE_ASM_WRITTEN (result))
16706     return;
16707
16708   if (TREE_CODE (result) != FUNCTION_DECL)
16709     /* The TREE_PUBLIC flag for function declarations will have been
16710        set correctly by tsubst.  */
16711     TREE_PUBLIC (result) = 1;
16712
16713   /* This might have been set by an earlier implicit instantiation.  */
16714   DECL_COMDAT (result) = 0;
16715
16716   if (extern_p)
16717     DECL_NOT_REALLY_EXTERN (result) = 0;
16718   else
16719     {
16720       mark_definable (result);
16721       /* Always make artificials weak.  */
16722       if (DECL_ARTIFICIAL (result) && flag_weak)
16723         comdat_linkage (result);
16724       /* For WIN32 we also want to put explicit instantiations in
16725          linkonce sections.  */
16726       else if (TREE_PUBLIC (result))
16727         maybe_make_one_only (result);
16728     }
16729
16730   /* If EXTERN_P, then this function will not be emitted -- unless
16731      followed by an explicit instantiation, at which point its linkage
16732      will be adjusted.  If !EXTERN_P, then this function will be
16733      emitted here.  In neither circumstance do we want
16734      import_export_decl to adjust the linkage.  */
16735   DECL_INTERFACE_KNOWN (result) = 1;
16736 }
16737
16738 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16739    important template arguments.  If any are missing, we check whether
16740    they're important by using error_mark_node for substituting into any
16741    args that were used for partial ordering (the ones between ARGS and END)
16742    and seeing if it bubbles up.  */
16743
16744 static bool
16745 check_undeduced_parms (tree targs, tree args, tree end)
16746 {
16747   bool found = false;
16748   int i;
16749   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16750     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16751       {
16752         found = true;
16753         TREE_VEC_ELT (targs, i) = error_mark_node;
16754       }
16755   if (found)
16756     {
16757       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
16758       if (substed == error_mark_node)
16759         return true;
16760     }
16761   return false;
16762 }
16763
16764 /* Given two function templates PAT1 and PAT2, return:
16765
16766    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16767    -1 if PAT2 is more specialized than PAT1.
16768    0 if neither is more specialized.
16769
16770    LEN indicates the number of parameters we should consider
16771    (defaulted parameters should not be considered).
16772
16773    The 1998 std underspecified function template partial ordering, and
16774    DR214 addresses the issue.  We take pairs of arguments, one from
16775    each of the templates, and deduce them against each other.  One of
16776    the templates will be more specialized if all the *other*
16777    template's arguments deduce against its arguments and at least one
16778    of its arguments *does* *not* deduce against the other template's
16779    corresponding argument.  Deduction is done as for class templates.
16780    The arguments used in deduction have reference and top level cv
16781    qualifiers removed.  Iff both arguments were originally reference
16782    types *and* deduction succeeds in both directions, the template
16783    with the more cv-qualified argument wins for that pairing (if
16784    neither is more cv-qualified, they both are equal).  Unlike regular
16785    deduction, after all the arguments have been deduced in this way,
16786    we do *not* verify the deduced template argument values can be
16787    substituted into non-deduced contexts.
16788
16789    The logic can be a bit confusing here, because we look at deduce1 and
16790    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16791    can find template arguments for pat1 to make arg1 look like arg2, that
16792    means that arg2 is at least as specialized as arg1.  */
16793
16794 int
16795 more_specialized_fn (tree pat1, tree pat2, int len)
16796 {
16797   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16798   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16799   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16800   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16801   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16802   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16803   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16804   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16805   tree origs1, origs2;
16806   bool lose1 = false;
16807   bool lose2 = false;
16808
16809   /* Remove the this parameter from non-static member functions.  If
16810      one is a non-static member function and the other is not a static
16811      member function, remove the first parameter from that function
16812      also.  This situation occurs for operator functions where we
16813      locate both a member function (with this pointer) and non-member
16814      operator (with explicit first operand).  */
16815   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16816     {
16817       len--; /* LEN is the number of significant arguments for DECL1 */
16818       args1 = TREE_CHAIN (args1);
16819       if (!DECL_STATIC_FUNCTION_P (decl2))
16820         args2 = TREE_CHAIN (args2);
16821     }
16822   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16823     {
16824       args2 = TREE_CHAIN (args2);
16825       if (!DECL_STATIC_FUNCTION_P (decl1))
16826         {
16827           len--;
16828           args1 = TREE_CHAIN (args1);
16829         }
16830     }
16831
16832   /* If only one is a conversion operator, they are unordered.  */
16833   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16834     return 0;
16835
16836   /* Consider the return type for a conversion function */
16837   if (DECL_CONV_FN_P (decl1))
16838     {
16839       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16840       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16841       len++;
16842     }
16843
16844   processing_template_decl++;
16845
16846   origs1 = args1;
16847   origs2 = args2;
16848
16849   while (len--
16850          /* Stop when an ellipsis is seen.  */
16851          && args1 != NULL_TREE && args2 != NULL_TREE)
16852     {
16853       tree arg1 = TREE_VALUE (args1);
16854       tree arg2 = TREE_VALUE (args2);
16855       int deduce1, deduce2;
16856       int quals1 = -1;
16857       int quals2 = -1;
16858
16859       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16860           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16861         {
16862           /* When both arguments are pack expansions, we need only
16863              unify the patterns themselves.  */
16864           arg1 = PACK_EXPANSION_PATTERN (arg1);
16865           arg2 = PACK_EXPANSION_PATTERN (arg2);
16866
16867           /* This is the last comparison we need to do.  */
16868           len = 0;
16869         }
16870
16871       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16872         {
16873           arg1 = TREE_TYPE (arg1);
16874           quals1 = cp_type_quals (arg1);
16875         }
16876
16877       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16878         {
16879           arg2 = TREE_TYPE (arg2);
16880           quals2 = cp_type_quals (arg2);
16881         }
16882
16883       if ((quals1 < 0) != (quals2 < 0))
16884         {
16885           /* Only of the args is a reference, see if we should apply
16886              array/function pointer decay to it.  This is not part of
16887              DR214, but is, IMHO, consistent with the deduction rules
16888              for the function call itself, and with our earlier
16889              implementation of the underspecified partial ordering
16890              rules.  (nathan).  */
16891           if (quals1 >= 0)
16892             {
16893               switch (TREE_CODE (arg1))
16894                 {
16895                 case ARRAY_TYPE:
16896                   arg1 = TREE_TYPE (arg1);
16897                   /* FALLTHROUGH. */
16898                 case FUNCTION_TYPE:
16899                   arg1 = build_pointer_type (arg1);
16900                   break;
16901
16902                 default:
16903                   break;
16904                 }
16905             }
16906           else
16907             {
16908               switch (TREE_CODE (arg2))
16909                 {
16910                 case ARRAY_TYPE:
16911                   arg2 = TREE_TYPE (arg2);
16912                   /* FALLTHROUGH. */
16913                 case FUNCTION_TYPE:
16914                   arg2 = build_pointer_type (arg2);
16915                   break;
16916
16917                 default:
16918                   break;
16919                 }
16920             }
16921         }
16922
16923       arg1 = TYPE_MAIN_VARIANT (arg1);
16924       arg2 = TYPE_MAIN_VARIANT (arg2);
16925
16926       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16927         {
16928           int i, len2 = list_length (args2);
16929           tree parmvec = make_tree_vec (1);
16930           tree argvec = make_tree_vec (len2);
16931           tree ta = args2;
16932
16933           /* Setup the parameter vector, which contains only ARG1.  */
16934           TREE_VEC_ELT (parmvec, 0) = arg1;
16935
16936           /* Setup the argument vector, which contains the remaining
16937              arguments.  */
16938           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16939             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16940
16941           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16942                                            argvec, DEDUCE_EXACT,
16943                                            /*subr=*/true, /*explain_p=*/false)
16944                      == 0);
16945
16946           /* We cannot deduce in the other direction, because ARG1 is
16947              a pack expansion but ARG2 is not.  */
16948           deduce2 = 0;
16949         }
16950       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16951         {
16952           int i, len1 = list_length (args1);
16953           tree parmvec = make_tree_vec (1);
16954           tree argvec = make_tree_vec (len1);
16955           tree ta = args1;
16956
16957           /* Setup the parameter vector, which contains only ARG1.  */
16958           TREE_VEC_ELT (parmvec, 0) = arg2;
16959
16960           /* Setup the argument vector, which contains the remaining
16961              arguments.  */
16962           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16963             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16964
16965           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16966                                            argvec, DEDUCE_EXACT,
16967                                            /*subr=*/true, /*explain_p=*/false)
16968                      == 0);
16969
16970           /* We cannot deduce in the other direction, because ARG2 is
16971              a pack expansion but ARG1 is not.*/
16972           deduce1 = 0;
16973         }
16974
16975       else
16976         {
16977           /* The normal case, where neither argument is a pack
16978              expansion.  */
16979           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16980                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16981                      == 0);
16982           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16983                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16984                      == 0);
16985         }
16986
16987       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16988          arg2, then arg2 is not as specialized as arg1.  */
16989       if (!deduce1)
16990         lose2 = true;
16991       if (!deduce2)
16992         lose1 = true;
16993
16994       /* "If, for a given type, deduction succeeds in both directions
16995          (i.e., the types are identical after the transformations above)
16996          and if the type from the argument template is more cv-qualified
16997          than the type from the parameter template (as described above)
16998          that type is considered to be more specialized than the other. If
16999          neither type is more cv-qualified than the other then neither type
17000          is more specialized than the other."  */
17001
17002       if (deduce1 && deduce2
17003           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
17004         {
17005           if ((quals1 & quals2) == quals2)
17006             lose2 = true;
17007           if ((quals1 & quals2) == quals1)
17008             lose1 = true;
17009         }
17010
17011       if (lose1 && lose2)
17012         /* We've failed to deduce something in either direction.
17013            These must be unordered.  */
17014         break;
17015
17016       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
17017           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17018         /* We have already processed all of the arguments in our
17019            handing of the pack expansion type.  */
17020         len = 0;
17021
17022       args1 = TREE_CHAIN (args1);
17023       args2 = TREE_CHAIN (args2);
17024     }
17025
17026   /* "In most cases, all template parameters must have values in order for
17027      deduction to succeed, but for partial ordering purposes a template
17028      parameter may remain without a value provided it is not used in the
17029      types being used for partial ordering."
17030
17031      Thus, if we are missing any of the targs1 we need to substitute into
17032      origs1, then pat2 is not as specialized as pat1.  This can happen when
17033      there is a nondeduced context.  */
17034   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
17035     lose2 = true;
17036   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
17037     lose1 = true;
17038
17039   processing_template_decl--;
17040
17041   /* All things being equal, if the next argument is a pack expansion
17042      for one function but not for the other, prefer the
17043      non-variadic function.  FIXME this is bogus; see c++/41958.  */
17044   if (lose1 == lose2
17045       && args1 && TREE_VALUE (args1)
17046       && args2 && TREE_VALUE (args2))
17047     {
17048       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
17049       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
17050     }
17051
17052   if (lose1 == lose2)
17053     return 0;
17054   else if (!lose1)
17055     return 1;
17056   else
17057     return -1;
17058 }
17059
17060 /* Determine which of two partial specializations is more specialized.
17061
17062    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
17063    to the first partial specialization.  The TREE_VALUE is the
17064    innermost set of template parameters for the partial
17065    specialization.  PAT2 is similar, but for the second template.
17066
17067    Return 1 if the first partial specialization is more specialized;
17068    -1 if the second is more specialized; 0 if neither is more
17069    specialized.
17070
17071    See [temp.class.order] for information about determining which of
17072    two templates is more specialized.  */
17073
17074 static int
17075 more_specialized_class (tree pat1, tree pat2)
17076 {
17077   tree targs;
17078   tree tmpl1, tmpl2;
17079   int winner = 0;
17080   bool any_deductions = false;
17081
17082   tmpl1 = TREE_TYPE (pat1);
17083   tmpl2 = TREE_TYPE (pat2);
17084
17085   /* Just like what happens for functions, if we are ordering between
17086      different class template specializations, we may encounter dependent
17087      types in the arguments, and we need our dependency check functions
17088      to behave correctly.  */
17089   ++processing_template_decl;
17090   targs = get_class_bindings (TREE_VALUE (pat1),
17091                               CLASSTYPE_TI_ARGS (tmpl1),
17092                               CLASSTYPE_TI_ARGS (tmpl2));
17093   if (targs)
17094     {
17095       --winner;
17096       any_deductions = true;
17097     }
17098
17099   targs = get_class_bindings (TREE_VALUE (pat2),
17100                               CLASSTYPE_TI_ARGS (tmpl2),
17101                               CLASSTYPE_TI_ARGS (tmpl1));
17102   if (targs)
17103     {
17104       ++winner;
17105       any_deductions = true;
17106     }
17107   --processing_template_decl;
17108
17109   /* In the case of a tie where at least one of the class templates
17110      has a parameter pack at the end, the template with the most
17111      non-packed parameters wins.  */
17112   if (winner == 0
17113       && any_deductions
17114       && (template_args_variadic_p (TREE_PURPOSE (pat1))
17115           || template_args_variadic_p (TREE_PURPOSE (pat2))))
17116     {
17117       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
17118       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
17119       int len1 = TREE_VEC_LENGTH (args1);
17120       int len2 = TREE_VEC_LENGTH (args2);
17121
17122       /* We don't count the pack expansion at the end.  */
17123       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
17124         --len1;
17125       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
17126         --len2;
17127
17128       if (len1 > len2)
17129         return 1;
17130       else if (len1 < len2)
17131         return -1;
17132     }
17133
17134   return winner;
17135 }
17136
17137 /* Return the template arguments that will produce the function signature
17138    DECL from the function template FN, with the explicit template
17139    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17140    also match.  Return NULL_TREE if no satisfactory arguments could be
17141    found.  */
17142
17143 static tree
17144 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17145 {
17146   int ntparms = DECL_NTPARMS (fn);
17147   tree targs = make_tree_vec (ntparms);
17148   tree decl_type;
17149   tree decl_arg_types;
17150   tree *args;
17151   unsigned int nargs, ix;
17152   tree arg;
17153
17154   /* Substitute the explicit template arguments into the type of DECL.
17155      The call to fn_type_unification will handle substitution into the
17156      FN.  */
17157   decl_type = TREE_TYPE (decl);
17158   if (explicit_args && uses_template_parms (decl_type))
17159     {
17160       tree tmpl;
17161       tree converted_args;
17162
17163       if (DECL_TEMPLATE_INFO (decl))
17164         tmpl = DECL_TI_TEMPLATE (decl);
17165       else
17166         /* We can get here for some invalid specializations.  */
17167         return NULL_TREE;
17168
17169       converted_args
17170         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17171                                  explicit_args, NULL_TREE,
17172                                  tf_none,
17173                                  /*require_all_args=*/false,
17174                                  /*use_default_args=*/false);
17175       if (converted_args == error_mark_node)
17176         return NULL_TREE;
17177
17178       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17179       if (decl_type == error_mark_node)
17180         return NULL_TREE;
17181     }
17182
17183   /* Never do unification on the 'this' parameter.  */
17184   decl_arg_types = skip_artificial_parms_for (decl, 
17185                                               TYPE_ARG_TYPES (decl_type));
17186
17187   nargs = list_length (decl_arg_types);
17188   args = XALLOCAVEC (tree, nargs);
17189   for (arg = decl_arg_types, ix = 0;
17190        arg != NULL_TREE && arg != void_list_node;
17191        arg = TREE_CHAIN (arg), ++ix)
17192     args[ix] = TREE_VALUE (arg);
17193
17194   if (fn_type_unification (fn, explicit_args, targs,
17195                            args, ix,
17196                            (check_rettype || DECL_CONV_FN_P (fn)
17197                             ? TREE_TYPE (decl_type) : NULL_TREE),
17198                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17199     return NULL_TREE;
17200
17201   return targs;
17202 }
17203
17204 /* Return the innermost template arguments that, when applied to a
17205    template specialization whose innermost template parameters are
17206    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17207    ARGS.
17208
17209    For example, suppose we have:
17210
17211      template <class T, class U> struct S {};
17212      template <class T> struct S<T*, int> {};
17213
17214    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17215    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17216    int}.  The resulting vector will be {double}, indicating that `T'
17217    is bound to `double'.  */
17218
17219 static tree
17220 get_class_bindings (tree tparms, tree spec_args, tree args)
17221 {
17222   int i, ntparms = TREE_VEC_LENGTH (tparms);
17223   tree deduced_args;
17224   tree innermost_deduced_args;
17225
17226   innermost_deduced_args = make_tree_vec (ntparms);
17227   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17228     {
17229       deduced_args = copy_node (args);
17230       SET_TMPL_ARGS_LEVEL (deduced_args,
17231                            TMPL_ARGS_DEPTH (deduced_args),
17232                            innermost_deduced_args);
17233     }
17234   else
17235     deduced_args = innermost_deduced_args;
17236
17237   if (unify (tparms, deduced_args,
17238              INNERMOST_TEMPLATE_ARGS (spec_args),
17239              INNERMOST_TEMPLATE_ARGS (args),
17240              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17241     return NULL_TREE;
17242
17243   for (i =  0; i < ntparms; ++i)
17244     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17245       return NULL_TREE;
17246
17247   /* Verify that nondeduced template arguments agree with the type
17248      obtained from argument deduction.
17249
17250      For example:
17251
17252        struct A { typedef int X; };
17253        template <class T, class U> struct C {};
17254        template <class T> struct C<T, typename T::X> {};
17255
17256      Then with the instantiation `C<A, int>', we can deduce that
17257      `T' is `A' but unify () does not check whether `typename T::X'
17258      is `int'.  */
17259   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17260   if (spec_args == error_mark_node
17261       /* We only need to check the innermost arguments; the other
17262          arguments will always agree.  */
17263       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17264                               INNERMOST_TEMPLATE_ARGS (args)))
17265     return NULL_TREE;
17266
17267   /* Now that we have bindings for all of the template arguments,
17268      ensure that the arguments deduced for the template template
17269      parameters have compatible template parameter lists.  See the use
17270      of template_template_parm_bindings_ok_p in fn_type_unification
17271      for more information.  */
17272   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17273     return NULL_TREE;
17274
17275   return deduced_args;
17276 }
17277
17278 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17279    Return the TREE_LIST node with the most specialized template, if
17280    any.  If there is no most specialized template, the error_mark_node
17281    is returned.
17282
17283    Note that this function does not look at, or modify, the
17284    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17285    returned is one of the elements of INSTANTIATIONS, callers may
17286    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17287    and retrieve it from the value returned.  */
17288
17289 tree
17290 most_specialized_instantiation (tree templates)
17291 {
17292   tree fn, champ;
17293
17294   ++processing_template_decl;
17295
17296   champ = templates;
17297   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17298     {
17299       int fate = 0;
17300
17301       if (get_bindings (TREE_VALUE (champ),
17302                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17303                         NULL_TREE, /*check_ret=*/true))
17304         fate--;
17305
17306       if (get_bindings (TREE_VALUE (fn),
17307                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17308                         NULL_TREE, /*check_ret=*/true))
17309         fate++;
17310
17311       if (fate == -1)
17312         champ = fn;
17313       else if (!fate)
17314         {
17315           /* Equally specialized, move to next function.  If there
17316              is no next function, nothing's most specialized.  */
17317           fn = TREE_CHAIN (fn);
17318           champ = fn;
17319           if (!fn)
17320             break;
17321         }
17322     }
17323
17324   if (champ)
17325     /* Now verify that champ is better than everything earlier in the
17326        instantiation list.  */
17327     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17328       if (get_bindings (TREE_VALUE (champ),
17329                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17330                         NULL_TREE, /*check_ret=*/true)
17331           || !get_bindings (TREE_VALUE (fn),
17332                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17333                             NULL_TREE, /*check_ret=*/true))
17334         {
17335           champ = NULL_TREE;
17336           break;
17337         }
17338
17339   processing_template_decl--;
17340
17341   if (!champ)
17342     return error_mark_node;
17343
17344   return champ;
17345 }
17346
17347 /* If DECL is a specialization of some template, return the most
17348    general such template.  Otherwise, returns NULL_TREE.
17349
17350    For example, given:
17351
17352      template <class T> struct S { template <class U> void f(U); };
17353
17354    if TMPL is `template <class U> void S<int>::f(U)' this will return
17355    the full template.  This function will not trace past partial
17356    specializations, however.  For example, given in addition:
17357
17358      template <class T> struct S<T*> { template <class U> void f(U); };
17359
17360    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17361    `template <class T> template <class U> S<T*>::f(U)'.  */
17362
17363 tree
17364 most_general_template (tree decl)
17365 {
17366   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17367      an immediate specialization.  */
17368   if (TREE_CODE (decl) == FUNCTION_DECL)
17369     {
17370       if (DECL_TEMPLATE_INFO (decl)) {
17371         decl = DECL_TI_TEMPLATE (decl);
17372
17373         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17374            template friend.  */
17375         if (TREE_CODE (decl) != TEMPLATE_DECL)
17376           return NULL_TREE;
17377       } else
17378         return NULL_TREE;
17379     }
17380
17381   /* Look for more and more general templates.  */
17382   while (DECL_TEMPLATE_INFO (decl))
17383     {
17384       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17385          (See cp-tree.h for details.)  */
17386       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17387         break;
17388
17389       if (CLASS_TYPE_P (TREE_TYPE (decl))
17390           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17391         break;
17392
17393       /* Stop if we run into an explicitly specialized class template.  */
17394       if (!DECL_NAMESPACE_SCOPE_P (decl)
17395           && DECL_CONTEXT (decl)
17396           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17397         break;
17398
17399       decl = DECL_TI_TEMPLATE (decl);
17400     }
17401
17402   return decl;
17403 }
17404
17405 /* Return the most specialized of the class template partial
17406    specializations of TMPL which can produce TYPE, a specialization of
17407    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17408    a _TYPE node corresponding to the partial specialization, while the
17409    TREE_PURPOSE is the set of template arguments that must be
17410    substituted into the TREE_TYPE in order to generate TYPE.
17411
17412    If the choice of partial specialization is ambiguous, a diagnostic
17413    is issued, and the error_mark_node is returned.  If there are no
17414    partial specializations of TMPL matching TYPE, then NULL_TREE is
17415    returned.  */
17416
17417 static tree
17418 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17419 {
17420   tree list = NULL_TREE;
17421   tree t;
17422   tree champ;
17423   int fate;
17424   bool ambiguous_p;
17425   tree args;
17426   tree outer_args = NULL_TREE;
17427
17428   tmpl = most_general_template (tmpl);
17429   args = CLASSTYPE_TI_ARGS (type);
17430
17431   /* For determining which partial specialization to use, only the
17432      innermost args are interesting.  */
17433   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17434     {
17435       outer_args = strip_innermost_template_args (args, 1);
17436       args = INNERMOST_TEMPLATE_ARGS (args);
17437     }
17438
17439   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17440     {
17441       tree partial_spec_args;
17442       tree spec_args;
17443       tree parms = TREE_VALUE (t);
17444
17445       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17446
17447       ++processing_template_decl;
17448
17449       if (outer_args)
17450         {
17451           int i;
17452
17453           /* Discard the outer levels of args, and then substitute in the
17454              template args from the enclosing class.  */
17455           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17456           partial_spec_args = tsubst_template_args
17457             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17458
17459           /* PARMS already refers to just the innermost parms, but the
17460              template parms in partial_spec_args had their levels lowered
17461              by tsubst, so we need to do the same for the parm list.  We
17462              can't just tsubst the TREE_VEC itself, as tsubst wants to
17463              treat a TREE_VEC as an argument vector.  */
17464           parms = copy_node (parms);
17465           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17466             TREE_VEC_ELT (parms, i) =
17467               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17468
17469         }
17470
17471       partial_spec_args =
17472           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17473                                  add_to_template_args (outer_args,
17474                                                        partial_spec_args),
17475                                  tmpl, tf_none,
17476                                  /*require_all_args=*/true,
17477                                  /*use_default_args=*/true);
17478
17479       --processing_template_decl;
17480
17481       if (partial_spec_args == error_mark_node)
17482         return error_mark_node;
17483
17484       spec_args = get_class_bindings (parms,
17485                                       partial_spec_args,
17486                                       args);
17487       if (spec_args)
17488         {
17489           if (outer_args)
17490             spec_args = add_to_template_args (outer_args, spec_args);
17491           list = tree_cons (spec_args, TREE_VALUE (t), list);
17492           TREE_TYPE (list) = TREE_TYPE (t);
17493         }
17494     }
17495
17496   if (! list)
17497     return NULL_TREE;
17498
17499   ambiguous_p = false;
17500   t = list;
17501   champ = t;
17502   t = TREE_CHAIN (t);
17503   for (; t; t = TREE_CHAIN (t))
17504     {
17505       fate = more_specialized_class (champ, t);
17506       if (fate == 1)
17507         ;
17508       else
17509         {
17510           if (fate == 0)
17511             {
17512               t = TREE_CHAIN (t);
17513               if (! t)
17514                 {
17515                   ambiguous_p = true;
17516                   break;
17517                 }
17518             }
17519           champ = t;
17520         }
17521     }
17522
17523   if (!ambiguous_p)
17524     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17525       {
17526         fate = more_specialized_class (champ, t);
17527         if (fate != 1)
17528           {
17529             ambiguous_p = true;
17530             break;
17531           }
17532       }
17533
17534   if (ambiguous_p)
17535     {
17536       const char *str;
17537       char *spaces = NULL;
17538       if (!(complain & tf_error))
17539         return error_mark_node;
17540       error ("ambiguous class template instantiation for %q#T", type);
17541       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17542       for (t = list; t; t = TREE_CHAIN (t))
17543         {
17544           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17545           spaces = spaces ? spaces : get_spaces (str);
17546         }
17547       free (spaces);
17548       return error_mark_node;
17549     }
17550
17551   return champ;
17552 }
17553
17554 /* Explicitly instantiate DECL.  */
17555
17556 void
17557 do_decl_instantiation (tree decl, tree storage)
17558 {
17559   tree result = NULL_TREE;
17560   int extern_p = 0;
17561
17562   if (!decl || decl == error_mark_node)
17563     /* An error occurred, for which grokdeclarator has already issued
17564        an appropriate message.  */
17565     return;
17566   else if (! DECL_LANG_SPECIFIC (decl))
17567     {
17568       error ("explicit instantiation of non-template %q#D", decl);
17569       return;
17570     }
17571   else if (TREE_CODE (decl) == VAR_DECL)
17572     {
17573       /* There is an asymmetry here in the way VAR_DECLs and
17574          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17575          the latter, the DECL we get back will be marked as a
17576          template instantiation, and the appropriate
17577          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17578          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17579          should handle VAR_DECLs as it currently handles
17580          FUNCTION_DECLs.  */
17581       if (!DECL_CLASS_SCOPE_P (decl))
17582         {
17583           error ("%qD is not a static data member of a class template", decl);
17584           return;
17585         }
17586       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17587       if (!result || TREE_CODE (result) != VAR_DECL)
17588         {
17589           error ("no matching template for %qD found", decl);
17590           return;
17591         }
17592       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17593         {
17594           error ("type %qT for explicit instantiation %qD does not match "
17595                  "declared type %qT", TREE_TYPE (result), decl,
17596                  TREE_TYPE (decl));
17597           return;
17598         }
17599     }
17600   else if (TREE_CODE (decl) != FUNCTION_DECL)
17601     {
17602       error ("explicit instantiation of %q#D", decl);
17603       return;
17604     }
17605   else
17606     result = decl;
17607
17608   /* Check for various error cases.  Note that if the explicit
17609      instantiation is valid the RESULT will currently be marked as an
17610      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17611      until we get here.  */
17612
17613   if (DECL_TEMPLATE_SPECIALIZATION (result))
17614     {
17615       /* DR 259 [temp.spec].
17616
17617          Both an explicit instantiation and a declaration of an explicit
17618          specialization shall not appear in a program unless the explicit
17619          instantiation follows a declaration of the explicit specialization.
17620
17621          For a given set of template parameters, if an explicit
17622          instantiation of a template appears after a declaration of an
17623          explicit specialization for that template, the explicit
17624          instantiation has no effect.  */
17625       return;
17626     }
17627   else if (DECL_EXPLICIT_INSTANTIATION (result))
17628     {
17629       /* [temp.spec]
17630
17631          No program shall explicitly instantiate any template more
17632          than once.
17633
17634          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17635          the first instantiation was `extern' and the second is not,
17636          and EXTERN_P for the opposite case.  */
17637       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17638         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17639       /* If an "extern" explicit instantiation follows an ordinary
17640          explicit instantiation, the template is instantiated.  */
17641       if (extern_p)
17642         return;
17643     }
17644   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17645     {
17646       error ("no matching template for %qD found", result);
17647       return;
17648     }
17649   else if (!DECL_TEMPLATE_INFO (result))
17650     {
17651       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17652       return;
17653     }
17654
17655   if (storage == NULL_TREE)
17656     ;
17657   else if (storage == ridpointers[(int) RID_EXTERN])
17658     {
17659       if (!in_system_header && (cxx_dialect == cxx98))
17660         pedwarn (input_location, OPT_pedantic, 
17661                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17662                  "instantiations");
17663       extern_p = 1;
17664     }
17665   else
17666     error ("storage class %qD applied to template instantiation", storage);
17667
17668   check_explicit_instantiation_namespace (result);
17669   mark_decl_instantiated (result, extern_p);
17670   if (! extern_p)
17671     instantiate_decl (result, /*defer_ok=*/1,
17672                       /*expl_inst_class_mem_p=*/false);
17673 }
17674
17675 static void
17676 mark_class_instantiated (tree t, int extern_p)
17677 {
17678   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17679   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17680   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17681   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17682   if (! extern_p)
17683     {
17684       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17685       rest_of_type_compilation (t, 1);
17686     }
17687 }
17688
17689 /* Called from do_type_instantiation through binding_table_foreach to
17690    do recursive instantiation for the type bound in ENTRY.  */
17691 static void
17692 bt_instantiate_type_proc (binding_entry entry, void *data)
17693 {
17694   tree storage = *(tree *) data;
17695
17696   if (MAYBE_CLASS_TYPE_P (entry->type)
17697       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17698     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17699 }
17700
17701 /* Called from do_type_instantiation to instantiate a member
17702    (a member function or a static member variable) of an
17703    explicitly instantiated class template.  */
17704 static void
17705 instantiate_class_member (tree decl, int extern_p)
17706 {
17707   mark_decl_instantiated (decl, extern_p);
17708   if (! extern_p)
17709     instantiate_decl (decl, /*defer_ok=*/1,
17710                       /*expl_inst_class_mem_p=*/true);
17711 }
17712
17713 /* Perform an explicit instantiation of template class T.  STORAGE, if
17714    non-null, is the RID for extern, inline or static.  COMPLAIN is
17715    nonzero if this is called from the parser, zero if called recursively,
17716    since the standard is unclear (as detailed below).  */
17717
17718 void
17719 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17720 {
17721   int extern_p = 0;
17722   int nomem_p = 0;
17723   int static_p = 0;
17724   int previous_instantiation_extern_p = 0;
17725
17726   if (TREE_CODE (t) == TYPE_DECL)
17727     t = TREE_TYPE (t);
17728
17729   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17730     {
17731       tree tmpl =
17732         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
17733       if (tmpl)
17734         error ("explicit instantiation of non-class template %qD", tmpl);
17735       else
17736         error ("explicit instantiation of non-template type %qT", t);
17737       return;
17738     }
17739
17740   complete_type (t);
17741
17742   if (!COMPLETE_TYPE_P (t))
17743     {
17744       if (complain & tf_error)
17745         error ("explicit instantiation of %q#T before definition of template",
17746                t);
17747       return;
17748     }
17749
17750   if (storage != NULL_TREE)
17751     {
17752       if (!in_system_header)
17753         {
17754           if (storage == ridpointers[(int) RID_EXTERN])
17755             {
17756               if (cxx_dialect == cxx98)
17757                 pedwarn (input_location, OPT_pedantic, 
17758                          "ISO C++ 1998 forbids the use of %<extern%> on "
17759                          "explicit instantiations");
17760             }
17761           else
17762             pedwarn (input_location, OPT_pedantic, 
17763                      "ISO C++ forbids the use of %qE"
17764                      " on explicit instantiations", storage);
17765         }
17766
17767       if (storage == ridpointers[(int) RID_INLINE])
17768         nomem_p = 1;
17769       else if (storage == ridpointers[(int) RID_EXTERN])
17770         extern_p = 1;
17771       else if (storage == ridpointers[(int) RID_STATIC])
17772         static_p = 1;
17773       else
17774         {
17775           error ("storage class %qD applied to template instantiation",
17776                  storage);
17777           extern_p = 0;
17778         }
17779     }
17780
17781   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17782     {
17783       /* DR 259 [temp.spec].
17784
17785          Both an explicit instantiation and a declaration of an explicit
17786          specialization shall not appear in a program unless the explicit
17787          instantiation follows a declaration of the explicit specialization.
17788
17789          For a given set of template parameters, if an explicit
17790          instantiation of a template appears after a declaration of an
17791          explicit specialization for that template, the explicit
17792          instantiation has no effect.  */
17793       return;
17794     }
17795   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17796     {
17797       /* [temp.spec]
17798
17799          No program shall explicitly instantiate any template more
17800          than once.
17801
17802          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17803          instantiation was `extern'.  If EXTERN_P then the second is.
17804          These cases are OK.  */
17805       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17806
17807       if (!previous_instantiation_extern_p && !extern_p
17808           && (complain & tf_error))
17809         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17810
17811       /* If we've already instantiated the template, just return now.  */
17812       if (!CLASSTYPE_INTERFACE_ONLY (t))
17813         return;
17814     }
17815
17816   check_explicit_instantiation_namespace (TYPE_NAME (t));
17817   mark_class_instantiated (t, extern_p);
17818
17819   if (nomem_p)
17820     return;
17821
17822   {
17823     tree tmp;
17824
17825     /* In contrast to implicit instantiation, where only the
17826        declarations, and not the definitions, of members are
17827        instantiated, we have here:
17828
17829          [temp.explicit]
17830
17831          The explicit instantiation of a class template specialization
17832          implies the instantiation of all of its members not
17833          previously explicitly specialized in the translation unit
17834          containing the explicit instantiation.
17835
17836        Of course, we can't instantiate member template classes, since
17837        we don't have any arguments for them.  Note that the standard
17838        is unclear on whether the instantiation of the members are
17839        *explicit* instantiations or not.  However, the most natural
17840        interpretation is that it should be an explicit instantiation.  */
17841
17842     if (! static_p)
17843       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17844         if (TREE_CODE (tmp) == FUNCTION_DECL
17845             && DECL_TEMPLATE_INSTANTIATION (tmp))
17846           instantiate_class_member (tmp, extern_p);
17847
17848     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17849       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17850         instantiate_class_member (tmp, extern_p);
17851
17852     if (CLASSTYPE_NESTED_UTDS (t))
17853       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17854                              bt_instantiate_type_proc, &storage);
17855   }
17856 }
17857
17858 /* Given a function DECL, which is a specialization of TMPL, modify
17859    DECL to be a re-instantiation of TMPL with the same template
17860    arguments.  TMPL should be the template into which tsubst'ing
17861    should occur for DECL, not the most general template.
17862
17863    One reason for doing this is a scenario like this:
17864
17865      template <class T>
17866      void f(const T&, int i);
17867
17868      void g() { f(3, 7); }
17869
17870      template <class T>
17871      void f(const T& t, const int i) { }
17872
17873    Note that when the template is first instantiated, with
17874    instantiate_template, the resulting DECL will have no name for the
17875    first parameter, and the wrong type for the second.  So, when we go
17876    to instantiate the DECL, we regenerate it.  */
17877
17878 static void
17879 regenerate_decl_from_template (tree decl, tree tmpl)
17880 {
17881   /* The arguments used to instantiate DECL, from the most general
17882      template.  */
17883   tree args;
17884   tree code_pattern;
17885
17886   args = DECL_TI_ARGS (decl);
17887   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17888
17889   /* Make sure that we can see identifiers, and compute access
17890      correctly.  */
17891   push_access_scope (decl);
17892
17893   if (TREE_CODE (decl) == FUNCTION_DECL)
17894     {
17895       tree decl_parm;
17896       tree pattern_parm;
17897       tree specs;
17898       int args_depth;
17899       int parms_depth;
17900
17901       args_depth = TMPL_ARGS_DEPTH (args);
17902       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17903       if (args_depth > parms_depth)
17904         args = get_innermost_template_args (args, parms_depth);
17905
17906       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17907                                               args, tf_error, NULL_TREE,
17908                                               /*defer_ok*/false);
17909       if (specs && specs != error_mark_node)
17910         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17911                                                     specs);
17912
17913       /* Merge parameter declarations.  */
17914       decl_parm = skip_artificial_parms_for (decl,
17915                                              DECL_ARGUMENTS (decl));
17916       pattern_parm
17917         = skip_artificial_parms_for (code_pattern,
17918                                      DECL_ARGUMENTS (code_pattern));
17919       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17920         {
17921           tree parm_type;
17922           tree attributes;
17923           
17924           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17925             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17926           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17927                               NULL_TREE);
17928           parm_type = type_decays_to (parm_type);
17929           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17930             TREE_TYPE (decl_parm) = parm_type;
17931           attributes = DECL_ATTRIBUTES (pattern_parm);
17932           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17933             {
17934               DECL_ATTRIBUTES (decl_parm) = attributes;
17935               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17936             }
17937           decl_parm = DECL_CHAIN (decl_parm);
17938           pattern_parm = DECL_CHAIN (pattern_parm);
17939         }
17940       /* Merge any parameters that match with the function parameter
17941          pack.  */
17942       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17943         {
17944           int i, len;
17945           tree expanded_types;
17946           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17947              the parameters in this function parameter pack.  */
17948           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17949                                                  args, tf_error, NULL_TREE);
17950           len = TREE_VEC_LENGTH (expanded_types);
17951           for (i = 0; i < len; i++)
17952             {
17953               tree parm_type;
17954               tree attributes;
17955           
17956               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17957                 /* Rename the parameter to include the index.  */
17958                 DECL_NAME (decl_parm) = 
17959                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17960               parm_type = TREE_VEC_ELT (expanded_types, i);
17961               parm_type = type_decays_to (parm_type);
17962               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17963                 TREE_TYPE (decl_parm) = parm_type;
17964               attributes = DECL_ATTRIBUTES (pattern_parm);
17965               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17966                 {
17967                   DECL_ATTRIBUTES (decl_parm) = attributes;
17968                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17969                 }
17970               decl_parm = DECL_CHAIN (decl_parm);
17971             }
17972         }
17973       /* Merge additional specifiers from the CODE_PATTERN.  */
17974       if (DECL_DECLARED_INLINE_P (code_pattern)
17975           && !DECL_DECLARED_INLINE_P (decl))
17976         DECL_DECLARED_INLINE_P (decl) = 1;
17977     }
17978   else if (TREE_CODE (decl) == VAR_DECL)
17979     {
17980       DECL_INITIAL (decl) =
17981         tsubst_expr (DECL_INITIAL (code_pattern), args,
17982                      tf_error, DECL_TI_TEMPLATE (decl),
17983                      /*integral_constant_expression_p=*/false);
17984       if (VAR_HAD_UNKNOWN_BOUND (decl))
17985         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17986                                    tf_error, DECL_TI_TEMPLATE (decl));
17987     }
17988   else
17989     gcc_unreachable ();
17990
17991   pop_access_scope (decl);
17992 }
17993
17994 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
17995    substituted to get DECL.  */
17996
17997 tree
17998 template_for_substitution (tree decl)
17999 {
18000   tree tmpl = DECL_TI_TEMPLATE (decl);
18001
18002   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
18003      for the instantiation.  This is not always the most general
18004      template.  Consider, for example:
18005
18006         template <class T>
18007         struct S { template <class U> void f();
18008                    template <> void f<int>(); };
18009
18010      and an instantiation of S<double>::f<int>.  We want TD to be the
18011      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
18012   while (/* An instantiation cannot have a definition, so we need a
18013             more general template.  */
18014          DECL_TEMPLATE_INSTANTIATION (tmpl)
18015            /* We must also deal with friend templates.  Given:
18016
18017                 template <class T> struct S {
18018                   template <class U> friend void f() {};
18019                 };
18020
18021               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
18022               so far as the language is concerned, but that's still
18023               where we get the pattern for the instantiation from.  On
18024               other hand, if the definition comes outside the class, say:
18025
18026                 template <class T> struct S {
18027                   template <class U> friend void f();
18028                 };
18029                 template <class U> friend void f() {}
18030
18031               we don't need to look any further.  That's what the check for
18032               DECL_INITIAL is for.  */
18033           || (TREE_CODE (decl) == FUNCTION_DECL
18034               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
18035               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
18036     {
18037       /* The present template, TD, should not be a definition.  If it
18038          were a definition, we should be using it!  Note that we
18039          cannot restructure the loop to just keep going until we find
18040          a template with a definition, since that might go too far if
18041          a specialization was declared, but not defined.  */
18042       gcc_assert (TREE_CODE (decl) != VAR_DECL
18043                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
18044
18045       /* Fetch the more general template.  */
18046       tmpl = DECL_TI_TEMPLATE (tmpl);
18047     }
18048
18049   return tmpl;
18050 }
18051
18052 /* Returns true if we need to instantiate this template instance even if we
18053    know we aren't going to emit it..  */
18054
18055 bool
18056 always_instantiate_p (tree decl)
18057 {
18058   /* We always instantiate inline functions so that we can inline them.  An
18059      explicit instantiation declaration prohibits implicit instantiation of
18060      non-inline functions.  With high levels of optimization, we would
18061      normally inline non-inline functions -- but we're not allowed to do
18062      that for "extern template" functions.  Therefore, we check
18063      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
18064   return ((TREE_CODE (decl) == FUNCTION_DECL
18065            && DECL_DECLARED_INLINE_P (decl))
18066           /* And we need to instantiate static data members so that
18067              their initializers are available in integral constant
18068              expressions.  */
18069           || (TREE_CODE (decl) == VAR_DECL
18070               && decl_maybe_constant_var_p (decl)));
18071 }
18072
18073 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
18074    instantiate it now, modifying TREE_TYPE (fn).  */
18075
18076 void
18077 maybe_instantiate_noexcept (tree fn)
18078 {
18079   tree fntype, spec, noex, clone;
18080
18081   if (DECL_CLONED_FUNCTION_P (fn))
18082     fn = DECL_CLONED_FUNCTION (fn);
18083   fntype = TREE_TYPE (fn);
18084   spec = TYPE_RAISES_EXCEPTIONS (fntype);
18085
18086   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
18087     return;
18088
18089   noex = TREE_PURPOSE (spec);
18090
18091   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
18092     {
18093       if (push_tinst_level (fn))
18094         {
18095           push_access_scope (fn);
18096           input_location = DECL_SOURCE_LOCATION (fn);
18097           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
18098                                         DEFERRED_NOEXCEPT_ARGS (noex),
18099                                         tf_warning_or_error, fn,
18100                                         /*function_p=*/false,
18101                                         /*integral_constant_expression_p=*/true);
18102           pop_access_scope (fn);
18103           pop_tinst_level ();
18104           spec = build_noexcept_spec (noex, tf_warning_or_error);
18105           if (spec == error_mark_node)
18106             spec = noexcept_false_spec;
18107         }
18108       else
18109         spec = noexcept_false_spec;
18110     }
18111   else
18112     {
18113       /* This is an implicitly declared function, so NOEX is a list of
18114          other functions to evaluate and merge.  */
18115       tree elt;
18116       spec = noexcept_true_spec;
18117       for (elt = noex; elt; elt = OVL_NEXT (elt))
18118         {
18119           tree fn = OVL_CURRENT (elt);
18120           tree subspec;
18121           maybe_instantiate_noexcept (fn);
18122           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
18123           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
18124         }
18125     }
18126
18127   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
18128
18129   FOR_EACH_CLONE (clone, fn)
18130     {
18131       if (TREE_TYPE (clone) == fntype)
18132         TREE_TYPE (clone) = TREE_TYPE (fn);
18133       else
18134         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
18135     }
18136 }
18137
18138 /* Produce the definition of D, a _DECL generated from a template.  If
18139    DEFER_OK is nonzero, then we don't have to actually do the
18140    instantiation now; we just have to do it sometime.  Normally it is
18141    an error if this is an explicit instantiation but D is undefined.
18142    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
18143    explicitly instantiated class template.  */
18144
18145 tree
18146 instantiate_decl (tree d, int defer_ok,
18147                   bool expl_inst_class_mem_p)
18148 {
18149   tree tmpl = DECL_TI_TEMPLATE (d);
18150   tree gen_args;
18151   tree args;
18152   tree td;
18153   tree code_pattern;
18154   tree spec;
18155   tree gen_tmpl;
18156   bool pattern_defined;
18157   location_t saved_loc = input_location;
18158   bool external_p;
18159   tree fn_context;
18160   bool nested;
18161
18162   /* This function should only be used to instantiate templates for
18163      functions and static member variables.  */
18164   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18165               || TREE_CODE (d) == VAR_DECL);
18166
18167   /* Variables are never deferred; if instantiation is required, they
18168      are instantiated right away.  That allows for better code in the
18169      case that an expression refers to the value of the variable --
18170      if the variable has a constant value the referring expression can
18171      take advantage of that fact.  */
18172   if (TREE_CODE (d) == VAR_DECL
18173       || DECL_DECLARED_CONSTEXPR_P (d))
18174     defer_ok = 0;
18175
18176   /* Don't instantiate cloned functions.  Instead, instantiate the
18177      functions they cloned.  */
18178   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18179     d = DECL_CLONED_FUNCTION (d);
18180
18181   if (DECL_TEMPLATE_INSTANTIATED (d)
18182       || (TREE_CODE (d) == FUNCTION_DECL
18183           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
18184       || DECL_TEMPLATE_SPECIALIZATION (d))
18185     /* D has already been instantiated or explicitly specialized, so
18186        there's nothing for us to do here.
18187
18188        It might seem reasonable to check whether or not D is an explicit
18189        instantiation, and, if so, stop here.  But when an explicit
18190        instantiation is deferred until the end of the compilation,
18191        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18192        the instantiation.  */
18193     return d;
18194
18195   /* Check to see whether we know that this template will be
18196      instantiated in some other file, as with "extern template"
18197      extension.  */
18198   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18199
18200   /* In general, we do not instantiate such templates.  */
18201   if (external_p && !always_instantiate_p (d))
18202     return d;
18203
18204   gen_tmpl = most_general_template (tmpl);
18205   gen_args = DECL_TI_ARGS (d);
18206
18207   if (tmpl != gen_tmpl)
18208     /* We should already have the extra args.  */
18209     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18210                 == TMPL_ARGS_DEPTH (gen_args));
18211   /* And what's in the hash table should match D.  */
18212   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18213               || spec == NULL_TREE);
18214
18215   /* This needs to happen before any tsubsting.  */
18216   if (! push_tinst_level (d))
18217     return d;
18218
18219   timevar_push (TV_TEMPLATE_INST);
18220
18221   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18222      for the instantiation.  */
18223   td = template_for_substitution (d);
18224   code_pattern = DECL_TEMPLATE_RESULT (td);
18225
18226   /* We should never be trying to instantiate a member of a class
18227      template or partial specialization.  */
18228   gcc_assert (d != code_pattern);
18229
18230   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18231       || DECL_TEMPLATE_SPECIALIZATION (td))
18232     /* In the case of a friend template whose definition is provided
18233        outside the class, we may have too many arguments.  Drop the
18234        ones we don't need.  The same is true for specializations.  */
18235     args = get_innermost_template_args
18236       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18237   else
18238     args = gen_args;
18239
18240   if (TREE_CODE (d) == FUNCTION_DECL)
18241     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18242                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18243   else
18244     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18245
18246   /* We may be in the middle of deferred access check.  Disable it now.  */
18247   push_deferring_access_checks (dk_no_deferred);
18248
18249   /* Unless an explicit instantiation directive has already determined
18250      the linkage of D, remember that a definition is available for
18251      this entity.  */
18252   if (pattern_defined
18253       && !DECL_INTERFACE_KNOWN (d)
18254       && !DECL_NOT_REALLY_EXTERN (d))
18255     mark_definable (d);
18256
18257   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18258   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18259   input_location = DECL_SOURCE_LOCATION (d);
18260
18261   /* If D is a member of an explicitly instantiated class template,
18262      and no definition is available, treat it like an implicit
18263      instantiation.  */
18264   if (!pattern_defined && expl_inst_class_mem_p
18265       && DECL_EXPLICIT_INSTANTIATION (d))
18266     {
18267       /* Leave linkage flags alone on instantiations with anonymous
18268          visibility.  */
18269       if (TREE_PUBLIC (d))
18270         {
18271           DECL_NOT_REALLY_EXTERN (d) = 0;
18272           DECL_INTERFACE_KNOWN (d) = 0;
18273         }
18274       SET_DECL_IMPLICIT_INSTANTIATION (d);
18275     }
18276
18277   if (TREE_CODE (d) == FUNCTION_DECL)
18278     maybe_instantiate_noexcept (d);
18279
18280   /* Recheck the substitutions to obtain any warning messages
18281      about ignoring cv qualifiers.  Don't do this for artificial decls,
18282      as it breaks the context-sensitive substitution for lambda op(). */
18283   if (!defer_ok && !DECL_ARTIFICIAL (d))
18284     {
18285       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18286       tree type = TREE_TYPE (gen);
18287
18288       /* Make sure that we can see identifiers, and compute access
18289          correctly.  D is already the target FUNCTION_DECL with the
18290          right context.  */
18291       push_access_scope (d);
18292
18293       if (TREE_CODE (gen) == FUNCTION_DECL)
18294         {
18295           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18296           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18297                                           d, /*defer_ok*/true);
18298           /* Don't simply tsubst the function type, as that will give
18299              duplicate warnings about poor parameter qualifications.
18300              The function arguments are the same as the decl_arguments
18301              without the top level cv qualifiers.  */
18302           type = TREE_TYPE (type);
18303         }
18304       tsubst (type, gen_args, tf_warning_or_error, d);
18305
18306       pop_access_scope (d);
18307     }
18308
18309   /* Defer all other templates, unless we have been explicitly
18310      forbidden from doing so.  */
18311   if (/* If there is no definition, we cannot instantiate the
18312          template.  */
18313       ! pattern_defined
18314       /* If it's OK to postpone instantiation, do so.  */
18315       || defer_ok
18316       /* If this is a static data member that will be defined
18317          elsewhere, we don't want to instantiate the entire data
18318          member, but we do want to instantiate the initializer so that
18319          we can substitute that elsewhere.  */
18320       || (external_p && TREE_CODE (d) == VAR_DECL))
18321     {
18322       /* The definition of the static data member is now required so
18323          we must substitute the initializer.  */
18324       if (TREE_CODE (d) == VAR_DECL
18325           && !DECL_INITIAL (d)
18326           && DECL_INITIAL (code_pattern))
18327         {
18328           tree ns;
18329           tree init;
18330           bool const_init = false;
18331
18332           ns = decl_namespace_context (d);
18333           push_nested_namespace (ns);
18334           push_nested_class (DECL_CONTEXT (d));
18335           init = tsubst_expr (DECL_INITIAL (code_pattern),
18336                               args,
18337                               tf_warning_or_error, NULL_TREE,
18338                               /*integral_constant_expression_p=*/false);
18339           /* Make sure the initializer is still constant, in case of
18340              circular dependency (template/instantiate6.C). */
18341           const_init
18342             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18343           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18344                           /*asmspec_tree=*/NULL_TREE,
18345                           LOOKUP_ONLYCONVERTING);
18346           pop_nested_class ();
18347           pop_nested_namespace (ns);
18348         }
18349
18350       /* We restore the source position here because it's used by
18351          add_pending_template.  */
18352       input_location = saved_loc;
18353
18354       if (at_eof && !pattern_defined
18355           && DECL_EXPLICIT_INSTANTIATION (d)
18356           && DECL_NOT_REALLY_EXTERN (d))
18357         /* [temp.explicit]
18358
18359            The definition of a non-exported function template, a
18360            non-exported member function template, or a non-exported
18361            member function or static data member of a class template
18362            shall be present in every translation unit in which it is
18363            explicitly instantiated.  */
18364         permerror (input_location,  "explicit instantiation of %qD "
18365                    "but no definition available", d);
18366
18367       /* If we're in unevaluated context, we just wanted to get the
18368          constant value; this isn't an odr use, so don't queue
18369          a full instantiation.  */
18370       if (cp_unevaluated_operand != 0)
18371         goto out;
18372       /* ??? Historically, we have instantiated inline functions, even
18373          when marked as "extern template".  */
18374       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18375         add_pending_template (d);
18376       goto out;
18377     }
18378   /* Tell the repository that D is available in this translation unit
18379      -- and see if it is supposed to be instantiated here.  */
18380   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18381     {
18382       /* In a PCH file, despite the fact that the repository hasn't
18383          requested instantiation in the PCH it is still possible that
18384          an instantiation will be required in a file that includes the
18385          PCH.  */
18386       if (pch_file)
18387         add_pending_template (d);
18388       /* Instantiate inline functions so that the inliner can do its
18389          job, even though we'll not be emitting a copy of this
18390          function.  */
18391       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18392         goto out;
18393     }
18394
18395   fn_context = decl_function_context (d);
18396   nested = (current_function_decl != NULL_TREE);
18397   if (!fn_context)
18398     push_to_top_level ();
18399   else if (nested)
18400     push_function_context ();
18401
18402   /* Mark D as instantiated so that recursive calls to
18403      instantiate_decl do not try to instantiate it again.  */
18404   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18405
18406   /* Regenerate the declaration in case the template has been modified
18407      by a subsequent redeclaration.  */
18408   regenerate_decl_from_template (d, td);
18409
18410   /* We already set the file and line above.  Reset them now in case
18411      they changed as a result of calling regenerate_decl_from_template.  */
18412   input_location = DECL_SOURCE_LOCATION (d);
18413
18414   if (TREE_CODE (d) == VAR_DECL)
18415     {
18416       tree init;
18417       bool const_init = false;
18418
18419       /* Clear out DECL_RTL; whatever was there before may not be right
18420          since we've reset the type of the declaration.  */
18421       SET_DECL_RTL (d, NULL);
18422       DECL_IN_AGGR_P (d) = 0;
18423
18424       /* The initializer is placed in DECL_INITIAL by
18425          regenerate_decl_from_template so we don't need to
18426          push/pop_access_scope again here.  Pull it out so that
18427          cp_finish_decl can process it.  */
18428       init = DECL_INITIAL (d);
18429       DECL_INITIAL (d) = NULL_TREE;
18430       DECL_INITIALIZED_P (d) = 0;
18431
18432       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18433          initializer.  That function will defer actual emission until
18434          we have a chance to determine linkage.  */
18435       DECL_EXTERNAL (d) = 0;
18436
18437       /* Enter the scope of D so that access-checking works correctly.  */
18438       push_nested_class (DECL_CONTEXT (d));
18439       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18440       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18441       pop_nested_class ();
18442     }
18443   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18444     synthesize_method (d);
18445   else if (TREE_CODE (d) == FUNCTION_DECL)
18446     {
18447       htab_t saved_local_specializations;
18448       tree subst_decl;
18449       tree tmpl_parm;
18450       tree spec_parm;
18451
18452       /* Save away the current list, in case we are instantiating one
18453          template from within the body of another.  */
18454       saved_local_specializations = local_specializations;
18455
18456       /* Set up the list of local specializations.  */
18457       local_specializations = htab_create (37,
18458                                            hash_local_specialization,
18459                                            eq_local_specializations,
18460                                            NULL);
18461
18462       /* Set up context.  */
18463       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18464
18465       /* Create substitution entries for the parameters.  */
18466       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18467       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18468       spec_parm = DECL_ARGUMENTS (d);
18469       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18470         {
18471           register_local_specialization (spec_parm, tmpl_parm);
18472           spec_parm = skip_artificial_parms_for (d, spec_parm);
18473           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18474         }
18475       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18476         {
18477           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18478             {
18479               register_local_specialization (spec_parm, tmpl_parm);
18480               spec_parm = DECL_CHAIN (spec_parm);
18481             }
18482           else
18483             {
18484               /* Register the (value) argument pack as a specialization of
18485                  TMPL_PARM, then move on.  */
18486               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18487               register_local_specialization (argpack, tmpl_parm);
18488             }
18489         }
18490       gcc_assert (!spec_parm);
18491
18492       /* Substitute into the body of the function.  */
18493       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18494                    tf_warning_or_error, tmpl,
18495                    /*integral_constant_expression_p=*/false);
18496
18497       /* Set the current input_location to the end of the function
18498          so that finish_function knows where we are.  */
18499       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18500
18501       /* We don't need the local specializations any more.  */
18502       htab_delete (local_specializations);
18503       local_specializations = saved_local_specializations;
18504
18505       /* Finish the function.  */
18506       d = finish_function (0);
18507       expand_or_defer_fn (d);
18508     }
18509
18510   /* We're not deferring instantiation any more.  */
18511   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18512
18513   if (!fn_context)
18514     pop_from_top_level ();
18515   else if (nested)
18516     pop_function_context ();
18517
18518 out:
18519   input_location = saved_loc;
18520   pop_deferring_access_checks ();
18521   pop_tinst_level ();
18522
18523   timevar_pop (TV_TEMPLATE_INST);
18524
18525   return d;
18526 }
18527
18528 /* Run through the list of templates that we wish we could
18529    instantiate, and instantiate any we can.  RETRIES is the
18530    number of times we retry pending template instantiation.  */
18531
18532 void
18533 instantiate_pending_templates (int retries)
18534 {
18535   int reconsider;
18536   location_t saved_loc = input_location;
18537
18538   /* Instantiating templates may trigger vtable generation.  This in turn
18539      may require further template instantiations.  We place a limit here
18540      to avoid infinite loop.  */
18541   if (pending_templates && retries >= max_tinst_depth)
18542     {
18543       tree decl = pending_templates->tinst->decl;
18544
18545       error ("template instantiation depth exceeds maximum of %d"
18546              " instantiating %q+D, possibly from virtual table generation"
18547              " (use -ftemplate-depth= to increase the maximum)",
18548              max_tinst_depth, decl);
18549       if (TREE_CODE (decl) == FUNCTION_DECL)
18550         /* Pretend that we defined it.  */
18551         DECL_INITIAL (decl) = error_mark_node;
18552       return;
18553     }
18554
18555   do
18556     {
18557       struct pending_template **t = &pending_templates;
18558       struct pending_template *last = NULL;
18559       reconsider = 0;
18560       while (*t)
18561         {
18562           tree instantiation = reopen_tinst_level ((*t)->tinst);
18563           bool complete = false;
18564
18565           if (TYPE_P (instantiation))
18566             {
18567               tree fn;
18568
18569               if (!COMPLETE_TYPE_P (instantiation))
18570                 {
18571                   instantiate_class_template (instantiation);
18572                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18573                     for (fn = TYPE_METHODS (instantiation);
18574                          fn;
18575                          fn = TREE_CHAIN (fn))
18576                       if (! DECL_ARTIFICIAL (fn))
18577                         instantiate_decl (fn,
18578                                           /*defer_ok=*/0,
18579                                           /*expl_inst_class_mem_p=*/false);
18580                   if (COMPLETE_TYPE_P (instantiation))
18581                     reconsider = 1;
18582                 }
18583
18584               complete = COMPLETE_TYPE_P (instantiation);
18585             }
18586           else
18587             {
18588               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18589                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18590                 {
18591                   instantiation
18592                     = instantiate_decl (instantiation,
18593                                         /*defer_ok=*/0,
18594                                         /*expl_inst_class_mem_p=*/false);
18595                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18596                     reconsider = 1;
18597                 }
18598
18599               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18600                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18601             }
18602
18603           if (complete)
18604             /* If INSTANTIATION has been instantiated, then we don't
18605                need to consider it again in the future.  */
18606             *t = (*t)->next;
18607           else
18608             {
18609               last = *t;
18610               t = &(*t)->next;
18611             }
18612           tinst_depth = 0;
18613           current_tinst_level = NULL;
18614         }
18615       last_pending_template = last;
18616     }
18617   while (reconsider);
18618
18619   input_location = saved_loc;
18620 }
18621
18622 /* Substitute ARGVEC into T, which is a list of initializers for
18623    either base class or a non-static data member.  The TREE_PURPOSEs
18624    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18625    instantiate_decl.  */
18626
18627 static tree
18628 tsubst_initializer_list (tree t, tree argvec)
18629 {
18630   tree inits = NULL_TREE;
18631
18632   for (; t; t = TREE_CHAIN (t))
18633     {
18634       tree decl;
18635       tree init;
18636       tree expanded_bases = NULL_TREE;
18637       tree expanded_arguments = NULL_TREE;
18638       int i, len = 1;
18639
18640       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18641         {
18642           tree expr;
18643           tree arg;
18644
18645           /* Expand the base class expansion type into separate base
18646              classes.  */
18647           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18648                                                  tf_warning_or_error,
18649                                                  NULL_TREE);
18650           if (expanded_bases == error_mark_node)
18651             continue;
18652           
18653           /* We'll be building separate TREE_LISTs of arguments for
18654              each base.  */
18655           len = TREE_VEC_LENGTH (expanded_bases);
18656           expanded_arguments = make_tree_vec (len);
18657           for (i = 0; i < len; i++)
18658             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18659
18660           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18661              expand each argument in the TREE_VALUE of t.  */
18662           expr = make_node (EXPR_PACK_EXPANSION);
18663           PACK_EXPANSION_LOCAL_P (expr) = true;
18664           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18665             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18666
18667           if (TREE_VALUE (t) == void_type_node)
18668             /* VOID_TYPE_NODE is used to indicate
18669                value-initialization.  */
18670             {
18671               for (i = 0; i < len; i++)
18672                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18673             }
18674           else
18675             {
18676               /* Substitute parameter packs into each argument in the
18677                  TREE_LIST.  */
18678               in_base_initializer = 1;
18679               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18680                 {
18681                   tree expanded_exprs;
18682
18683                   /* Expand the argument.  */
18684                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18685                   expanded_exprs 
18686                     = tsubst_pack_expansion (expr, argvec,
18687                                              tf_warning_or_error,
18688                                              NULL_TREE);
18689                   if (expanded_exprs == error_mark_node)
18690                     continue;
18691
18692                   /* Prepend each of the expanded expressions to the
18693                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18694                   for (i = 0; i < len; i++)
18695                     {
18696                       TREE_VEC_ELT (expanded_arguments, i) = 
18697                         tree_cons (NULL_TREE, 
18698                                    TREE_VEC_ELT (expanded_exprs, i),
18699                                    TREE_VEC_ELT (expanded_arguments, i));
18700                     }
18701                 }
18702               in_base_initializer = 0;
18703
18704               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18705                  since we built them backwards.  */
18706               for (i = 0; i < len; i++)
18707                 {
18708                   TREE_VEC_ELT (expanded_arguments, i) = 
18709                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18710                 }
18711             }
18712         }
18713
18714       for (i = 0; i < len; ++i)
18715         {
18716           if (expanded_bases)
18717             {
18718               decl = TREE_VEC_ELT (expanded_bases, i);
18719               decl = expand_member_init (decl);
18720               init = TREE_VEC_ELT (expanded_arguments, i);
18721             }
18722           else
18723             {
18724               tree tmp;
18725               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18726                                   tf_warning_or_error, NULL_TREE);
18727
18728               decl = expand_member_init (decl);
18729               if (decl && !DECL_P (decl))
18730                 in_base_initializer = 1;
18731
18732               init = TREE_VALUE (t);
18733               tmp = init;
18734               if (init != void_type_node)
18735                 init = tsubst_expr (init, argvec,
18736                                     tf_warning_or_error, NULL_TREE,
18737                                     /*integral_constant_expression_p=*/false);
18738               if (init == NULL_TREE && tmp != NULL_TREE)
18739                 /* If we had an initializer but it instantiated to nothing,
18740                    value-initialize the object.  This will only occur when
18741                    the initializer was a pack expansion where the parameter
18742                    packs used in that expansion were of length zero.  */
18743                 init = void_type_node;
18744               in_base_initializer = 0;
18745             }
18746
18747           if (decl)
18748             {
18749               init = build_tree_list (decl, init);
18750               TREE_CHAIN (init) = inits;
18751               inits = init;
18752             }
18753         }
18754     }
18755   return inits;
18756 }
18757
18758 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18759
18760 static void
18761 set_current_access_from_decl (tree decl)
18762 {
18763   if (TREE_PRIVATE (decl))
18764     current_access_specifier = access_private_node;
18765   else if (TREE_PROTECTED (decl))
18766     current_access_specifier = access_protected_node;
18767   else
18768     current_access_specifier = access_public_node;
18769 }
18770
18771 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18772    is the instantiation (which should have been created with
18773    start_enum) and ARGS are the template arguments to use.  */
18774
18775 static void
18776 tsubst_enum (tree tag, tree newtag, tree args)
18777 {
18778   tree e;
18779
18780   if (SCOPED_ENUM_P (newtag))
18781     begin_scope (sk_scoped_enum, newtag);
18782
18783   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18784     {
18785       tree value;
18786       tree decl;
18787
18788       decl = TREE_VALUE (e);
18789       /* Note that in a template enum, the TREE_VALUE is the
18790          CONST_DECL, not the corresponding INTEGER_CST.  */
18791       value = tsubst_expr (DECL_INITIAL (decl),
18792                            args, tf_warning_or_error, NULL_TREE,
18793                            /*integral_constant_expression_p=*/true);
18794
18795       /* Give this enumeration constant the correct access.  */
18796       set_current_access_from_decl (decl);
18797
18798       /* Actually build the enumerator itself.  */
18799       build_enumerator
18800         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18801     }
18802
18803   if (SCOPED_ENUM_P (newtag))
18804     finish_scope ();
18805
18806   finish_enum_value_list (newtag);
18807   finish_enum (newtag);
18808
18809   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18810     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18811 }
18812
18813 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18814    its type -- but without substituting the innermost set of template
18815    arguments.  So, innermost set of template parameters will appear in
18816    the type.  */
18817
18818 tree
18819 get_mostly_instantiated_function_type (tree decl)
18820 {
18821   tree fn_type;
18822   tree tmpl;
18823   tree targs;
18824   tree tparms;
18825   int parm_depth;
18826
18827   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18828   targs = DECL_TI_ARGS (decl);
18829   tparms = DECL_TEMPLATE_PARMS (tmpl);
18830   parm_depth = TMPL_PARMS_DEPTH (tparms);
18831
18832   /* There should be as many levels of arguments as there are levels
18833      of parameters.  */
18834   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18835
18836   fn_type = TREE_TYPE (tmpl);
18837
18838   if (parm_depth == 1)
18839     /* No substitution is necessary.  */
18840     ;
18841   else
18842     {
18843       int i;
18844       tree partial_args;
18845
18846       /* Replace the innermost level of the TARGS with NULL_TREEs to
18847          let tsubst know not to substitute for those parameters.  */
18848       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18849       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18850         SET_TMPL_ARGS_LEVEL (partial_args, i,
18851                              TMPL_ARGS_LEVEL (targs, i));
18852       SET_TMPL_ARGS_LEVEL (partial_args,
18853                            TMPL_ARGS_DEPTH (targs),
18854                            make_tree_vec (DECL_NTPARMS (tmpl)));
18855
18856       /* Make sure that we can see identifiers, and compute access
18857          correctly.  */
18858       push_access_scope (decl);
18859
18860       ++processing_template_decl;
18861       /* Now, do the (partial) substitution to figure out the
18862          appropriate function type.  */
18863       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18864       --processing_template_decl;
18865
18866       /* Substitute into the template parameters to obtain the real
18867          innermost set of parameters.  This step is important if the
18868          innermost set of template parameters contains value
18869          parameters whose types depend on outer template parameters.  */
18870       TREE_VEC_LENGTH (partial_args)--;
18871       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18872
18873       pop_access_scope (decl);
18874     }
18875
18876   return fn_type;
18877 }
18878
18879 /* Return truthvalue if we're processing a template different from
18880    the last one involved in diagnostics.  */
18881 int
18882 problematic_instantiation_changed (void)
18883 {
18884   return current_tinst_level != last_error_tinst_level;
18885 }
18886
18887 /* Remember current template involved in diagnostics.  */
18888 void
18889 record_last_problematic_instantiation (void)
18890 {
18891   last_error_tinst_level = current_tinst_level;
18892 }
18893
18894 struct tinst_level *
18895 current_instantiation (void)
18896 {
18897   return current_tinst_level;
18898 }
18899
18900 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18901    type. Return zero for ok, nonzero for disallowed. Issue error and
18902    warning messages under control of COMPLAIN.  */
18903
18904 static int
18905 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18906 {
18907   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18908     return 0;
18909   else if (POINTER_TYPE_P (type))
18910     return 0;
18911   else if (TYPE_PTR_TO_MEMBER_P (type))
18912     return 0;
18913   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18914     return 0;
18915   else if (TREE_CODE (type) == TYPENAME_TYPE)
18916     return 0;
18917   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18918     return 0;
18919   else if (TREE_CODE (type) == NULLPTR_TYPE)
18920     return 0;
18921
18922   if (complain & tf_error)
18923     {
18924       if (type == error_mark_node)
18925         inform (input_location, "invalid template non-type parameter");
18926       else
18927         error ("%q#T is not a valid type for a template non-type parameter",
18928                type);
18929     }
18930   return 1;
18931 }
18932
18933 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18934    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18935
18936 static bool
18937 dependent_type_p_r (tree type)
18938 {
18939   tree scope;
18940
18941   /* [temp.dep.type]
18942
18943      A type is dependent if it is:
18944
18945      -- a template parameter. Template template parameters are types
18946         for us (since TYPE_P holds true for them) so we handle
18947         them here.  */
18948   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18949       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18950     return true;
18951   /* -- a qualified-id with a nested-name-specifier which contains a
18952         class-name that names a dependent type or whose unqualified-id
18953         names a dependent type.  */
18954   if (TREE_CODE (type) == TYPENAME_TYPE)
18955     return true;
18956   /* -- a cv-qualified type where the cv-unqualified type is
18957         dependent.  */
18958   type = TYPE_MAIN_VARIANT (type);
18959   /* -- a compound type constructed from any dependent type.  */
18960   if (TYPE_PTR_TO_MEMBER_P (type))
18961     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18962             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18963                                            (type)));
18964   else if (TREE_CODE (type) == POINTER_TYPE
18965            || TREE_CODE (type) == REFERENCE_TYPE)
18966     return dependent_type_p (TREE_TYPE (type));
18967   else if (TREE_CODE (type) == FUNCTION_TYPE
18968            || TREE_CODE (type) == METHOD_TYPE)
18969     {
18970       tree arg_type;
18971
18972       if (dependent_type_p (TREE_TYPE (type)))
18973         return true;
18974       for (arg_type = TYPE_ARG_TYPES (type);
18975            arg_type;
18976            arg_type = TREE_CHAIN (arg_type))
18977         if (dependent_type_p (TREE_VALUE (arg_type)))
18978           return true;
18979       return false;
18980     }
18981   /* -- an array type constructed from any dependent type or whose
18982         size is specified by a constant expression that is
18983         value-dependent.
18984
18985         We checked for type- and value-dependence of the bounds in
18986         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18987   if (TREE_CODE (type) == ARRAY_TYPE)
18988     {
18989       if (TYPE_DOMAIN (type)
18990           && dependent_type_p (TYPE_DOMAIN (type)))
18991         return true;
18992       return dependent_type_p (TREE_TYPE (type));
18993     }
18994
18995   /* -- a template-id in which either the template name is a template
18996      parameter ...  */
18997   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18998     return true;
18999   /* ... or any of the template arguments is a dependent type or
19000         an expression that is type-dependent or value-dependent.  */
19001   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
19002            && (any_dependent_template_arguments_p
19003                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
19004     return true;
19005
19006   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
19007      dependent; if the argument of the `typeof' expression is not
19008      type-dependent, then it should already been have resolved.  */
19009   if (TREE_CODE (type) == TYPEOF_TYPE
19010       || TREE_CODE (type) == DECLTYPE_TYPE
19011       || TREE_CODE (type) == UNDERLYING_TYPE)
19012     return true;
19013
19014   /* A template argument pack is dependent if any of its packed
19015      arguments are.  */
19016   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
19017     {
19018       tree args = ARGUMENT_PACK_ARGS (type);
19019       int i, len = TREE_VEC_LENGTH (args);
19020       for (i = 0; i < len; ++i)
19021         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19022           return true;
19023     }
19024
19025   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
19026      be template parameters.  */
19027   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
19028     return true;
19029
19030   /* The standard does not specifically mention types that are local
19031      to template functions or local classes, but they should be
19032      considered dependent too.  For example:
19033
19034        template <int I> void f() {
19035          enum E { a = I };
19036          S<sizeof (E)> s;
19037        }
19038
19039      The size of `E' cannot be known until the value of `I' has been
19040      determined.  Therefore, `E' must be considered dependent.  */
19041   scope = TYPE_CONTEXT (type);
19042   if (scope && TYPE_P (scope))
19043     return dependent_type_p (scope);
19044   /* Don't use type_dependent_expression_p here, as it can lead
19045      to infinite recursion trying to determine whether a lambda
19046      nested in a lambda is dependent (c++/47687).  */
19047   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
19048            && DECL_LANG_SPECIFIC (scope)
19049            && DECL_TEMPLATE_INFO (scope)
19050            && (any_dependent_template_arguments_p
19051                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
19052     return true;
19053
19054   /* Other types are non-dependent.  */
19055   return false;
19056 }
19057
19058 /* Returns TRUE if TYPE is dependent, in the sense of
19059    [temp.dep.type].  Note that a NULL type is considered dependent.  */
19060
19061 bool
19062 dependent_type_p (tree type)
19063 {
19064   /* If there are no template parameters in scope, then there can't be
19065      any dependent types.  */
19066   if (!processing_template_decl)
19067     {
19068       /* If we are not processing a template, then nobody should be
19069          providing us with a dependent type.  */
19070       gcc_assert (type);
19071       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
19072       return false;
19073     }
19074
19075   /* If the type is NULL, we have not computed a type for the entity
19076      in question; in that case, the type is dependent.  */
19077   if (!type)
19078     return true;
19079
19080   /* Erroneous types can be considered non-dependent.  */
19081   if (type == error_mark_node)
19082     return false;
19083
19084   /* If we have not already computed the appropriate value for TYPE,
19085      do so now.  */
19086   if (!TYPE_DEPENDENT_P_VALID (type))
19087     {
19088       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
19089       TYPE_DEPENDENT_P_VALID (type) = 1;
19090     }
19091
19092   return TYPE_DEPENDENT_P (type);
19093 }
19094
19095 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
19096    lookup.  In other words, a dependent type that is not the current
19097    instantiation.  */
19098
19099 bool
19100 dependent_scope_p (tree scope)
19101 {
19102   return (scope && TYPE_P (scope) && dependent_type_p (scope)
19103           && !currently_open_class (scope));
19104 }
19105
19106 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
19107    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
19108    expression.  */
19109
19110 /* Note that this predicate is not appropriate for general expressions;
19111    only constant expressions (that satisfy potential_constant_expression)
19112    can be tested for value dependence.
19113
19114    We should really also have a predicate for "instantiation-dependent".
19115
19116    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
19117      (what about instantiation-dependent constant-expressions?)
19118    is_late_template_attribute: defer if instantiation-dependent.
19119    compute_array_index_type: proceed if constant and not t- or v-dependent
19120      if instantiation-dependent, need to remember full expression
19121    uses_template_parms: FIXME - need to audit callers
19122    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
19123    dependent_type_p [array_type]: dependent if index type is dependent
19124      (or non-constant?)
19125    static_assert - instantiation-dependent */
19126
19127 bool
19128 value_dependent_expression_p (tree expression)
19129 {
19130   if (!processing_template_decl)
19131     return false;
19132
19133   /* A name declared with a dependent type.  */
19134   if (DECL_P (expression) && type_dependent_expression_p (expression))
19135     return true;
19136
19137   switch (TREE_CODE (expression))
19138     {
19139     case IDENTIFIER_NODE:
19140       /* A name that has not been looked up -- must be dependent.  */
19141       return true;
19142
19143     case TEMPLATE_PARM_INDEX:
19144       /* A non-type template parm.  */
19145       return true;
19146
19147     case CONST_DECL:
19148       /* A non-type template parm.  */
19149       if (DECL_TEMPLATE_PARM_P (expression))
19150         return true;
19151       return value_dependent_expression_p (DECL_INITIAL (expression));
19152
19153     case VAR_DECL:
19154        /* A constant with literal type and is initialized
19155           with an expression that is value-dependent.
19156
19157           Note that a non-dependent parenthesized initializer will have
19158           already been replaced with its constant value, so if we see
19159           a TREE_LIST it must be dependent.  */
19160       if (DECL_INITIAL (expression)
19161           && decl_constant_var_p (expression)
19162           && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
19163               || value_dependent_expression_p (DECL_INITIAL (expression))))
19164         return true;
19165       return false;
19166
19167     case DYNAMIC_CAST_EXPR:
19168     case STATIC_CAST_EXPR:
19169     case CONST_CAST_EXPR:
19170     case REINTERPRET_CAST_EXPR:
19171     case CAST_EXPR:
19172       /* These expressions are value-dependent if the type to which
19173          the cast occurs is dependent or the expression being casted
19174          is value-dependent.  */
19175       {
19176         tree type = TREE_TYPE (expression);
19177
19178         if (dependent_type_p (type))
19179           return true;
19180
19181         /* A functional cast has a list of operands.  */
19182         expression = TREE_OPERAND (expression, 0);
19183         if (!expression)
19184           {
19185             /* If there are no operands, it must be an expression such
19186                as "int()". This should not happen for aggregate types
19187                because it would form non-constant expressions.  */
19188             gcc_assert (cxx_dialect >= cxx0x
19189                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19190
19191             return false;
19192           }
19193
19194         if (TREE_CODE (expression) == TREE_LIST)
19195           return any_value_dependent_elements_p (expression);
19196
19197         return value_dependent_expression_p (expression);
19198       }
19199
19200     case SIZEOF_EXPR:
19201     case ALIGNOF_EXPR:
19202     case TYPEID_EXPR:
19203       /* A `sizeof' expression is value-dependent if the operand is
19204          type-dependent or is a pack expansion.  */
19205       expression = TREE_OPERAND (expression, 0);
19206       if (PACK_EXPANSION_P (expression))
19207         return true;
19208       else if (TYPE_P (expression))
19209         return dependent_type_p (expression);
19210       return type_dependent_expression_p (expression);
19211
19212     case AT_ENCODE_EXPR:
19213       /* An 'encode' expression is value-dependent if the operand is
19214          type-dependent.  */
19215       expression = TREE_OPERAND (expression, 0);
19216       return dependent_type_p (expression);
19217
19218     case NOEXCEPT_EXPR:
19219       expression = TREE_OPERAND (expression, 0);
19220       return type_dependent_expression_p (expression);
19221
19222     case SCOPE_REF:
19223       {
19224         tree name = TREE_OPERAND (expression, 1);
19225         return value_dependent_expression_p (name);
19226       }
19227
19228     case COMPONENT_REF:
19229       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19230               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19231
19232     case NONTYPE_ARGUMENT_PACK:
19233       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19234          is value-dependent.  */
19235       {
19236         tree values = ARGUMENT_PACK_ARGS (expression);
19237         int i, len = TREE_VEC_LENGTH (values);
19238         
19239         for (i = 0; i < len; ++i)
19240           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19241             return true;
19242         
19243         return false;
19244       }
19245
19246     case TRAIT_EXPR:
19247       {
19248         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19249         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19250                 || (type2 ? dependent_type_p (type2) : false));
19251       }
19252
19253     case MODOP_EXPR:
19254       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19255               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19256
19257     case ARRAY_REF:
19258       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19259               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19260
19261     case ADDR_EXPR:
19262       {
19263         tree op = TREE_OPERAND (expression, 0);
19264         return (value_dependent_expression_p (op)
19265                 || has_value_dependent_address (op));
19266       }
19267
19268     case CALL_EXPR:
19269       {
19270         tree fn = get_callee_fndecl (expression);
19271         int i, nargs;
19272         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19273           return true;
19274         nargs = call_expr_nargs (expression);
19275         for (i = 0; i < nargs; ++i)
19276           {
19277             tree op = CALL_EXPR_ARG (expression, i);
19278             /* In a call to a constexpr member function, look through the
19279                implicit ADDR_EXPR on the object argument so that it doesn't
19280                cause the call to be considered value-dependent.  We also
19281                look through it in potential_constant_expression.  */
19282             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19283                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19284                 && TREE_CODE (op) == ADDR_EXPR)
19285               op = TREE_OPERAND (op, 0);
19286             if (value_dependent_expression_p (op))
19287               return true;
19288           }
19289         return false;
19290       }
19291
19292     case TEMPLATE_ID_EXPR:
19293       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19294          type-dependent.  */
19295       return type_dependent_expression_p (expression);
19296
19297     case CONSTRUCTOR:
19298       {
19299         unsigned ix;
19300         tree val;
19301         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19302           if (value_dependent_expression_p (val))
19303             return true;
19304         return false;
19305       }
19306
19307     case STMT_EXPR:
19308       /* Treat a GNU statement expression as dependent to avoid crashing
19309          under fold_non_dependent_expr; it can't be constant.  */
19310       return true;
19311
19312     default:
19313       /* A constant expression is value-dependent if any subexpression is
19314          value-dependent.  */
19315       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19316         {
19317         case tcc_reference:
19318         case tcc_unary:
19319         case tcc_comparison:
19320         case tcc_binary:
19321         case tcc_expression:
19322         case tcc_vl_exp:
19323           {
19324             int i, len = cp_tree_operand_length (expression);
19325
19326             for (i = 0; i < len; i++)
19327               {
19328                 tree t = TREE_OPERAND (expression, i);
19329
19330                 /* In some cases, some of the operands may be missing.l
19331                    (For example, in the case of PREDECREMENT_EXPR, the
19332                    amount to increment by may be missing.)  That doesn't
19333                    make the expression dependent.  */
19334                 if (t && value_dependent_expression_p (t))
19335                   return true;
19336               }
19337           }
19338           break;
19339         default:
19340           break;
19341         }
19342       break;
19343     }
19344
19345   /* The expression is not value-dependent.  */
19346   return false;
19347 }
19348
19349 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19350    [temp.dep.expr].  Note that an expression with no type is
19351    considered dependent.  Other parts of the compiler arrange for an
19352    expression with type-dependent subexpressions to have no type, so
19353    this function doesn't have to be fully recursive.  */
19354
19355 bool
19356 type_dependent_expression_p (tree expression)
19357 {
19358   if (!processing_template_decl)
19359     return false;
19360
19361   if (expression == error_mark_node)
19362     return false;
19363
19364   /* An unresolved name is always dependent.  */
19365   if (TREE_CODE (expression) == IDENTIFIER_NODE
19366       || TREE_CODE (expression) == USING_DECL)
19367     return true;
19368
19369   /* Some expression forms are never type-dependent.  */
19370   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19371       || TREE_CODE (expression) == SIZEOF_EXPR
19372       || TREE_CODE (expression) == ALIGNOF_EXPR
19373       || TREE_CODE (expression) == AT_ENCODE_EXPR
19374       || TREE_CODE (expression) == NOEXCEPT_EXPR
19375       || TREE_CODE (expression) == TRAIT_EXPR
19376       || TREE_CODE (expression) == TYPEID_EXPR
19377       || TREE_CODE (expression) == DELETE_EXPR
19378       || TREE_CODE (expression) == VEC_DELETE_EXPR
19379       || TREE_CODE (expression) == THROW_EXPR)
19380     return false;
19381
19382   /* The types of these expressions depends only on the type to which
19383      the cast occurs.  */
19384   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19385       || TREE_CODE (expression) == STATIC_CAST_EXPR
19386       || TREE_CODE (expression) == CONST_CAST_EXPR
19387       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19388       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19389       || TREE_CODE (expression) == CAST_EXPR)
19390     return dependent_type_p (TREE_TYPE (expression));
19391
19392   /* The types of these expressions depends only on the type created
19393      by the expression.  */
19394   if (TREE_CODE (expression) == NEW_EXPR
19395       || TREE_CODE (expression) == VEC_NEW_EXPR)
19396     {
19397       /* For NEW_EXPR tree nodes created inside a template, either
19398          the object type itself or a TREE_LIST may appear as the
19399          operand 1.  */
19400       tree type = TREE_OPERAND (expression, 1);
19401       if (TREE_CODE (type) == TREE_LIST)
19402         /* This is an array type.  We need to check array dimensions
19403            as well.  */
19404         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19405                || value_dependent_expression_p
19406                     (TREE_OPERAND (TREE_VALUE (type), 1));
19407       else
19408         return dependent_type_p (type);
19409     }
19410
19411   if (TREE_CODE (expression) == SCOPE_REF)
19412     {
19413       tree scope = TREE_OPERAND (expression, 0);
19414       tree name = TREE_OPERAND (expression, 1);
19415
19416       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19417          contains an identifier associated by name lookup with one or more
19418          declarations declared with a dependent type, or...a
19419          nested-name-specifier or qualified-id that names a member of an
19420          unknown specialization.  */
19421       return (type_dependent_expression_p (name)
19422               || dependent_scope_p (scope));
19423     }
19424
19425   if (TREE_CODE (expression) == FUNCTION_DECL
19426       && DECL_LANG_SPECIFIC (expression)
19427       && DECL_TEMPLATE_INFO (expression)
19428       && (any_dependent_template_arguments_p
19429           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19430     return true;
19431
19432   if (TREE_CODE (expression) == TEMPLATE_DECL
19433       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19434     return false;
19435
19436   if (TREE_CODE (expression) == STMT_EXPR)
19437     expression = stmt_expr_value_expr (expression);
19438
19439   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19440     {
19441       tree elt;
19442       unsigned i;
19443
19444       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19445         {
19446           if (type_dependent_expression_p (elt))
19447             return true;
19448         }
19449       return false;
19450     }
19451
19452   /* A static data member of the current instantiation with incomplete
19453      array type is type-dependent, as the definition and specializations
19454      can have different bounds.  */
19455   if (TREE_CODE (expression) == VAR_DECL
19456       && DECL_CLASS_SCOPE_P (expression)
19457       && dependent_type_p (DECL_CONTEXT (expression))
19458       && VAR_HAD_UNKNOWN_BOUND (expression))
19459     return true;
19460
19461   if (TREE_TYPE (expression) == unknown_type_node)
19462     {
19463       if (TREE_CODE (expression) == ADDR_EXPR)
19464         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19465       if (TREE_CODE (expression) == COMPONENT_REF
19466           || TREE_CODE (expression) == OFFSET_REF)
19467         {
19468           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19469             return true;
19470           expression = TREE_OPERAND (expression, 1);
19471           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19472             return false;
19473         }
19474       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19475       if (TREE_CODE (expression) == SCOPE_REF)
19476         return false;
19477
19478       if (BASELINK_P (expression))
19479         expression = BASELINK_FUNCTIONS (expression);
19480
19481       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19482         {
19483           if (any_dependent_template_arguments_p
19484               (TREE_OPERAND (expression, 1)))
19485             return true;
19486           expression = TREE_OPERAND (expression, 0);
19487         }
19488       gcc_assert (TREE_CODE (expression) == OVERLOAD
19489                   || TREE_CODE (expression) == FUNCTION_DECL);
19490
19491       while (expression)
19492         {
19493           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19494             return true;
19495           expression = OVL_NEXT (expression);
19496         }
19497       return false;
19498     }
19499
19500   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19501
19502   return (dependent_type_p (TREE_TYPE (expression)));
19503 }
19504
19505 /* Like type_dependent_expression_p, but it also works while not processing
19506    a template definition, i.e. during substitution or mangling.  */
19507
19508 bool
19509 type_dependent_expression_p_push (tree expr)
19510 {
19511   bool b;
19512   ++processing_template_decl;
19513   b = type_dependent_expression_p (expr);
19514   --processing_template_decl;
19515   return b;
19516 }
19517
19518 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19519
19520 bool
19521 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19522 {
19523   unsigned int i;
19524   tree arg;
19525
19526   FOR_EACH_VEC_ELT (tree, args, i, arg)
19527     {
19528       if (type_dependent_expression_p (arg))
19529         return true;
19530     }
19531   return false;
19532 }
19533
19534 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19535    expressions) contains any type-dependent expressions.  */
19536
19537 bool
19538 any_type_dependent_elements_p (const_tree list)
19539 {
19540   for (; list; list = TREE_CHAIN (list))
19541     if (value_dependent_expression_p (TREE_VALUE (list)))
19542       return true;
19543
19544   return false;
19545 }
19546
19547 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19548    expressions) contains any value-dependent expressions.  */
19549
19550 bool
19551 any_value_dependent_elements_p (const_tree list)
19552 {
19553   for (; list; list = TREE_CHAIN (list))
19554     if (value_dependent_expression_p (TREE_VALUE (list)))
19555       return true;
19556
19557   return false;
19558 }
19559
19560 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19561
19562 bool
19563 dependent_template_arg_p (tree arg)
19564 {
19565   if (!processing_template_decl)
19566     return false;
19567
19568   /* Assume a template argument that was wrongly written by the user
19569      is dependent. This is consistent with what
19570      any_dependent_template_arguments_p [that calls this function]
19571      does.  */
19572   if (!arg || arg == error_mark_node)
19573     return true;
19574
19575   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19576     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19577
19578   if (TREE_CODE (arg) == TEMPLATE_DECL
19579       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19580     return dependent_template_p (arg);
19581   else if (ARGUMENT_PACK_P (arg))
19582     {
19583       tree args = ARGUMENT_PACK_ARGS (arg);
19584       int i, len = TREE_VEC_LENGTH (args);
19585       for (i = 0; i < len; ++i)
19586         {
19587           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19588             return true;
19589         }
19590
19591       return false;
19592     }
19593   else if (TYPE_P (arg))
19594     return dependent_type_p (arg);
19595   else
19596     return (type_dependent_expression_p (arg)
19597             || value_dependent_expression_p (arg));
19598 }
19599
19600 /* Returns true if ARGS (a collection of template arguments) contains
19601    any types that require structural equality testing.  */
19602
19603 bool
19604 any_template_arguments_need_structural_equality_p (tree args)
19605 {
19606   int i;
19607   int j;
19608
19609   if (!args)
19610     return false;
19611   if (args == error_mark_node)
19612     return true;
19613
19614   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19615     {
19616       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19617       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19618         {
19619           tree arg = TREE_VEC_ELT (level, j);
19620           tree packed_args = NULL_TREE;
19621           int k, len = 1;
19622
19623           if (ARGUMENT_PACK_P (arg))
19624             {
19625               /* Look inside the argument pack.  */
19626               packed_args = ARGUMENT_PACK_ARGS (arg);
19627               len = TREE_VEC_LENGTH (packed_args);
19628             }
19629
19630           for (k = 0; k < len; ++k)
19631             {
19632               if (packed_args)
19633                 arg = TREE_VEC_ELT (packed_args, k);
19634
19635               if (error_operand_p (arg))
19636                 return true;
19637               else if (TREE_CODE (arg) == TEMPLATE_DECL
19638                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19639                 continue;
19640               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19641                 return true;
19642               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19643                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19644                 return true;
19645             }
19646         }
19647     }
19648
19649   return false;
19650 }
19651
19652 /* Returns true if ARGS (a collection of template arguments) contains
19653    any dependent arguments.  */
19654
19655 bool
19656 any_dependent_template_arguments_p (const_tree args)
19657 {
19658   int i;
19659   int j;
19660
19661   if (!args)
19662     return false;
19663   if (args == error_mark_node)
19664     return true;
19665
19666   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19667     {
19668       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19669       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19670         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19671           return true;
19672     }
19673
19674   return false;
19675 }
19676
19677 /* Returns TRUE if the template TMPL is dependent.  */
19678
19679 bool
19680 dependent_template_p (tree tmpl)
19681 {
19682   if (TREE_CODE (tmpl) == OVERLOAD)
19683     {
19684       while (tmpl)
19685         {
19686           if (dependent_template_p (OVL_CURRENT (tmpl)))
19687             return true;
19688           tmpl = OVL_NEXT (tmpl);
19689         }
19690       return false;
19691     }
19692
19693   /* Template template parameters are dependent.  */
19694   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19695       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19696     return true;
19697   /* So are names that have not been looked up.  */
19698   if (TREE_CODE (tmpl) == SCOPE_REF
19699       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19700     return true;
19701   /* So are member templates of dependent classes.  */
19702   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19703     return dependent_type_p (DECL_CONTEXT (tmpl));
19704   return false;
19705 }
19706
19707 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19708
19709 bool
19710 dependent_template_id_p (tree tmpl, tree args)
19711 {
19712   return (dependent_template_p (tmpl)
19713           || any_dependent_template_arguments_p (args));
19714 }
19715
19716 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19717    is dependent.  */
19718
19719 bool
19720 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19721 {
19722   int i;
19723
19724   if (!processing_template_decl)
19725     return false;
19726
19727   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19728     {
19729       tree decl = TREE_VEC_ELT (declv, i);
19730       tree init = TREE_VEC_ELT (initv, i);
19731       tree cond = TREE_VEC_ELT (condv, i);
19732       tree incr = TREE_VEC_ELT (incrv, i);
19733
19734       if (type_dependent_expression_p (decl))
19735         return true;
19736
19737       if (init && type_dependent_expression_p (init))
19738         return true;
19739
19740       if (type_dependent_expression_p (cond))
19741         return true;
19742
19743       if (COMPARISON_CLASS_P (cond)
19744           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19745               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19746         return true;
19747
19748       if (TREE_CODE (incr) == MODOP_EXPR)
19749         {
19750           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19751               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19752             return true;
19753         }
19754       else if (type_dependent_expression_p (incr))
19755         return true;
19756       else if (TREE_CODE (incr) == MODIFY_EXPR)
19757         {
19758           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19759             return true;
19760           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19761             {
19762               tree t = TREE_OPERAND (incr, 1);
19763               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19764                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19765                 return true;
19766             }
19767         }
19768     }
19769
19770   return false;
19771 }
19772
19773 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19774    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19775    no such TYPE can be found.  Note that this function peers inside
19776    uninstantiated templates and therefore should be used only in
19777    extremely limited situations.  ONLY_CURRENT_P restricts this
19778    peering to the currently open classes hierarchy (which is required
19779    when comparing types).  */
19780
19781 tree
19782 resolve_typename_type (tree type, bool only_current_p)
19783 {
19784   tree scope;
19785   tree name;
19786   tree decl;
19787   int quals;
19788   tree pushed_scope;
19789   tree result;
19790
19791   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19792
19793   scope = TYPE_CONTEXT (type);
19794   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19795      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19796      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19797      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19798      identifier  of the TYPENAME_TYPE anymore.
19799      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19800      TYPENAME_TYPE instead, we avoid messing up with a possible
19801      typedef variant case.  */
19802   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19803
19804   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19805      it first before we can figure out what NAME refers to.  */
19806   if (TREE_CODE (scope) == TYPENAME_TYPE)
19807     scope = resolve_typename_type (scope, only_current_p);
19808   /* If we don't know what SCOPE refers to, then we cannot resolve the
19809      TYPENAME_TYPE.  */
19810   if (TREE_CODE (scope) == TYPENAME_TYPE)
19811     return type;
19812   /* If the SCOPE is a template type parameter, we have no way of
19813      resolving the name.  */
19814   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19815     return type;
19816   /* If the SCOPE is not the current instantiation, there's no reason
19817      to look inside it.  */
19818   if (only_current_p && !currently_open_class (scope))
19819     return type;
19820   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19821   if (typedef_variant_p (type))
19822     return type;
19823   /* If SCOPE isn't the template itself, it will not have a valid
19824      TYPE_FIELDS list.  */
19825   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19826     /* scope is either the template itself or a compatible instantiation
19827        like X<T>, so look up the name in the original template.  */
19828     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19829   else
19830     /* scope is a partial instantiation, so we can't do the lookup or we
19831        will lose the template arguments.  */
19832     return type;
19833   /* Enter the SCOPE so that name lookup will be resolved as if we
19834      were in the class definition.  In particular, SCOPE will no
19835      longer be considered a dependent type.  */
19836   pushed_scope = push_scope (scope);
19837   /* Look up the declaration.  */
19838   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
19839                         tf_warning_or_error);
19840
19841   result = NULL_TREE;
19842   
19843   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19844      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19845   if (!decl)
19846     /*nop*/;
19847   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19848            && TREE_CODE (decl) == TYPE_DECL)
19849     {
19850       result = TREE_TYPE (decl);
19851       if (result == error_mark_node)
19852         result = NULL_TREE;
19853     }
19854   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19855            && DECL_CLASS_TEMPLATE_P (decl))
19856     {
19857       tree tmpl;
19858       tree args;
19859       /* Obtain the template and the arguments.  */
19860       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19861       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19862       /* Instantiate the template.  */
19863       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19864                                       /*entering_scope=*/0,
19865                                       tf_error | tf_user);
19866       if (result == error_mark_node)
19867         result = NULL_TREE;
19868     }
19869   
19870   /* Leave the SCOPE.  */
19871   if (pushed_scope)
19872     pop_scope (pushed_scope);
19873
19874   /* If we failed to resolve it, return the original typename.  */
19875   if (!result)
19876     return type;
19877   
19878   /* If lookup found a typename type, resolve that too.  */
19879   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19880     {
19881       /* Ill-formed programs can cause infinite recursion here, so we
19882          must catch that.  */
19883       TYPENAME_IS_RESOLVING_P (type) = 1;
19884       result = resolve_typename_type (result, only_current_p);
19885       TYPENAME_IS_RESOLVING_P (type) = 0;
19886     }
19887   
19888   /* Qualify the resulting type.  */
19889   quals = cp_type_quals (type);
19890   if (quals)
19891     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19892
19893   return result;
19894 }
19895
19896 /* EXPR is an expression which is not type-dependent.  Return a proxy
19897    for EXPR that can be used to compute the types of larger
19898    expressions containing EXPR.  */
19899
19900 tree
19901 build_non_dependent_expr (tree expr)
19902 {
19903   tree inner_expr;
19904
19905 #ifdef ENABLE_CHECKING
19906   /* Try to get a constant value for all non-type-dependent expressions in
19907       order to expose bugs in *_dependent_expression_p and constexpr.  */
19908   if (cxx_dialect >= cxx0x)
19909     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19910 #endif
19911
19912   /* Preserve OVERLOADs; the functions must be available to resolve
19913      types.  */
19914   inner_expr = expr;
19915   if (TREE_CODE (inner_expr) == STMT_EXPR)
19916     inner_expr = stmt_expr_value_expr (inner_expr);
19917   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19918     inner_expr = TREE_OPERAND (inner_expr, 0);
19919   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19920     inner_expr = TREE_OPERAND (inner_expr, 1);
19921   if (is_overloaded_fn (inner_expr)
19922       || TREE_CODE (inner_expr) == OFFSET_REF)
19923     return expr;
19924   /* There is no need to return a proxy for a variable.  */
19925   if (TREE_CODE (expr) == VAR_DECL)
19926     return expr;
19927   /* Preserve string constants; conversions from string constants to
19928      "char *" are allowed, even though normally a "const char *"
19929      cannot be used to initialize a "char *".  */
19930   if (TREE_CODE (expr) == STRING_CST)
19931     return expr;
19932   /* Preserve arithmetic constants, as an optimization -- there is no
19933      reason to create a new node.  */
19934   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19935     return expr;
19936   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19937      There is at least one place where we want to know that a
19938      particular expression is a throw-expression: when checking a ?:
19939      expression, there are special rules if the second or third
19940      argument is a throw-expression.  */
19941   if (TREE_CODE (expr) == THROW_EXPR)
19942     return expr;
19943
19944   /* Don't wrap an initializer list, we need to be able to look inside.  */
19945   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19946     return expr;
19947
19948   if (TREE_CODE (expr) == COND_EXPR)
19949     return build3 (COND_EXPR,
19950                    TREE_TYPE (expr),
19951                    TREE_OPERAND (expr, 0),
19952                    (TREE_OPERAND (expr, 1)
19953                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19954                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19955                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19956   if (TREE_CODE (expr) == COMPOUND_EXPR
19957       && !COMPOUND_EXPR_OVERLOADED (expr))
19958     return build2 (COMPOUND_EXPR,
19959                    TREE_TYPE (expr),
19960                    TREE_OPERAND (expr, 0),
19961                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19962
19963   /* If the type is unknown, it can't really be non-dependent */
19964   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19965
19966   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19967   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19968 }
19969
19970 /* ARGS is a vector of expressions as arguments to a function call.
19971    Replace the arguments with equivalent non-dependent expressions.
19972    This modifies ARGS in place.  */
19973
19974 void
19975 make_args_non_dependent (VEC(tree,gc) *args)
19976 {
19977   unsigned int ix;
19978   tree arg;
19979
19980   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19981     {
19982       tree newarg = build_non_dependent_expr (arg);
19983       if (newarg != arg)
19984         VEC_replace (tree, args, ix, newarg);
19985     }
19986 }
19987
19988 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
19989    with a level one deeper than the actual template parms.  */
19990
19991 tree
19992 make_auto (void)
19993 {
19994   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
19995   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
19996                                TYPE_DECL, get_identifier ("auto"), au);
19997   TYPE_STUB_DECL (au) = TYPE_NAME (au);
19998   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
19999     (0, processing_template_decl + 1, processing_template_decl + 1,
20000      TYPE_NAME (au), NULL_TREE);
20001   TYPE_CANONICAL (au) = canonical_type_parameter (au);
20002   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
20003   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
20004
20005   return au;
20006 }
20007
20008 /* Given type ARG, return std::initializer_list<ARG>.  */
20009
20010 static tree
20011 listify (tree arg)
20012 {
20013   tree std_init_list = namespace_binding
20014     (get_identifier ("initializer_list"), std_node);
20015   tree argvec;
20016   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
20017     {    
20018       error ("deducing from brace-enclosed initializer list requires "
20019              "#include <initializer_list>");
20020       return error_mark_node;
20021     }
20022   argvec = make_tree_vec (1);
20023   TREE_VEC_ELT (argvec, 0) = arg;
20024   return lookup_template_class (std_init_list, argvec, NULL_TREE,
20025                                 NULL_TREE, 0, tf_warning_or_error);
20026 }
20027
20028 /* Replace auto in TYPE with std::initializer_list<auto>.  */
20029
20030 static tree
20031 listify_autos (tree type, tree auto_node)
20032 {
20033   tree init_auto = listify (auto_node);
20034   tree argvec = make_tree_vec (1);
20035   TREE_VEC_ELT (argvec, 0) = init_auto;
20036   if (processing_template_decl)
20037     argvec = add_to_template_args (current_template_args (), argvec);
20038   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20039 }
20040
20041 /* walk_tree helper for do_auto_deduction.  */
20042
20043 static tree
20044 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
20045                  void *type)
20046 {
20047   /* Is this a variable with the type we're looking for?  */
20048   if (DECL_P (*tp)
20049       && TREE_TYPE (*tp) == type)
20050     return *tp;
20051   else
20052     return NULL_TREE;
20053 }
20054
20055 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
20056    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
20057
20058 tree
20059 do_auto_deduction (tree type, tree init, tree auto_node)
20060 {
20061   tree parms, tparms, targs;
20062   tree args[1];
20063   tree decl;
20064   int val;
20065
20066   if (type_dependent_expression_p (init))
20067     /* Defining a subset of type-dependent expressions that we can deduce
20068        from ahead of time isn't worth the trouble.  */
20069     return type;
20070
20071   /* The name of the object being declared shall not appear in the
20072      initializer expression.  */
20073   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
20074   if (decl)
20075     {
20076       error ("variable %q#D with %<auto%> type used in its own "
20077              "initializer", decl);
20078       return error_mark_node;
20079     }
20080
20081   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
20082      with either a new invented type template parameter U or, if the
20083      initializer is a braced-init-list (8.5.4), with
20084      std::initializer_list<U>.  */
20085   if (BRACE_ENCLOSED_INITIALIZER_P (init))
20086     type = listify_autos (type, auto_node);
20087
20088   init = resolve_nondeduced_context (init);
20089
20090   parms = build_tree_list (NULL_TREE, type);
20091   args[0] = init;
20092   tparms = make_tree_vec (1);
20093   targs = make_tree_vec (1);
20094   TREE_VEC_ELT (tparms, 0)
20095     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
20096   val = type_unification_real (tparms, targs, parms, args, 1, 0,
20097                                DEDUCE_CALL, LOOKUP_NORMAL,
20098                                /*explain_p=*/false);
20099   if (val > 0)
20100     {
20101       if (processing_template_decl)
20102         /* Try again at instantiation time.  */
20103         return type;
20104       if (type && type != error_mark_node)
20105         /* If type is error_mark_node a diagnostic must have been
20106            emitted by now.  Also, having a mention to '<type error>'
20107            in the diagnostic is not really useful to the user.  */
20108         error ("unable to deduce %qT from %qE", type, init);
20109       return error_mark_node;
20110     }
20111
20112   /* If the list of declarators contains more than one declarator, the type
20113      of each declared variable is determined as described above. If the
20114      type deduced for the template parameter U is not the same in each
20115      deduction, the program is ill-formed.  */
20116   if (TREE_TYPE (auto_node)
20117       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
20118     {
20119       error ("inconsistent deduction for %qT: %qT and then %qT",
20120              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
20121       return error_mark_node;
20122     }
20123   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
20124
20125   if (processing_template_decl)
20126     targs = add_to_template_args (current_template_args (), targs);
20127   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
20128 }
20129
20130 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
20131    result.  */
20132
20133 tree
20134 splice_late_return_type (tree type, tree late_return_type)
20135 {
20136   tree argvec;
20137
20138   if (late_return_type == NULL_TREE)
20139     return type;
20140   argvec = make_tree_vec (1);
20141   TREE_VEC_ELT (argvec, 0) = late_return_type;
20142   if (processing_template_parmlist)
20143     /* For a late-specified return type in a template type-parameter, we
20144        need to add a dummy argument level for its parmlist.  */
20145     argvec = add_to_template_args
20146       (make_tree_vec (processing_template_parmlist), argvec);
20147   if (current_template_parms)
20148     argvec = add_to_template_args (current_template_args (), argvec);
20149   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20150 }
20151
20152 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
20153
20154 bool
20155 is_auto (const_tree type)
20156 {
20157   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20158       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
20159     return true;
20160   else
20161     return false;
20162 }
20163
20164 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
20165    appear as a type-specifier for the declaration in question, we don't
20166    have to look through the whole type.  */
20167
20168 tree
20169 type_uses_auto (tree type)
20170 {
20171   enum tree_code code;
20172   if (is_auto (type))
20173     return type;
20174
20175   code = TREE_CODE (type);
20176
20177   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20178       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20179       || code == METHOD_TYPE || code == ARRAY_TYPE)
20180     return type_uses_auto (TREE_TYPE (type));
20181
20182   if (TYPE_PTRMEMFUNC_P (type))
20183     return type_uses_auto (TREE_TYPE (TREE_TYPE
20184                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20185
20186   return NULL_TREE;
20187 }
20188
20189 /* For a given template T, return the vector of typedefs referenced
20190    in T for which access check is needed at T instantiation time.
20191    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20192    Those typedefs were added to T by the function
20193    append_type_to_template_for_access_check.  */
20194
20195 VEC(qualified_typedef_usage_t,gc)*
20196 get_types_needing_access_check (tree t)
20197 {
20198   tree ti;
20199   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20200
20201   if (!t || t == error_mark_node)
20202     return NULL;
20203
20204   if (!(ti = get_template_info (t)))
20205     return NULL;
20206
20207   if (CLASS_TYPE_P (t)
20208       || TREE_CODE (t) == FUNCTION_DECL)
20209     {
20210       if (!TI_TEMPLATE (ti))
20211         return NULL;
20212
20213       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20214     }
20215
20216   return result;
20217 }
20218
20219 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20220    tied to T. That list of typedefs will be access checked at
20221    T instantiation time.
20222    T is either a FUNCTION_DECL or a RECORD_TYPE.
20223    TYPE_DECL is a TYPE_DECL node representing a typedef.
20224    SCOPE is the scope through which TYPE_DECL is accessed.
20225    LOCATION is the location of the usage point of TYPE_DECL.
20226
20227    This function is a subroutine of
20228    append_type_to_template_for_access_check.  */
20229
20230 static void
20231 append_type_to_template_for_access_check_1 (tree t,
20232                                             tree type_decl,
20233                                             tree scope,
20234                                             location_t location)
20235 {
20236   qualified_typedef_usage_t typedef_usage;
20237   tree ti;
20238
20239   if (!t || t == error_mark_node)
20240     return;
20241
20242   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20243                || CLASS_TYPE_P (t))
20244               && type_decl
20245               && TREE_CODE (type_decl) == TYPE_DECL
20246               && scope);
20247
20248   if (!(ti = get_template_info (t)))
20249     return;
20250
20251   gcc_assert (TI_TEMPLATE (ti));
20252
20253   typedef_usage.typedef_decl = type_decl;
20254   typedef_usage.context = scope;
20255   typedef_usage.locus = location;
20256
20257   VEC_safe_push (qualified_typedef_usage_t, gc,
20258                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20259                  &typedef_usage);
20260 }
20261
20262 /* Append TYPE_DECL to the template TEMPL.
20263    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20264    At TEMPL instanciation time, TYPE_DECL will be checked to see
20265    if it can be accessed through SCOPE.
20266    LOCATION is the location of the usage point of TYPE_DECL.
20267
20268    e.g. consider the following code snippet:
20269
20270      class C
20271      {
20272        typedef int myint;
20273      };
20274
20275      template<class U> struct S
20276      {
20277        C::myint mi; // <-- usage point of the typedef C::myint
20278      };
20279
20280      S<char> s;
20281
20282    At S<char> instantiation time, we need to check the access of C::myint
20283    In other words, we need to check the access of the myint typedef through
20284    the C scope. For that purpose, this function will add the myint typedef
20285    and the scope C through which its being accessed to a list of typedefs
20286    tied to the template S. That list will be walked at template instantiation
20287    time and access check performed on each typedefs it contains.
20288    Note that this particular code snippet should yield an error because
20289    myint is private to C.  */
20290
20291 void
20292 append_type_to_template_for_access_check (tree templ,
20293                                           tree type_decl,
20294                                           tree scope,
20295                                           location_t location)
20296 {
20297   qualified_typedef_usage_t *iter;
20298   int i;
20299
20300   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20301
20302   /* Make sure we don't append the type to the template twice.  */
20303   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20304                     get_types_needing_access_check (templ),
20305                     i, iter)
20306     if (iter->typedef_decl == type_decl && scope == iter->context)
20307       return;
20308
20309   append_type_to_template_for_access_check_1 (templ, type_decl,
20310                                               scope, location);
20311 }
20312
20313 /* Set up the hash tables for template instantiations.  */
20314
20315 void
20316 init_template_processing (void)
20317 {
20318   decl_specializations = htab_create_ggc (37,
20319                                           hash_specialization,
20320                                           eq_specializations,
20321                                           ggc_free);
20322   type_specializations = htab_create_ggc (37,
20323                                           hash_specialization,
20324                                           eq_specializations,
20325                                           ggc_free);
20326 }
20327
20328 /* Print stats about the template hash tables for -fstats.  */
20329
20330 void
20331 print_template_statistics (void)
20332 {
20333   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20334            "%f collisions\n", (long) htab_size (decl_specializations),
20335            (long) htab_elements (decl_specializations),
20336            htab_collisions (decl_specializations));
20337   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20338            "%f collisions\n", (long) htab_size (type_specializations),
20339            (long) htab_elements (type_specializations),
20340            htab_collisions (type_specializations));
20341 }
20342
20343 #include "gt-cp-pt.h"