Merge branch 'vendor/OPENSSL'
[dragonfly.git] / contrib / gcc-4.7 / 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 int comparing_specializations;
1463
1464 static int
1465 eq_specializations (const void *p1, const void *p2)
1466 {
1467   const spec_entry *e1 = (const spec_entry *)p1;
1468   const spec_entry *e2 = (const spec_entry *)p2;
1469   int equal;
1470
1471   ++comparing_specializations;
1472   equal = (e1->tmpl == e2->tmpl
1473            && comp_template_args (e1->args, e2->args));
1474   --comparing_specializations;
1475
1476   return equal;
1477 }
1478
1479 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1480
1481 static hashval_t
1482 hash_tmpl_and_args (tree tmpl, tree args)
1483 {
1484   hashval_t val = DECL_UID (tmpl);
1485   return iterative_hash_template_arg (args, val);
1486 }
1487
1488 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1489    ignoring SPEC.  */
1490
1491 static hashval_t
1492 hash_specialization (const void *p)
1493 {
1494   const spec_entry *e = (const spec_entry *)p;
1495   return hash_tmpl_and_args (e->tmpl, e->args);
1496 }
1497
1498 /* Recursively calculate a hash value for a template argument ARG, for use
1499    in the hash tables of template specializations.  */
1500
1501 hashval_t
1502 iterative_hash_template_arg (tree arg, hashval_t val)
1503 {
1504   unsigned HOST_WIDE_INT i;
1505   enum tree_code code;
1506   char tclass;
1507
1508   if (arg == NULL_TREE)
1509     return iterative_hash_object (arg, val);
1510
1511   if (!TYPE_P (arg))
1512     STRIP_NOPS (arg);
1513
1514   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1515     /* We can get one of these when re-hashing a previous entry in the middle
1516        of substituting into a pack expansion.  Just look through it.  */
1517     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1518
1519   code = TREE_CODE (arg);
1520   tclass = TREE_CODE_CLASS (code);
1521
1522   val = iterative_hash_object (code, val);
1523
1524   switch (code)
1525     {
1526     case ERROR_MARK:
1527       return val;
1528
1529     case IDENTIFIER_NODE:
1530       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1531
1532     case TREE_VEC:
1533       {
1534         int i, len = TREE_VEC_LENGTH (arg);
1535         for (i = 0; i < len; ++i)
1536           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1537         return val;
1538       }
1539
1540     case TYPE_PACK_EXPANSION:
1541     case EXPR_PACK_EXPANSION:
1542       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1543       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1544
1545     case TYPE_ARGUMENT_PACK:
1546     case NONTYPE_ARGUMENT_PACK:
1547       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1548
1549     case TREE_LIST:
1550       for (; arg; arg = TREE_CHAIN (arg))
1551         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1552       return val;
1553
1554     case OVERLOAD:
1555       for (; arg; arg = OVL_NEXT (arg))
1556         val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1557       return val;
1558
1559     case CONSTRUCTOR:
1560       {
1561         tree field, value;
1562         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1563           {
1564             val = iterative_hash_template_arg (field, val);
1565             val = iterative_hash_template_arg (value, val);
1566           }
1567         return val;
1568       }
1569
1570     case PARM_DECL:
1571       if (!DECL_ARTIFICIAL (arg))
1572         {
1573           val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1574           val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1575         }
1576       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1577
1578     case TARGET_EXPR:
1579       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1580
1581     case PTRMEM_CST:
1582       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1583       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1584
1585     case TEMPLATE_PARM_INDEX:
1586       val = iterative_hash_template_arg
1587         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1588       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1589       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1590
1591     case TRAIT_EXPR:
1592       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1593       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1594       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1595
1596     case BASELINK:
1597       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1598                                          val);
1599       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1600                                           val);
1601
1602     case MODOP_EXPR:
1603       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1604       code = TREE_CODE (TREE_OPERAND (arg, 1));
1605       val = iterative_hash_object (code, val);
1606       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1607
1608     case LAMBDA_EXPR:
1609       /* A lambda can't appear in a template arg, but don't crash on
1610          erroneous input.  */
1611       gcc_assert (seen_error ());
1612       return val;
1613
1614     case CAST_EXPR:
1615     case IMPLICIT_CONV_EXPR:
1616     case STATIC_CAST_EXPR:
1617     case REINTERPRET_CAST_EXPR:
1618     case CONST_CAST_EXPR:
1619     case DYNAMIC_CAST_EXPR:
1620     case NEW_EXPR:
1621       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1622       /* Now hash operands as usual.  */
1623       break;
1624
1625     default:
1626       break;
1627     }
1628
1629   switch (tclass)
1630     {
1631     case tcc_type:
1632       if (TYPE_CANONICAL (arg))
1633         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1634                                       val);
1635       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1636         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1637       /* Otherwise just compare the types during lookup.  */
1638       return val;
1639
1640     case tcc_declaration:
1641     case tcc_constant:
1642       return iterative_hash_expr (arg, val);
1643
1644     default:
1645       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1646       {
1647         unsigned n = cp_tree_operand_length (arg);
1648         for (i = 0; i < n; ++i)
1649           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1650         return val;
1651       }
1652     }
1653   gcc_unreachable ();
1654   return 0;
1655 }
1656
1657 /* Unregister the specialization SPEC as a specialization of TMPL.
1658    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1659    if the SPEC was listed as a specialization of TMPL.
1660
1661    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1662
1663 bool
1664 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1665 {
1666   spec_entry *entry;
1667   spec_entry elt;
1668
1669   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1670   elt.args = TI_ARGS (tinfo);
1671   elt.spec = NULL_TREE;
1672
1673   entry = (spec_entry *) htab_find (decl_specializations, &elt);
1674   if (entry != NULL)
1675     {
1676       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1677       gcc_assert (new_spec != NULL_TREE);
1678       entry->spec = new_spec;
1679       return 1;
1680     }
1681
1682   return 0;
1683 }
1684
1685 /* Compare an entry in the local specializations hash table P1 (which
1686    is really a pointer to a TREE_LIST) with P2 (which is really a
1687    DECL).  */
1688
1689 static int
1690 eq_local_specializations (const void *p1, const void *p2)
1691 {
1692   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1693 }
1694
1695 /* Hash P1, an entry in the local specializations table.  */
1696
1697 static hashval_t
1698 hash_local_specialization (const void* p1)
1699 {
1700   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1701 }
1702
1703 /* Like register_specialization, but for local declarations.  We are
1704    registering SPEC, an instantiation of TMPL.  */
1705
1706 static void
1707 register_local_specialization (tree spec, tree tmpl)
1708 {
1709   void **slot;
1710
1711   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1712                                    htab_hash_pointer (tmpl), INSERT);
1713   *slot = build_tree_list (spec, tmpl);
1714 }
1715
1716 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1717    specialized class.  */
1718
1719 bool
1720 explicit_class_specialization_p (tree type)
1721 {
1722   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1723     return false;
1724   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1725 }
1726
1727 /* Print the list of functions at FNS, going through all the overloads
1728    for each element of the list.  Alternatively, FNS can not be a
1729    TREE_LIST, in which case it will be printed together with all the
1730    overloads.
1731
1732    MORE and *STR should respectively be FALSE and NULL when the function
1733    is called from the outside.  They are used internally on recursive
1734    calls.  print_candidates manages the two parameters and leaves NULL
1735    in *STR when it ends.  */
1736
1737 static void
1738 print_candidates_1 (tree fns, bool more, const char **str)
1739 {
1740   tree fn, fn2;
1741   char *spaces = NULL;
1742
1743   for (fn = fns; fn; fn = OVL_NEXT (fn))
1744     if (TREE_CODE (fn) == TREE_LIST)
1745       {
1746         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1747           print_candidates_1 (TREE_VALUE (fn2),
1748                               TREE_CHAIN (fn2) || more, str);
1749       }
1750     else
1751       {
1752         if (!*str)
1753           {
1754             /* Pick the prefix string.  */
1755             if (!more && !OVL_NEXT (fns))
1756               {
1757                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1758                 continue;
1759               }
1760
1761             *str = _("candidates are:");
1762             spaces = get_spaces (*str);
1763           }
1764         error ("%s %+#D", *str, OVL_CURRENT (fn));
1765         *str = spaces ? spaces : *str;
1766       }
1767
1768   if (!more)
1769     {
1770       free (spaces);
1771       *str = NULL;
1772     }
1773 }
1774
1775 /* Print the list of candidate FNS in an error message.  FNS can also
1776    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1777
1778 void
1779 print_candidates (tree fns)
1780 {
1781   const char *str = NULL;
1782   print_candidates_1 (fns, false, &str);
1783   gcc_assert (str == NULL);
1784 }
1785
1786 /* Returns the template (one of the functions given by TEMPLATE_ID)
1787    which can be specialized to match the indicated DECL with the
1788    explicit template args given in TEMPLATE_ID.  The DECL may be
1789    NULL_TREE if none is available.  In that case, the functions in
1790    TEMPLATE_ID are non-members.
1791
1792    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1793    specialization of a member template.
1794
1795    The TEMPLATE_COUNT is the number of references to qualifying
1796    template classes that appeared in the name of the function. See
1797    check_explicit_specialization for a more accurate description.
1798
1799    TSK indicates what kind of template declaration (if any) is being
1800    declared.  TSK_TEMPLATE indicates that the declaration given by
1801    DECL, though a FUNCTION_DECL, has template parameters, and is
1802    therefore a template function.
1803
1804    The template args (those explicitly specified and those deduced)
1805    are output in a newly created vector *TARGS_OUT.
1806
1807    If it is impossible to determine the result, an error message is
1808    issued.  The error_mark_node is returned to indicate failure.  */
1809
1810 static tree
1811 determine_specialization (tree template_id,
1812                           tree decl,
1813                           tree* targs_out,
1814                           int need_member_template,
1815                           int template_count,
1816                           tmpl_spec_kind tsk)
1817 {
1818   tree fns;
1819   tree targs;
1820   tree explicit_targs;
1821   tree candidates = NULL_TREE;
1822   /* A TREE_LIST of templates of which DECL may be a specialization.
1823      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1824      corresponding TREE_PURPOSE is the set of template arguments that,
1825      when used to instantiate the template, would produce a function
1826      with the signature of DECL.  */
1827   tree templates = NULL_TREE;
1828   int header_count;
1829   cp_binding_level *b;
1830
1831   *targs_out = NULL_TREE;
1832
1833   if (template_id == error_mark_node || decl == error_mark_node)
1834     return error_mark_node;
1835
1836   fns = TREE_OPERAND (template_id, 0);
1837   explicit_targs = TREE_OPERAND (template_id, 1);
1838
1839   if (fns == error_mark_node)
1840     return error_mark_node;
1841
1842   /* Check for baselinks.  */
1843   if (BASELINK_P (fns))
1844     fns = BASELINK_FUNCTIONS (fns);
1845
1846   if (!is_overloaded_fn (fns))
1847     {
1848       error ("%qD is not a function template", fns);
1849       return error_mark_node;
1850     }
1851
1852   /* Count the number of template headers specified for this
1853      specialization.  */
1854   header_count = 0;
1855   for (b = current_binding_level;
1856        b->kind == sk_template_parms;
1857        b = b->level_chain)
1858     ++header_count;
1859
1860   for (; fns; fns = OVL_NEXT (fns))
1861     {
1862       tree fn = OVL_CURRENT (fns);
1863
1864       if (TREE_CODE (fn) == TEMPLATE_DECL)
1865         {
1866           tree decl_arg_types;
1867           tree fn_arg_types;
1868           tree insttype;
1869
1870           /* In case of explicit specialization, we need to check if
1871              the number of template headers appearing in the specialization
1872              is correct. This is usually done in check_explicit_specialization,
1873              but the check done there cannot be exhaustive when specializing
1874              member functions. Consider the following code:
1875
1876              template <> void A<int>::f(int);
1877              template <> template <> void A<int>::f(int);
1878
1879              Assuming that A<int> is not itself an explicit specialization
1880              already, the first line specializes "f" which is a non-template
1881              member function, whilst the second line specializes "f" which
1882              is a template member function. So both lines are syntactically
1883              correct, and check_explicit_specialization does not reject
1884              them.
1885
1886              Here, we can do better, as we are matching the specialization
1887              against the declarations. We count the number of template
1888              headers, and we check if they match TEMPLATE_COUNT + 1
1889              (TEMPLATE_COUNT is the number of qualifying template classes,
1890              plus there must be another header for the member template
1891              itself).
1892
1893              Notice that if header_count is zero, this is not a
1894              specialization but rather a template instantiation, so there
1895              is no check we can perform here.  */
1896           if (header_count && header_count != template_count + 1)
1897             continue;
1898
1899           /* Check that the number of template arguments at the
1900              innermost level for DECL is the same as for FN.  */
1901           if (current_binding_level->kind == sk_template_parms
1902               && !current_binding_level->explicit_spec_p
1903               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1904                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1905                                       (current_template_parms))))
1906             continue;
1907
1908           /* DECL might be a specialization of FN.  */
1909           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1910           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1911
1912           /* For a non-static member function, we need to make sure
1913              that the const qualification is the same.  Since
1914              get_bindings does not try to merge the "this" parameter,
1915              we must do the comparison explicitly.  */
1916           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1917               && !same_type_p (TREE_VALUE (fn_arg_types),
1918                                TREE_VALUE (decl_arg_types)))
1919             continue;
1920
1921           /* Skip the "this" parameter and, for constructors of
1922              classes with virtual bases, the VTT parameter.  A
1923              full specialization of a constructor will have a VTT
1924              parameter, but a template never will.  */ 
1925           decl_arg_types 
1926             = skip_artificial_parms_for (decl, decl_arg_types);
1927           fn_arg_types 
1928             = skip_artificial_parms_for (fn, fn_arg_types);
1929
1930           /* Check that the number of function parameters matches.
1931              For example,
1932                template <class T> void f(int i = 0);
1933                template <> void f<int>();
1934              The specialization f<int> is invalid but is not caught
1935              by get_bindings below.  */
1936           if (cxx_dialect < cxx11
1937               && list_length (fn_arg_types) != list_length (decl_arg_types))
1938             continue;
1939
1940           /* Function templates cannot be specializations; there are
1941              no partial specializations of functions.  Therefore, if
1942              the type of DECL does not match FN, there is no
1943              match.  */
1944           if (tsk == tsk_template)
1945             {
1946               if (compparms (fn_arg_types, decl_arg_types))
1947                 candidates = tree_cons (NULL_TREE, fn, candidates);
1948               continue;
1949             }
1950
1951           /* See whether this function might be a specialization of this
1952              template.  */
1953           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1954
1955           if (!targs)
1956             /* We cannot deduce template arguments that when used to
1957                specialize TMPL will produce DECL.  */
1958             continue;
1959
1960           if (cxx_dialect >= cxx11)
1961             {
1962               /* Make sure that the deduced arguments actually work.  */
1963               insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
1964               if (insttype == error_mark_node)
1965                 continue;
1966               fn_arg_types
1967                 = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
1968               if (!compparms (fn_arg_types, decl_arg_types))
1969                 continue;
1970             }
1971
1972           /* Save this template, and the arguments deduced.  */
1973           templates = tree_cons (targs, fn, templates);
1974         }
1975       else if (need_member_template)
1976         /* FN is an ordinary member function, and we need a
1977            specialization of a member template.  */
1978         ;
1979       else if (TREE_CODE (fn) != FUNCTION_DECL)
1980         /* We can get IDENTIFIER_NODEs here in certain erroneous
1981            cases.  */
1982         ;
1983       else if (!DECL_FUNCTION_MEMBER_P (fn))
1984         /* This is just an ordinary non-member function.  Nothing can
1985            be a specialization of that.  */
1986         ;
1987       else if (DECL_ARTIFICIAL (fn))
1988         /* Cannot specialize functions that are created implicitly.  */
1989         ;
1990       else
1991         {
1992           tree decl_arg_types;
1993
1994           /* This is an ordinary member function.  However, since
1995              we're here, we can assume it's enclosing class is a
1996              template class.  For example,
1997
1998                template <typename T> struct S { void f(); };
1999                template <> void S<int>::f() {}
2000
2001              Here, S<int>::f is a non-template, but S<int> is a
2002              template class.  If FN has the same type as DECL, we
2003              might be in business.  */
2004
2005           if (!DECL_TEMPLATE_INFO (fn))
2006             /* Its enclosing class is an explicit specialization
2007                of a template class.  This is not a candidate.  */
2008             continue;
2009
2010           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2011                             TREE_TYPE (TREE_TYPE (fn))))
2012             /* The return types differ.  */
2013             continue;
2014
2015           /* Adjust the type of DECL in case FN is a static member.  */
2016           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2017           if (DECL_STATIC_FUNCTION_P (fn)
2018               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2019             decl_arg_types = TREE_CHAIN (decl_arg_types);
2020
2021           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2022                          decl_arg_types))
2023             /* They match!  */
2024             candidates = tree_cons (NULL_TREE, fn, candidates);
2025         }
2026     }
2027
2028   if (templates && TREE_CHAIN (templates))
2029     {
2030       /* We have:
2031
2032            [temp.expl.spec]
2033
2034            It is possible for a specialization with a given function
2035            signature to be instantiated from more than one function
2036            template.  In such cases, explicit specification of the
2037            template arguments must be used to uniquely identify the
2038            function template specialization being specialized.
2039
2040          Note that here, there's no suggestion that we're supposed to
2041          determine which of the candidate templates is most
2042          specialized.  However, we, also have:
2043
2044            [temp.func.order]
2045
2046            Partial ordering of overloaded function template
2047            declarations is used in the following contexts to select
2048            the function template to which a function template
2049            specialization refers:
2050
2051            -- when an explicit specialization refers to a function
2052               template.
2053
2054          So, we do use the partial ordering rules, at least for now.
2055          This extension can only serve to make invalid programs valid,
2056          so it's safe.  And, there is strong anecdotal evidence that
2057          the committee intended the partial ordering rules to apply;
2058          the EDG front end has that behavior, and John Spicer claims
2059          that the committee simply forgot to delete the wording in
2060          [temp.expl.spec].  */
2061       tree tmpl = most_specialized_instantiation (templates);
2062       if (tmpl != error_mark_node)
2063         {
2064           templates = tmpl;
2065           TREE_CHAIN (templates) = NULL_TREE;
2066         }
2067     }
2068
2069   if (templates == NULL_TREE && candidates == NULL_TREE)
2070     {
2071       error ("template-id %qD for %q+D does not match any template "
2072              "declaration", template_id, decl);
2073       if (header_count && header_count != template_count + 1)
2074         inform (input_location, "saw %d %<template<>%>, need %d for "
2075                 "specializing a member function template",
2076                 header_count, template_count + 1);
2077       return error_mark_node;
2078     }
2079   else if ((templates && TREE_CHAIN (templates))
2080            || (candidates && TREE_CHAIN (candidates))
2081            || (templates && candidates))
2082     {
2083       error ("ambiguous template specialization %qD for %q+D",
2084              template_id, decl);
2085       candidates = chainon (candidates, templates);
2086       print_candidates (candidates);
2087       return error_mark_node;
2088     }
2089
2090   /* We have one, and exactly one, match.  */
2091   if (candidates)
2092     {
2093       tree fn = TREE_VALUE (candidates);
2094       *targs_out = copy_node (DECL_TI_ARGS (fn));
2095       /* DECL is a re-declaration or partial instantiation of a template
2096          function.  */
2097       if (TREE_CODE (fn) == TEMPLATE_DECL)
2098         return fn;
2099       /* It was a specialization of an ordinary member function in a
2100          template class.  */
2101       return DECL_TI_TEMPLATE (fn);
2102     }
2103
2104   /* It was a specialization of a template.  */
2105   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2106   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2107     {
2108       *targs_out = copy_node (targs);
2109       SET_TMPL_ARGS_LEVEL (*targs_out,
2110                            TMPL_ARGS_DEPTH (*targs_out),
2111                            TREE_PURPOSE (templates));
2112     }
2113   else
2114     *targs_out = TREE_PURPOSE (templates);
2115   return TREE_VALUE (templates);
2116 }
2117
2118 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2119    but with the default argument values filled in from those in the
2120    TMPL_TYPES.  */
2121
2122 static tree
2123 copy_default_args_to_explicit_spec_1 (tree spec_types,
2124                                       tree tmpl_types)
2125 {
2126   tree new_spec_types;
2127
2128   if (!spec_types)
2129     return NULL_TREE;
2130
2131   if (spec_types == void_list_node)
2132     return void_list_node;
2133
2134   /* Substitute into the rest of the list.  */
2135   new_spec_types =
2136     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2137                                           TREE_CHAIN (tmpl_types));
2138
2139   /* Add the default argument for this parameter.  */
2140   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2141                          TREE_VALUE (spec_types),
2142                          new_spec_types);
2143 }
2144
2145 /* DECL is an explicit specialization.  Replicate default arguments
2146    from the template it specializes.  (That way, code like:
2147
2148      template <class T> void f(T = 3);
2149      template <> void f(double);
2150      void g () { f (); }
2151
2152    works, as required.)  An alternative approach would be to look up
2153    the correct default arguments at the call-site, but this approach
2154    is consistent with how implicit instantiations are handled.  */
2155
2156 static void
2157 copy_default_args_to_explicit_spec (tree decl)
2158 {
2159   tree tmpl;
2160   tree spec_types;
2161   tree tmpl_types;
2162   tree new_spec_types;
2163   tree old_type;
2164   tree new_type;
2165   tree t;
2166   tree object_type = NULL_TREE;
2167   tree in_charge = NULL_TREE;
2168   tree vtt = NULL_TREE;
2169
2170   /* See if there's anything we need to do.  */
2171   tmpl = DECL_TI_TEMPLATE (decl);
2172   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2173   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2174     if (TREE_PURPOSE (t))
2175       break;
2176   if (!t)
2177     return;
2178
2179   old_type = TREE_TYPE (decl);
2180   spec_types = TYPE_ARG_TYPES (old_type);
2181
2182   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2183     {
2184       /* Remove the this pointer, but remember the object's type for
2185          CV quals.  */
2186       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2187       spec_types = TREE_CHAIN (spec_types);
2188       tmpl_types = TREE_CHAIN (tmpl_types);
2189
2190       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2191         {
2192           /* DECL may contain more parameters than TMPL due to the extra
2193              in-charge parameter in constructors and destructors.  */
2194           in_charge = spec_types;
2195           spec_types = TREE_CHAIN (spec_types);
2196         }
2197       if (DECL_HAS_VTT_PARM_P (decl))
2198         {
2199           vtt = spec_types;
2200           spec_types = TREE_CHAIN (spec_types);
2201         }
2202     }
2203
2204   /* Compute the merged default arguments.  */
2205   new_spec_types =
2206     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2207
2208   /* Compute the new FUNCTION_TYPE.  */
2209   if (object_type)
2210     {
2211       if (vtt)
2212         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2213                                          TREE_VALUE (vtt),
2214                                          new_spec_types);
2215
2216       if (in_charge)
2217         /* Put the in-charge parameter back.  */
2218         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2219                                          TREE_VALUE (in_charge),
2220                                          new_spec_types);
2221
2222       new_type = build_method_type_directly (object_type,
2223                                              TREE_TYPE (old_type),
2224                                              new_spec_types);
2225     }
2226   else
2227     new_type = build_function_type (TREE_TYPE (old_type),
2228                                     new_spec_types);
2229   new_type = cp_build_type_attribute_variant (new_type,
2230                                               TYPE_ATTRIBUTES (old_type));
2231   new_type = build_exception_variant (new_type,
2232                                       TYPE_RAISES_EXCEPTIONS (old_type));
2233   TREE_TYPE (decl) = new_type;
2234 }
2235
2236 /* Check to see if the function just declared, as indicated in
2237    DECLARATOR, and in DECL, is a specialization of a function
2238    template.  We may also discover that the declaration is an explicit
2239    instantiation at this point.
2240
2241    Returns DECL, or an equivalent declaration that should be used
2242    instead if all goes well.  Issues an error message if something is
2243    amiss.  Returns error_mark_node if the error is not easily
2244    recoverable.
2245
2246    FLAGS is a bitmask consisting of the following flags:
2247
2248    2: The function has a definition.
2249    4: The function is a friend.
2250
2251    The TEMPLATE_COUNT is the number of references to qualifying
2252    template classes that appeared in the name of the function.  For
2253    example, in
2254
2255      template <class T> struct S { void f(); };
2256      void S<int>::f();
2257
2258    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2259    classes are not counted in the TEMPLATE_COUNT, so that in
2260
2261      template <class T> struct S {};
2262      template <> struct S<int> { void f(); }
2263      template <> void S<int>::f();
2264
2265    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2266    invalid; there should be no template <>.)
2267
2268    If the function is a specialization, it is marked as such via
2269    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2270    is set up correctly, and it is added to the list of specializations
2271    for that template.  */
2272
2273 tree
2274 check_explicit_specialization (tree declarator,
2275                                tree decl,
2276                                int template_count,
2277                                int flags)
2278 {
2279   int have_def = flags & 2;
2280   int is_friend = flags & 4;
2281   int specialization = 0;
2282   int explicit_instantiation = 0;
2283   int member_specialization = 0;
2284   tree ctype = DECL_CLASS_CONTEXT (decl);
2285   tree dname = DECL_NAME (decl);
2286   tmpl_spec_kind tsk;
2287
2288   if (is_friend)
2289     {
2290       if (!processing_specialization)
2291         tsk = tsk_none;
2292       else
2293         tsk = tsk_excessive_parms;
2294     }
2295   else
2296     tsk = current_tmpl_spec_kind (template_count);
2297
2298   switch (tsk)
2299     {
2300     case tsk_none:
2301       if (processing_specialization)
2302         {
2303           specialization = 1;
2304           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2305         }
2306       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2307         {
2308           if (is_friend)
2309             /* This could be something like:
2310
2311                template <class T> void f(T);
2312                class S { friend void f<>(int); }  */
2313             specialization = 1;
2314           else
2315             {
2316               /* This case handles bogus declarations like template <>
2317                  template <class T> void f<int>(); */
2318
2319               error ("template-id %qD in declaration of primary template",
2320                      declarator);
2321               return decl;
2322             }
2323         }
2324       break;
2325
2326     case tsk_invalid_member_spec:
2327       /* The error has already been reported in
2328          check_specialization_scope.  */
2329       return error_mark_node;
2330
2331     case tsk_invalid_expl_inst:
2332       error ("template parameter list used in explicit instantiation");
2333
2334       /* Fall through.  */
2335
2336     case tsk_expl_inst:
2337       if (have_def)
2338         error ("definition provided for explicit instantiation");
2339
2340       explicit_instantiation = 1;
2341       break;
2342
2343     case tsk_excessive_parms:
2344     case tsk_insufficient_parms:
2345       if (tsk == tsk_excessive_parms)
2346         error ("too many template parameter lists in declaration of %qD",
2347                decl);
2348       else if (template_header_count)
2349         error("too few template parameter lists in declaration of %qD", decl);
2350       else
2351         error("explicit specialization of %qD must be introduced by "
2352               "%<template <>%>", decl);
2353
2354       /* Fall through.  */
2355     case tsk_expl_spec:
2356       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2357       if (ctype)
2358         member_specialization = 1;
2359       else
2360         specialization = 1;
2361       break;
2362
2363     case tsk_template:
2364       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2365         {
2366           /* This case handles bogus declarations like template <>
2367              template <class T> void f<int>(); */
2368
2369           if (uses_template_parms (declarator))
2370             error ("function template partial specialization %qD "
2371                    "is not allowed", declarator);
2372           else
2373             error ("template-id %qD in declaration of primary template",
2374                    declarator);
2375           return decl;
2376         }
2377
2378       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2379         /* This is a specialization of a member template, without
2380            specialization the containing class.  Something like:
2381
2382              template <class T> struct S {
2383                template <class U> void f (U);
2384              };
2385              template <> template <class U> void S<int>::f(U) {}
2386
2387            That's a specialization -- but of the entire template.  */
2388         specialization = 1;
2389       break;
2390
2391     default:
2392       gcc_unreachable ();
2393     }
2394
2395   if (specialization || member_specialization)
2396     {
2397       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2398       for (; t; t = TREE_CHAIN (t))
2399         if (TREE_PURPOSE (t))
2400           {
2401             permerror (input_location, 
2402                        "default argument specified in explicit specialization");
2403             break;
2404           }
2405     }
2406
2407   if (specialization || member_specialization || explicit_instantiation)
2408     {
2409       tree tmpl = NULL_TREE;
2410       tree targs = NULL_TREE;
2411
2412       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2413       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2414         {
2415           tree fns;
2416
2417           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2418           if (ctype)
2419             fns = dname;
2420           else
2421             {
2422               /* If there is no class context, the explicit instantiation
2423                  must be at namespace scope.  */
2424               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2425
2426               /* Find the namespace binding, using the declaration
2427                  context.  */
2428               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2429                                            false, true);
2430               if (fns == error_mark_node || !is_overloaded_fn (fns))
2431                 {
2432                   error ("%qD is not a template function", dname);
2433                   fns = error_mark_node;
2434                 }
2435               else
2436                 {
2437                   tree fn = OVL_CURRENT (fns);
2438                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2439                                                 CP_DECL_CONTEXT (fn)))
2440                     error ("%qD is not declared in %qD",
2441                            decl, current_namespace);
2442                 }
2443             }
2444
2445           declarator = lookup_template_function (fns, NULL_TREE);
2446         }
2447
2448       if (declarator == error_mark_node)
2449         return error_mark_node;
2450
2451       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2452         {
2453           if (!explicit_instantiation)
2454             /* A specialization in class scope.  This is invalid,
2455                but the error will already have been flagged by
2456                check_specialization_scope.  */
2457             return error_mark_node;
2458           else
2459             {
2460               /* It's not valid to write an explicit instantiation in
2461                  class scope, e.g.:
2462
2463                    class C { template void f(); }
2464
2465                    This case is caught by the parser.  However, on
2466                    something like:
2467
2468                    template class C { void f(); };
2469
2470                    (which is invalid) we can get here.  The error will be
2471                    issued later.  */
2472               ;
2473             }
2474
2475           return decl;
2476         }
2477       else if (ctype != NULL_TREE
2478                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2479                    IDENTIFIER_NODE))
2480         {
2481           /* Find the list of functions in ctype that have the same
2482              name as the declared function.  */
2483           tree name = TREE_OPERAND (declarator, 0);
2484           tree fns = NULL_TREE;
2485           int idx;
2486
2487           if (constructor_name_p (name, ctype))
2488             {
2489               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2490
2491               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2492                   : !CLASSTYPE_DESTRUCTORS (ctype))
2493                 {
2494                   /* From [temp.expl.spec]:
2495
2496                      If such an explicit specialization for the member
2497                      of a class template names an implicitly-declared
2498                      special member function (clause _special_), the
2499                      program is ill-formed.
2500
2501                      Similar language is found in [temp.explicit].  */
2502                   error ("specialization of implicitly-declared special member function");
2503                   return error_mark_node;
2504                 }
2505
2506               name = is_constructor ? ctor_identifier : dtor_identifier;
2507             }
2508
2509           if (!DECL_CONV_FN_P (decl))
2510             {
2511               idx = lookup_fnfields_1 (ctype, name);
2512               if (idx >= 0)
2513                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2514             }
2515           else
2516             {
2517               VEC(tree,gc) *methods;
2518               tree ovl;
2519
2520               /* For a type-conversion operator, we cannot do a
2521                  name-based lookup.  We might be looking for `operator
2522                  int' which will be a specialization of `operator T'.
2523                  So, we find *all* the conversion operators, and then
2524                  select from them.  */
2525               fns = NULL_TREE;
2526
2527               methods = CLASSTYPE_METHOD_VEC (ctype);
2528               if (methods)
2529                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2530                      VEC_iterate (tree, methods, idx, ovl);
2531                      ++idx)
2532                   {
2533                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2534                       /* There are no more conversion functions.  */
2535                       break;
2536
2537                     /* Glue all these conversion functions together
2538                        with those we already have.  */
2539                     for (; ovl; ovl = OVL_NEXT (ovl))
2540                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2541                   }
2542             }
2543
2544           if (fns == NULL_TREE)
2545             {
2546               error ("no member function %qD declared in %qT", name, ctype);
2547               return error_mark_node;
2548             }
2549           else
2550             TREE_OPERAND (declarator, 0) = fns;
2551         }
2552
2553       /* Figure out what exactly is being specialized at this point.
2554          Note that for an explicit instantiation, even one for a
2555          member function, we cannot tell apriori whether the
2556          instantiation is for a member template, or just a member
2557          function of a template class.  Even if a member template is
2558          being instantiated, the member template arguments may be
2559          elided if they can be deduced from the rest of the
2560          declaration.  */
2561       tmpl = determine_specialization (declarator, decl,
2562                                        &targs,
2563                                        member_specialization,
2564                                        template_count,
2565                                        tsk);
2566
2567       if (!tmpl || tmpl == error_mark_node)
2568         /* We couldn't figure out what this declaration was
2569            specializing.  */
2570         return error_mark_node;
2571       else
2572         {
2573           tree gen_tmpl = most_general_template (tmpl);
2574
2575           if (explicit_instantiation)
2576             {
2577               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2578                  is done by do_decl_instantiation later.  */
2579
2580               int arg_depth = TMPL_ARGS_DEPTH (targs);
2581               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2582
2583               if (arg_depth > parm_depth)
2584                 {
2585                   /* If TMPL is not the most general template (for
2586                      example, if TMPL is a friend template that is
2587                      injected into namespace scope), then there will
2588                      be too many levels of TARGS.  Remove some of them
2589                      here.  */
2590                   int i;
2591                   tree new_targs;
2592
2593                   new_targs = make_tree_vec (parm_depth);
2594                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2595                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2596                       = TREE_VEC_ELT (targs, i);
2597                   targs = new_targs;
2598                 }
2599
2600               return instantiate_template (tmpl, targs, tf_error);
2601             }
2602
2603           /* If we thought that the DECL was a member function, but it
2604              turns out to be specializing a static member function,
2605              make DECL a static member function as well.  */
2606           if (DECL_STATIC_FUNCTION_P (tmpl)
2607               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2608             revert_static_member_fn (decl);
2609
2610           /* If this is a specialization of a member template of a
2611              template class, we want to return the TEMPLATE_DECL, not
2612              the specialization of it.  */
2613           if (tsk == tsk_template)
2614             {
2615               tree result = DECL_TEMPLATE_RESULT (tmpl);
2616               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2617               DECL_INITIAL (result) = NULL_TREE;
2618               if (have_def)
2619                 {
2620                   tree parm;
2621                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2622                   DECL_SOURCE_LOCATION (result)
2623                     = DECL_SOURCE_LOCATION (decl);
2624                   /* We want to use the argument list specified in the
2625                      definition, not in the original declaration.  */
2626                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2627                   for (parm = DECL_ARGUMENTS (result); parm;
2628                        parm = DECL_CHAIN (parm))
2629                     DECL_CONTEXT (parm) = result;
2630                 }
2631               return register_specialization (tmpl, gen_tmpl, targs,
2632                                               is_friend, 0);
2633             }
2634
2635           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2636           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2637
2638           /* Inherit default function arguments from the template
2639              DECL is specializing.  */
2640           copy_default_args_to_explicit_spec (decl);
2641
2642           /* This specialization has the same protection as the
2643              template it specializes.  */
2644           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2645           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2646
2647           /* 7.1.1-1 [dcl.stc]
2648
2649              A storage-class-specifier shall not be specified in an
2650              explicit specialization...
2651
2652              The parser rejects these, so unless action is taken here,
2653              explicit function specializations will always appear with
2654              global linkage.
2655
2656              The action recommended by the C++ CWG in response to C++
2657              defect report 605 is to make the storage class and linkage
2658              of the explicit specialization match the templated function:
2659
2660              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2661            */
2662           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2663             {
2664               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2665               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2666
2667               /* This specialization has the same linkage and visibility as
2668                  the function template it specializes.  */
2669               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2670               if (! TREE_PUBLIC (decl))
2671                 {
2672                   DECL_INTERFACE_KNOWN (decl) = 1;
2673                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2674                 }
2675               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2676               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2677                 {
2678                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2679                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2680                 }
2681             }
2682
2683           /* If DECL is a friend declaration, declared using an
2684              unqualified name, the namespace associated with DECL may
2685              have been set incorrectly.  For example, in:
2686
2687                template <typename T> void f(T);
2688                namespace N {
2689                  struct S { friend void f<int>(int); }
2690                }
2691
2692              we will have set the DECL_CONTEXT for the friend
2693              declaration to N, rather than to the global namespace.  */
2694           if (DECL_NAMESPACE_SCOPE_P (decl))
2695             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2696
2697           if (is_friend && !have_def)
2698             /* This is not really a declaration of a specialization.
2699                It's just the name of an instantiation.  But, it's not
2700                a request for an instantiation, either.  */
2701             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2702           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2703             /* This is indeed a specialization.  In case of constructors
2704                and destructors, we need in-charge and not-in-charge
2705                versions in V3 ABI.  */
2706             clone_function_decl (decl, /*update_method_vec_p=*/0);
2707
2708           /* Register this specialization so that we can find it
2709              again.  */
2710           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2711         }
2712     }
2713
2714   return decl;
2715 }
2716
2717 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2718    parameters.  These are represented in the same format used for
2719    DECL_TEMPLATE_PARMS.  */
2720
2721 int
2722 comp_template_parms (const_tree parms1, const_tree parms2)
2723 {
2724   const_tree p1;
2725   const_tree p2;
2726
2727   if (parms1 == parms2)
2728     return 1;
2729
2730   for (p1 = parms1, p2 = parms2;
2731        p1 != NULL_TREE && p2 != NULL_TREE;
2732        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2733     {
2734       tree t1 = TREE_VALUE (p1);
2735       tree t2 = TREE_VALUE (p2);
2736       int i;
2737
2738       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2739       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2740
2741       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2742         return 0;
2743
2744       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2745         {
2746           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2747           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2748
2749           /* If either of the template parameters are invalid, assume
2750              they match for the sake of error recovery. */
2751           if (parm1 == error_mark_node || parm2 == error_mark_node)
2752             return 1;
2753
2754           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2755             return 0;
2756
2757           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2758               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2759                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2760             continue;
2761           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2762             return 0;
2763         }
2764     }
2765
2766   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2767     /* One set of parameters has more parameters lists than the
2768        other.  */
2769     return 0;
2770
2771   return 1;
2772 }
2773
2774 /* Determine whether PARM is a parameter pack.  */
2775
2776 bool 
2777 template_parameter_pack_p (const_tree parm)
2778 {
2779   /* Determine if we have a non-type template parameter pack.  */
2780   if (TREE_CODE (parm) == PARM_DECL)
2781     return (DECL_TEMPLATE_PARM_P (parm) 
2782             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2783   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2784     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2785
2786   /* If this is a list of template parameters, we could get a
2787      TYPE_DECL or a TEMPLATE_DECL.  */ 
2788   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2789     parm = TREE_TYPE (parm);
2790
2791   /* Otherwise it must be a type template parameter.  */
2792   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2793            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2794           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2795 }
2796
2797 /* Determine if T is a function parameter pack.  */
2798
2799 bool
2800 function_parameter_pack_p (const_tree t)
2801 {
2802   if (t && TREE_CODE (t) == PARM_DECL)
2803     return FUNCTION_PARAMETER_PACK_P (t);
2804   return false;
2805 }
2806
2807 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2808    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2809
2810 tree
2811 get_function_template_decl (const_tree primary_func_tmpl_inst)
2812 {
2813   if (! primary_func_tmpl_inst
2814       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2815       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2816     return NULL;
2817
2818   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2819 }
2820
2821 /* Return true iff the function parameter PARAM_DECL was expanded
2822    from the function parameter pack PACK.  */
2823
2824 bool
2825 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2826 {
2827   if (DECL_ARTIFICIAL (param_decl)
2828       || !function_parameter_pack_p (pack))
2829     return false;
2830
2831   /* The parameter pack and its pack arguments have the same
2832      DECL_PARM_INDEX.  */
2833   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2834 }
2835
2836 /* Determine whether ARGS describes a variadic template args list,
2837    i.e., one that is terminated by a template argument pack.  */
2838
2839 static bool 
2840 template_args_variadic_p (tree args)
2841 {
2842   int nargs;
2843   tree last_parm;
2844
2845   if (args == NULL_TREE)
2846     return false;
2847
2848   args = INNERMOST_TEMPLATE_ARGS (args);
2849   nargs = TREE_VEC_LENGTH (args);
2850
2851   if (nargs == 0)
2852     return false;
2853
2854   last_parm = TREE_VEC_ELT (args, nargs - 1);
2855
2856   return ARGUMENT_PACK_P (last_parm);
2857 }
2858
2859 /* Generate a new name for the parameter pack name NAME (an
2860    IDENTIFIER_NODE) that incorporates its */
2861
2862 static tree
2863 make_ith_pack_parameter_name (tree name, int i)
2864 {
2865   /* Munge the name to include the parameter index.  */
2866 #define NUMBUF_LEN 128
2867   char numbuf[NUMBUF_LEN];
2868   char* newname;
2869   int newname_len;
2870
2871   if (name == NULL_TREE)
2872     return name;
2873   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2874   newname_len = IDENTIFIER_LENGTH (name)
2875                 + strlen (numbuf) + 2;
2876   newname = (char*)alloca (newname_len);
2877   snprintf (newname, newname_len,
2878             "%s#%i", IDENTIFIER_POINTER (name), i);
2879   return get_identifier (newname);
2880 }
2881
2882 /* Return true if T is a primary function, class or alias template
2883    instantiation.  */
2884
2885 bool
2886 primary_template_instantiation_p (const_tree t)
2887 {
2888   if (!t)
2889     return false;
2890
2891   if (TREE_CODE (t) == FUNCTION_DECL)
2892     return DECL_LANG_SPECIFIC (t)
2893            && DECL_TEMPLATE_INSTANTIATION (t)
2894            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2895   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
2896     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2897            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2898   else if (TYPE_P (t)
2899            && TYPE_TEMPLATE_INFO (t)
2900            && PRIMARY_TEMPLATE_P (TYPE_TI_TEMPLATE (t))
2901            && DECL_TEMPLATE_INSTANTIATION (TYPE_NAME (t)))
2902     return true;
2903   return false;
2904 }
2905
2906 /* Return true if PARM is a template template parameter.  */
2907
2908 bool
2909 template_template_parameter_p (const_tree parm)
2910 {
2911   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2912 }
2913
2914 /* Return the template parameters of T if T is a
2915    primary template instantiation, NULL otherwise.  */
2916
2917 tree
2918 get_primary_template_innermost_parameters (const_tree t)
2919 {
2920   tree parms = NULL, template_info = NULL;
2921
2922   if ((template_info = get_template_info (t))
2923       && primary_template_instantiation_p (t))
2924     parms = INNERMOST_TEMPLATE_PARMS
2925         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2926
2927   return parms;
2928 }
2929
2930 /* Return the template parameters of the LEVELth level from the full list
2931    of template parameters PARMS.  */
2932
2933 tree
2934 get_template_parms_at_level (tree parms, int level)
2935 {
2936   tree p;
2937   if (!parms
2938       || TREE_CODE (parms) != TREE_LIST
2939       || level > TMPL_PARMS_DEPTH (parms))
2940     return NULL_TREE;
2941
2942   for (p = parms; p; p = TREE_CHAIN (p))
2943     if (TMPL_PARMS_DEPTH (p) == level)
2944       return p;
2945
2946   return NULL_TREE;
2947 }
2948
2949 /* Returns the template arguments of T if T is a template instantiation,
2950    NULL otherwise.  */
2951
2952 tree
2953 get_template_innermost_arguments (const_tree t)
2954 {
2955   tree args = NULL, template_info = NULL;
2956
2957   if ((template_info = get_template_info (t))
2958       && TI_ARGS (template_info))
2959     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2960
2961   return args;
2962 }
2963
2964 /* Return the argument pack elements of T if T is a template argument pack,
2965    NULL otherwise.  */
2966
2967 tree
2968 get_template_argument_pack_elems (const_tree t)
2969 {
2970   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2971       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2972     return NULL;
2973
2974   return ARGUMENT_PACK_ARGS (t);
2975 }
2976
2977 /* Structure used to track the progress of find_parameter_packs_r.  */
2978 struct find_parameter_pack_data 
2979 {
2980   /* TREE_LIST that will contain all of the parameter packs found by
2981      the traversal.  */
2982   tree* parameter_packs;
2983
2984   /* Set of AST nodes that have been visited by the traversal.  */
2985   struct pointer_set_t *visited;
2986 };
2987
2988 /* Identifies all of the argument packs that occur in a template
2989    argument and appends them to the TREE_LIST inside DATA, which is a
2990    find_parameter_pack_data structure. This is a subroutine of
2991    make_pack_expansion and uses_parameter_packs.  */
2992 static tree
2993 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2994 {
2995   tree t = *tp;
2996   struct find_parameter_pack_data* ppd = 
2997     (struct find_parameter_pack_data*)data;
2998   bool parameter_pack_p = false;
2999
3000   /* Handle type aliases/typedefs.  */
3001   if (TYPE_P (t)
3002       && TYPE_NAME (t)
3003       && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
3004       && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3005     {
3006       if (TYPE_TEMPLATE_INFO (t))
3007         cp_walk_tree (&TYPE_TI_ARGS (t),
3008                       &find_parameter_packs_r,
3009                       ppd, ppd->visited);
3010       *walk_subtrees = 0;
3011       return NULL_TREE;
3012     }
3013
3014   /* Identify whether this is a parameter pack or not.  */
3015   switch (TREE_CODE (t))
3016     {
3017     case TEMPLATE_PARM_INDEX:
3018       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3019         parameter_pack_p = true;
3020       break;
3021
3022     case TEMPLATE_TYPE_PARM:
3023       t = TYPE_MAIN_VARIANT (t);
3024     case TEMPLATE_TEMPLATE_PARM:
3025       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3026         parameter_pack_p = true;
3027       break;
3028
3029     case PARM_DECL:
3030       if (FUNCTION_PARAMETER_PACK_P (t))
3031         {
3032           /* We don't want to walk into the type of a PARM_DECL,
3033              because we don't want to see the type parameter pack.  */
3034           *walk_subtrees = 0;
3035           parameter_pack_p = true;
3036         }
3037       break;
3038
3039     case BASES:
3040       parameter_pack_p = true;
3041       break;
3042     default:
3043       /* Not a parameter pack.  */
3044       break;
3045     }
3046
3047   if (parameter_pack_p)
3048     {
3049       /* Add this parameter pack to the list.  */
3050       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3051     }
3052
3053   if (TYPE_P (t))
3054     cp_walk_tree (&TYPE_CONTEXT (t), 
3055                   &find_parameter_packs_r, ppd, ppd->visited);
3056
3057   /* This switch statement will return immediately if we don't find a
3058      parameter pack.  */
3059   switch (TREE_CODE (t)) 
3060     {
3061     case TEMPLATE_PARM_INDEX:
3062       return NULL_TREE;
3063
3064     case BOUND_TEMPLATE_TEMPLATE_PARM:
3065       /* Check the template itself.  */
3066       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
3067                     &find_parameter_packs_r, ppd, ppd->visited);
3068       /* Check the template arguments.  */
3069       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
3070                     ppd->visited);
3071       *walk_subtrees = 0;
3072       return NULL_TREE;
3073
3074     case TEMPLATE_TYPE_PARM:
3075     case TEMPLATE_TEMPLATE_PARM:
3076       return NULL_TREE;
3077
3078     case PARM_DECL:
3079       return NULL_TREE;
3080
3081     case RECORD_TYPE:
3082       if (TYPE_PTRMEMFUNC_P (t))
3083         return NULL_TREE;
3084       /* Fall through.  */
3085
3086     case UNION_TYPE:
3087     case ENUMERAL_TYPE:
3088       if (TYPE_TEMPLATE_INFO (t))
3089         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3090                       &find_parameter_packs_r, ppd, ppd->visited);
3091
3092       *walk_subtrees = 0;
3093       return NULL_TREE;
3094
3095     case CONSTRUCTOR:
3096     case TEMPLATE_DECL:
3097       cp_walk_tree (&TREE_TYPE (t),
3098                     &find_parameter_packs_r, ppd, ppd->visited);
3099       return NULL_TREE;
3100  
3101     case TYPENAME_TYPE:
3102       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3103                    ppd, ppd->visited);
3104       *walk_subtrees = 0;
3105       return NULL_TREE;
3106       
3107     case TYPE_PACK_EXPANSION:
3108     case EXPR_PACK_EXPANSION:
3109       *walk_subtrees = 0;
3110       return NULL_TREE;
3111
3112     case INTEGER_TYPE:
3113       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3114                     ppd, ppd->visited);
3115       *walk_subtrees = 0;
3116       return NULL_TREE;
3117
3118     case IDENTIFIER_NODE:
3119       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3120                     ppd->visited);
3121       *walk_subtrees = 0;
3122       return NULL_TREE;
3123
3124     default:
3125       return NULL_TREE;
3126     }
3127
3128   return NULL_TREE;
3129 }
3130
3131 /* Determines if the expression or type T uses any parameter packs.  */
3132 bool
3133 uses_parameter_packs (tree t)
3134 {
3135   tree parameter_packs = NULL_TREE;
3136   struct find_parameter_pack_data ppd;
3137   ppd.parameter_packs = &parameter_packs;
3138   ppd.visited = pointer_set_create ();
3139   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3140   pointer_set_destroy (ppd.visited);
3141   return parameter_packs != NULL_TREE;
3142 }
3143
3144 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3145    representation a base-class initializer into a parameter pack
3146    expansion. If all goes well, the resulting node will be an
3147    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3148    respectively.  */
3149 tree 
3150 make_pack_expansion (tree arg)
3151 {
3152   tree result;
3153   tree parameter_packs = NULL_TREE;
3154   bool for_types = false;
3155   struct find_parameter_pack_data ppd;
3156
3157   if (!arg || arg == error_mark_node)
3158     return arg;
3159
3160   if (TREE_CODE (arg) == TREE_LIST)
3161     {
3162       /* The only time we will see a TREE_LIST here is for a base
3163          class initializer.  In this case, the TREE_PURPOSE will be a
3164          _TYPE node (representing the base class expansion we're
3165          initializing) and the TREE_VALUE will be a TREE_LIST
3166          containing the initialization arguments. 
3167
3168          The resulting expansion looks somewhat different from most
3169          expansions. Rather than returning just one _EXPANSION, we
3170          return a TREE_LIST whose TREE_PURPOSE is a
3171          TYPE_PACK_EXPANSION containing the bases that will be
3172          initialized.  The TREE_VALUE will be identical to the
3173          original TREE_VALUE, which is a list of arguments that will
3174          be passed to each base.  We do not introduce any new pack
3175          expansion nodes into the TREE_VALUE (although it is possible
3176          that some already exist), because the TREE_PURPOSE and
3177          TREE_VALUE all need to be expanded together with the same
3178          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3179          resulting TREE_PURPOSE will mention the parameter packs in
3180          both the bases and the arguments to the bases.  */
3181       tree purpose;
3182       tree value;
3183       tree parameter_packs = NULL_TREE;
3184
3185       /* Determine which parameter packs will be used by the base
3186          class expansion.  */
3187       ppd.visited = pointer_set_create ();
3188       ppd.parameter_packs = &parameter_packs;
3189       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3190                     &ppd, ppd.visited);
3191
3192       if (parameter_packs == NULL_TREE)
3193         {
3194           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3195           pointer_set_destroy (ppd.visited);
3196           return error_mark_node;
3197         }
3198
3199       if (TREE_VALUE (arg) != void_type_node)
3200         {
3201           /* Collect the sets of parameter packs used in each of the
3202              initialization arguments.  */
3203           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3204             {
3205               /* Determine which parameter packs will be expanded in this
3206                  argument.  */
3207               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3208                             &ppd, ppd.visited);
3209             }
3210         }
3211
3212       pointer_set_destroy (ppd.visited);
3213
3214       /* Create the pack expansion type for the base type.  */
3215       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3216       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3217       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3218
3219       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3220          they will rarely be compared to anything.  */
3221       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3222
3223       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3224     }
3225
3226   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3227     for_types = true;
3228
3229   /* Build the PACK_EXPANSION_* node.  */
3230   result = for_types
3231      ? cxx_make_type (TYPE_PACK_EXPANSION)
3232      : make_node (EXPR_PACK_EXPANSION);
3233   SET_PACK_EXPANSION_PATTERN (result, arg);
3234   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3235     {
3236       /* Propagate type and const-expression information.  */
3237       TREE_TYPE (result) = TREE_TYPE (arg);
3238       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3239     }
3240   else
3241     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3242        they will rarely be compared to anything.  */
3243     SET_TYPE_STRUCTURAL_EQUALITY (result);
3244
3245   /* Determine which parameter packs will be expanded.  */
3246   ppd.parameter_packs = &parameter_packs;
3247   ppd.visited = pointer_set_create ();
3248   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3249   pointer_set_destroy (ppd.visited);
3250
3251   /* Make sure we found some parameter packs.  */
3252   if (parameter_packs == NULL_TREE)
3253     {
3254       if (TYPE_P (arg))
3255         error ("expansion pattern %<%T%> contains no argument packs", arg);
3256       else
3257         error ("expansion pattern %<%E%> contains no argument packs", arg);
3258       return error_mark_node;
3259     }
3260   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3261
3262   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3263
3264   return result;
3265 }
3266
3267 /* Checks T for any "bare" parameter packs, which have not yet been
3268    expanded, and issues an error if any are found. This operation can
3269    only be done on full expressions or types (e.g., an expression
3270    statement, "if" condition, etc.), because we could have expressions like:
3271
3272      foo(f(g(h(args)))...)
3273
3274    where "args" is a parameter pack. check_for_bare_parameter_packs
3275    should not be called for the subexpressions args, h(args),
3276    g(h(args)), or f(g(h(args))), because we would produce erroneous
3277    error messages. 
3278
3279    Returns TRUE and emits an error if there were bare parameter packs,
3280    returns FALSE otherwise.  */
3281 bool 
3282 check_for_bare_parameter_packs (tree t)
3283 {
3284   tree parameter_packs = NULL_TREE;
3285   struct find_parameter_pack_data ppd;
3286
3287   if (!processing_template_decl || !t || t == error_mark_node)
3288     return false;
3289
3290   if (TREE_CODE (t) == TYPE_DECL)
3291     t = TREE_TYPE (t);
3292
3293   ppd.parameter_packs = &parameter_packs;
3294   ppd.visited = pointer_set_create ();
3295   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3296   pointer_set_destroy (ppd.visited);
3297
3298   if (parameter_packs) 
3299     {
3300       error ("parameter packs not expanded with %<...%>:");
3301       while (parameter_packs)
3302         {
3303           tree pack = TREE_VALUE (parameter_packs);
3304           tree name = NULL_TREE;
3305
3306           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3307               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3308             name = TYPE_NAME (pack);
3309           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3310             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3311           else
3312             name = DECL_NAME (pack);
3313
3314           if (name)
3315             inform (input_location, "        %qD", name);
3316           else
3317             inform (input_location, "        <anonymous>");
3318
3319           parameter_packs = TREE_CHAIN (parameter_packs);
3320         }
3321
3322       return true;
3323     }
3324
3325   return false;
3326 }
3327
3328 /* Expand any parameter packs that occur in the template arguments in
3329    ARGS.  */
3330 tree
3331 expand_template_argument_pack (tree args)
3332 {
3333   tree result_args = NULL_TREE;
3334   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3335   int num_result_args = -1;
3336   int non_default_args_count = -1;
3337
3338   /* First, determine if we need to expand anything, and the number of
3339      slots we'll need.  */
3340   for (in_arg = 0; in_arg < nargs; ++in_arg)
3341     {
3342       tree arg = TREE_VEC_ELT (args, in_arg);
3343       if (arg == NULL_TREE)
3344         return args;
3345       if (ARGUMENT_PACK_P (arg))
3346         {
3347           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3348           if (num_result_args < 0)
3349             num_result_args = in_arg + num_packed;
3350           else
3351             num_result_args += num_packed;
3352         }
3353       else
3354         {
3355           if (num_result_args >= 0)
3356             num_result_args++;
3357         }
3358     }
3359
3360   /* If no expansion is necessary, we're done.  */
3361   if (num_result_args < 0)
3362     return args;
3363
3364   /* Expand arguments.  */
3365   result_args = make_tree_vec (num_result_args);
3366   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3367     non_default_args_count =
3368       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3369   for (in_arg = 0; in_arg < nargs; ++in_arg)
3370     {
3371       tree arg = TREE_VEC_ELT (args, in_arg);
3372       if (ARGUMENT_PACK_P (arg))
3373         {
3374           tree packed = ARGUMENT_PACK_ARGS (arg);
3375           int i, num_packed = TREE_VEC_LENGTH (packed);
3376           for (i = 0; i < num_packed; ++i, ++out_arg)
3377             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3378           if (non_default_args_count > 0)
3379             non_default_args_count += num_packed;
3380         }
3381       else
3382         {
3383           TREE_VEC_ELT (result_args, out_arg) = arg;
3384           ++out_arg;
3385         }
3386     }
3387   if (non_default_args_count >= 0)
3388     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3389   return result_args;
3390 }
3391
3392 /* Checks if DECL shadows a template parameter.
3393
3394    [temp.local]: A template-parameter shall not be redeclared within its
3395    scope (including nested scopes).
3396
3397    Emits an error and returns TRUE if the DECL shadows a parameter,
3398    returns FALSE otherwise.  */
3399
3400 bool
3401 check_template_shadow (tree decl)
3402 {
3403   tree olddecl;
3404
3405   /* If we're not in a template, we can't possibly shadow a template
3406      parameter.  */
3407   if (!current_template_parms)
3408     return true;
3409
3410   /* Figure out what we're shadowing.  */
3411   if (TREE_CODE (decl) == OVERLOAD)
3412     decl = OVL_CURRENT (decl);
3413   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3414
3415   /* If there's no previous binding for this name, we're not shadowing
3416      anything, let alone a template parameter.  */
3417   if (!olddecl)
3418     return true;
3419
3420   /* If we're not shadowing a template parameter, we're done.  Note
3421      that OLDDECL might be an OVERLOAD (or perhaps even an
3422      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3423      node.  */
3424   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3425     return true;
3426
3427   /* We check for decl != olddecl to avoid bogus errors for using a
3428      name inside a class.  We check TPFI to avoid duplicate errors for
3429      inline member templates.  */
3430   if (decl == olddecl
3431       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3432     return true;
3433
3434   error ("declaration of %q+#D", decl);
3435   error (" shadows template parm %q+#D", olddecl);
3436   return false;
3437 }
3438
3439 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3440    ORIG_LEVEL, DECL, and TYPE.  */
3441
3442 static tree
3443 build_template_parm_index (int index,
3444                            int level,
3445                            int orig_level,
3446                            tree decl,
3447                            tree type)
3448 {
3449   tree t = make_node (TEMPLATE_PARM_INDEX);
3450   TEMPLATE_PARM_IDX (t) = index;
3451   TEMPLATE_PARM_LEVEL (t) = level;
3452   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3453   TEMPLATE_PARM_DECL (t) = decl;
3454   TREE_TYPE (t) = type;
3455   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3456   TREE_READONLY (t) = TREE_READONLY (decl);
3457
3458   return t;
3459 }
3460
3461 /* Find the canonical type parameter for the given template type
3462    parameter.  Returns the canonical type parameter, which may be TYPE
3463    if no such parameter existed.  */
3464
3465 static tree
3466 canonical_type_parameter (tree type)
3467 {
3468   tree list;
3469   int idx = TEMPLATE_TYPE_IDX (type);
3470   if (!canonical_template_parms)
3471     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3472
3473   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3474     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3475
3476   list = VEC_index (tree, canonical_template_parms, idx);
3477   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3478     list = TREE_CHAIN (list);
3479
3480   if (list)
3481     return TREE_VALUE (list);
3482   else
3483     {
3484       VEC_replace(tree, canonical_template_parms, idx,
3485                   tree_cons (NULL_TREE, type, 
3486                              VEC_index (tree, canonical_template_parms, idx)));
3487       return type;
3488     }
3489 }
3490
3491 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3492    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3493    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3494    new one is created.  */
3495
3496 static tree
3497 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3498                             tsubst_flags_t complain)
3499 {
3500   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3501       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3502           != TEMPLATE_PARM_LEVEL (index) - levels)
3503       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3504     {
3505       tree orig_decl = TEMPLATE_PARM_DECL (index);
3506       tree decl, t;
3507
3508       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3509                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3510       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3511       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3512       DECL_ARTIFICIAL (decl) = 1;
3513       SET_DECL_TEMPLATE_PARM_P (decl);
3514
3515       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3516                                      TEMPLATE_PARM_LEVEL (index) - levels,
3517                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3518                                      decl, type);
3519       TEMPLATE_PARM_DESCENDANTS (index) = t;
3520       TEMPLATE_PARM_PARAMETER_PACK (t) 
3521         = TEMPLATE_PARM_PARAMETER_PACK (index);
3522
3523         /* Template template parameters need this.  */
3524       if (TREE_CODE (decl) == TEMPLATE_DECL)
3525         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3526           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3527            args, complain);
3528     }
3529
3530   return TEMPLATE_PARM_DESCENDANTS (index);
3531 }
3532
3533 /* Process information from new template parameter PARM and append it
3534    to the LIST being built.  This new parameter is a non-type
3535    parameter iff IS_NON_TYPE is true. This new parameter is a
3536    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3537    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3538    parameter list PARM belongs to. This is used used to create a
3539    proper canonical type for the type of PARM that is to be created,
3540    iff PARM is a type.  If the size is not known, this parameter shall
3541    be set to 0.  */
3542
3543 tree
3544 process_template_parm (tree list, location_t parm_loc, tree parm,
3545                        bool is_non_type, bool is_parameter_pack)
3546 {
3547   tree decl = 0;
3548   tree defval;
3549   tree err_parm_list;
3550   int idx = 0;
3551
3552   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3553   defval = TREE_PURPOSE (parm);
3554
3555   if (list)
3556     {
3557       tree p = tree_last (list);
3558
3559       if (p && TREE_VALUE (p) != error_mark_node)
3560         {
3561           p = TREE_VALUE (p);
3562           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3563             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3564           else
3565             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3566         }
3567
3568       ++idx;
3569     }
3570   else
3571     idx = 0;
3572
3573   if (is_non_type)
3574     {
3575       parm = TREE_VALUE (parm);
3576
3577       SET_DECL_TEMPLATE_PARM_P (parm);
3578
3579       if (TREE_TYPE (parm) == error_mark_node)
3580         {
3581           err_parm_list = build_tree_list (defval, parm);
3582           TREE_VALUE (err_parm_list) = error_mark_node;
3583            return chainon (list, err_parm_list);
3584         }
3585       else
3586       {
3587         /* [temp.param]
3588
3589            The top-level cv-qualifiers on the template-parameter are
3590            ignored when determining its type.  */
3591         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3592         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3593           {
3594             err_parm_list = build_tree_list (defval, parm);
3595             TREE_VALUE (err_parm_list) = error_mark_node;
3596              return chainon (list, err_parm_list);
3597           }
3598
3599         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3600           {
3601             /* This template parameter is not a parameter pack, but it
3602                should be. Complain about "bare" parameter packs.  */
3603             check_for_bare_parameter_packs (TREE_TYPE (parm));
3604             
3605             /* Recover by calling this a parameter pack.  */
3606             is_parameter_pack = true;
3607           }
3608       }
3609
3610       /* A template parameter is not modifiable.  */
3611       TREE_CONSTANT (parm) = 1;
3612       TREE_READONLY (parm) = 1;
3613       decl = build_decl (parm_loc,
3614                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3615       TREE_CONSTANT (decl) = 1;
3616       TREE_READONLY (decl) = 1;
3617       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3618         = build_template_parm_index (idx, processing_template_decl,
3619                                      processing_template_decl,
3620                                      decl, TREE_TYPE (parm));
3621
3622       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3623         = is_parameter_pack;
3624     }
3625   else
3626     {
3627       tree t;
3628       parm = TREE_VALUE (TREE_VALUE (parm));
3629
3630       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3631         {
3632           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3633           /* This is for distinguishing between real templates and template
3634              template parameters */
3635           TREE_TYPE (parm) = t;
3636           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3637           decl = parm;
3638         }
3639       else
3640         {
3641           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3642           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3643           decl = build_decl (parm_loc,
3644                              TYPE_DECL, parm, t);
3645         }
3646
3647       TYPE_NAME (t) = decl;
3648       TYPE_STUB_DECL (t) = decl;
3649       parm = decl;
3650       TEMPLATE_TYPE_PARM_INDEX (t)
3651         = build_template_parm_index (idx, processing_template_decl,
3652                                      processing_template_decl,
3653                                      decl, TREE_TYPE (parm));
3654       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3655       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3656     }
3657   DECL_ARTIFICIAL (decl) = 1;
3658   SET_DECL_TEMPLATE_PARM_P (decl);
3659   pushdecl (decl);
3660   parm = build_tree_list (defval, parm);
3661   return chainon (list, parm);
3662 }
3663
3664 /* The end of a template parameter list has been reached.  Process the
3665    tree list into a parameter vector, converting each parameter into a more
3666    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3667    as PARM_DECLs.  */
3668
3669 tree
3670 end_template_parm_list (tree parms)
3671 {
3672   int nparms;
3673   tree parm, next;
3674   tree saved_parmlist = make_tree_vec (list_length (parms));
3675
3676   current_template_parms
3677     = tree_cons (size_int (processing_template_decl),
3678                  saved_parmlist, current_template_parms);
3679
3680   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3681     {
3682       next = TREE_CHAIN (parm);
3683       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3684       TREE_CHAIN (parm) = NULL_TREE;
3685     }
3686
3687   --processing_template_parmlist;
3688
3689   return saved_parmlist;
3690 }
3691
3692 /* end_template_decl is called after a template declaration is seen.  */
3693
3694 void
3695 end_template_decl (void)
3696 {
3697   reset_specialization ();
3698
3699   if (! processing_template_decl)
3700     return;
3701
3702   /* This matches the pushlevel in begin_template_parm_list.  */
3703   finish_scope ();
3704
3705   --processing_template_decl;
3706   current_template_parms = TREE_CHAIN (current_template_parms);
3707 }
3708
3709 /* Takes a TREE_LIST representing a template parameter and convert it
3710    into an argument suitable to be passed to the type substitution
3711    functions.  Note that If the TREE_LIST contains an error_mark
3712    node, the returned argument is error_mark_node.  */
3713
3714 static tree
3715 template_parm_to_arg (tree t)
3716 {
3717
3718   if (t == NULL_TREE
3719       || TREE_CODE (t) != TREE_LIST)
3720     return t;
3721
3722   if (error_operand_p (TREE_VALUE (t)))
3723     return error_mark_node;
3724
3725   t = TREE_VALUE (t);
3726
3727   if (TREE_CODE (t) == TYPE_DECL
3728       || TREE_CODE (t) == TEMPLATE_DECL)
3729     {
3730       t = TREE_TYPE (t);
3731
3732       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3733         {
3734           /* Turn this argument into a TYPE_ARGUMENT_PACK
3735              with a single element, which expands T.  */
3736           tree vec = make_tree_vec (1);
3737 #ifdef ENABLE_CHECKING
3738           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3739             (vec, TREE_VEC_LENGTH (vec));
3740 #endif
3741           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3742
3743           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3744           SET_ARGUMENT_PACK_ARGS (t, vec);
3745         }
3746     }
3747   else
3748     {
3749       t = DECL_INITIAL (t);
3750
3751       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3752         {
3753           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3754              with a single element, which expands T.  */
3755           tree vec = make_tree_vec (1);
3756           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3757 #ifdef ENABLE_CHECKING
3758           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3759             (vec, TREE_VEC_LENGTH (vec));
3760 #endif
3761           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3762
3763           t  = make_node (NONTYPE_ARGUMENT_PACK);
3764           SET_ARGUMENT_PACK_ARGS (t, vec);
3765           TREE_TYPE (t) = type;
3766         }
3767     }
3768   return t;
3769 }
3770
3771 /* This function returns TRUE if PARM_PACK is a template parameter
3772    pack and if ARG_PACK is what template_parm_to_arg returned when
3773    passed PARM_PACK.  */
3774
3775 static bool
3776 arg_from_parm_pack_p (tree arg_pack, tree parm_pack)
3777 {
3778   /* For clarity in the comments below let's use the representation
3779      argument_pack<elements>' to denote an argument pack and its
3780      elements.
3781
3782      In the 'if' block below, we want to detect cases where
3783      ARG_PACK is argument_pack<PARM_PACK...>.  I.e, we want to
3784      check if ARG_PACK is an argument pack which sole element is
3785      the expansion of PARM_PACK.  That argument pack is typically
3786      created by template_parm_to_arg when passed a parameter
3787      pack.  */
3788
3789   if (arg_pack
3790       && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
3791       && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
3792     {
3793       tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
3794       tree pattern = PACK_EXPANSION_PATTERN (expansion);
3795       if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
3796           || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
3797         /* The argument pack that the parameter maps to is just an
3798            expansion of the parameter itself, such as one would
3799            find in the implicit typedef of a class inside the
3800            class itself.  Consider this parameter "unsubstituted",
3801            so that we will maintain the outer pack expansion.  */
3802         return true;
3803     }
3804   return false;
3805 }
3806
3807 /* Within the declaration of a template, return all levels of template
3808    parameters that apply.  The template parameters are represented as
3809    a TREE_VEC, in the form documented in cp-tree.h for template
3810    arguments.  */
3811
3812 static tree
3813 current_template_args (void)
3814 {
3815   tree header;
3816   tree args = NULL_TREE;
3817   int length = TMPL_PARMS_DEPTH (current_template_parms);
3818   int l = length;
3819
3820   /* If there is only one level of template parameters, we do not
3821      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3822      TREE_VEC containing the arguments.  */
3823   if (length > 1)
3824     args = make_tree_vec (length);
3825
3826   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3827     {
3828       tree a = copy_node (TREE_VALUE (header));
3829       int i;
3830
3831       TREE_TYPE (a) = NULL_TREE;
3832       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3833         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
3834
3835 #ifdef ENABLE_CHECKING
3836       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3837 #endif
3838
3839       if (length > 1)
3840         TREE_VEC_ELT (args, --l) = a;
3841       else
3842         args = a;
3843     }
3844
3845     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
3846       /* This can happen for template parms of a template template
3847          parameter, e.g:
3848
3849          template<template<class T, class U> class TT> struct S;
3850
3851          Consider the level of the parms of TT; T and U both have
3852          level 2; TT has no template parm of level 1. So in this case
3853          the first element of full_template_args is NULL_TREE. If we
3854          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
3855          of 2. This will make tsubst wrongly consider that T and U
3856          have level 1. Instead, let's create a dummy vector as the
3857          first element of full_template_args so that TMPL_ARG_DEPTH
3858          returns the correct depth for args.  */
3859       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
3860   return args;
3861 }
3862
3863 /* Update the declared TYPE by doing any lookups which were thought to be
3864    dependent, but are not now that we know the SCOPE of the declarator.  */
3865
3866 tree
3867 maybe_update_decl_type (tree orig_type, tree scope)
3868 {
3869   tree type = orig_type;
3870
3871   if (type == NULL_TREE)
3872     return type;
3873
3874   if (TREE_CODE (orig_type) == TYPE_DECL)
3875     type = TREE_TYPE (type);
3876
3877   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3878       && dependent_type_p (type)
3879       /* Don't bother building up the args in this case.  */
3880       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3881     {
3882       /* tsubst in the args corresponding to the template parameters,
3883          including auto if present.  Most things will be unchanged, but
3884          make_typename_type and tsubst_qualified_id will resolve
3885          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3886       tree args = current_template_args ();
3887       tree auto_node = type_uses_auto (type);
3888       tree pushed;
3889       if (auto_node)
3890         {
3891           tree auto_vec = make_tree_vec (1);
3892           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3893           args = add_to_template_args (args, auto_vec);
3894         }
3895       pushed = push_scope (scope);
3896       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3897       if (pushed)
3898         pop_scope (scope);
3899     }
3900
3901   if (type == error_mark_node)
3902     return orig_type;
3903
3904   if (TREE_CODE (orig_type) == TYPE_DECL)
3905     {
3906       if (same_type_p (type, TREE_TYPE (orig_type)))
3907         type = orig_type;
3908       else
3909         type = TYPE_NAME (type);
3910     }
3911   return type;
3912 }
3913
3914 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3915    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3916    a member template.  Used by push_template_decl below.  */
3917
3918 static tree
3919 build_template_decl (tree decl, tree parms, bool member_template_p)
3920 {
3921   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3922   DECL_TEMPLATE_PARMS (tmpl) = parms;
3923   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3924   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3925   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3926
3927   return tmpl;
3928 }
3929
3930 struct template_parm_data
3931 {
3932   /* The level of the template parameters we are currently
3933      processing.  */
3934   int level;
3935
3936   /* The index of the specialization argument we are currently
3937      processing.  */
3938   int current_arg;
3939
3940   /* An array whose size is the number of template parameters.  The
3941      elements are nonzero if the parameter has been used in any one
3942      of the arguments processed so far.  */
3943   int* parms;
3944
3945   /* An array whose size is the number of template arguments.  The
3946      elements are nonzero if the argument makes use of template
3947      parameters of this level.  */
3948   int* arg_uses_template_parms;
3949 };
3950
3951 /* Subroutine of push_template_decl used to see if each template
3952    parameter in a partial specialization is used in the explicit
3953    argument list.  If T is of the LEVEL given in DATA (which is
3954    treated as a template_parm_data*), then DATA->PARMS is marked
3955    appropriately.  */
3956
3957 static int
3958 mark_template_parm (tree t, void* data)
3959 {
3960   int level;
3961   int idx;
3962   struct template_parm_data* tpd = (struct template_parm_data*) data;
3963
3964   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3965     {
3966       level = TEMPLATE_PARM_LEVEL (t);
3967       idx = TEMPLATE_PARM_IDX (t);
3968     }
3969   else
3970     {
3971       level = TEMPLATE_TYPE_LEVEL (t);
3972       idx = TEMPLATE_TYPE_IDX (t);
3973     }
3974
3975   if (level == tpd->level)
3976     {
3977       tpd->parms[idx] = 1;
3978       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3979     }
3980
3981   /* Return zero so that for_each_template_parm will continue the
3982      traversal of the tree; we want to mark *every* template parm.  */
3983   return 0;
3984 }
3985
3986 /* Process the partial specialization DECL.  */
3987
3988 static tree
3989 process_partial_specialization (tree decl)
3990 {
3991   tree type = TREE_TYPE (decl);
3992   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3993   tree specargs = CLASSTYPE_TI_ARGS (type);
3994   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3995   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3996   tree inner_parms;
3997   tree inst;
3998   int nargs = TREE_VEC_LENGTH (inner_args);
3999   int ntparms;
4000   int  i;
4001   bool did_error_intro = false;
4002   struct template_parm_data tpd;
4003   struct template_parm_data tpd2;
4004
4005   gcc_assert (current_template_parms);
4006
4007   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4008   ntparms = TREE_VEC_LENGTH (inner_parms);
4009
4010   /* We check that each of the template parameters given in the
4011      partial specialization is used in the argument list to the
4012      specialization.  For example:
4013
4014        template <class T> struct S;
4015        template <class T> struct S<T*>;
4016
4017      The second declaration is OK because `T*' uses the template
4018      parameter T, whereas
4019
4020        template <class T> struct S<int>;
4021
4022      is no good.  Even trickier is:
4023
4024        template <class T>
4025        struct S1
4026        {
4027           template <class U>
4028           struct S2;
4029           template <class U>
4030           struct S2<T>;
4031        };
4032
4033      The S2<T> declaration is actually invalid; it is a
4034      full-specialization.  Of course,
4035
4036           template <class U>
4037           struct S2<T (*)(U)>;
4038
4039      or some such would have been OK.  */
4040   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4041   tpd.parms = XALLOCAVEC (int, ntparms);
4042   memset (tpd.parms, 0, sizeof (int) * ntparms);
4043
4044   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4045   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4046   for (i = 0; i < nargs; ++i)
4047     {
4048       tpd.current_arg = i;
4049       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4050                               &mark_template_parm,
4051                               &tpd,
4052                               NULL,
4053                               /*include_nondeduced_p=*/false);
4054     }
4055   for (i = 0; i < ntparms; ++i)
4056     if (tpd.parms[i] == 0)
4057       {
4058         /* One of the template parms was not used in the
4059            specialization.  */
4060         if (!did_error_intro)
4061           {
4062             error ("template parameters not used in partial specialization:");
4063             did_error_intro = true;
4064           }
4065
4066         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4067       }
4068
4069   if (did_error_intro)
4070     return error_mark_node;
4071
4072   /* [temp.class.spec]
4073
4074      The argument list of the specialization shall not be identical to
4075      the implicit argument list of the primary template.  */
4076   if (comp_template_args
4077       (inner_args,
4078        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4079                                                    (maintmpl)))))
4080     error ("partial specialization %qT does not specialize any template arguments", type);
4081
4082   /* [temp.class.spec]
4083
4084      A partially specialized non-type argument expression shall not
4085      involve template parameters of the partial specialization except
4086      when the argument expression is a simple identifier.
4087
4088      The type of a template parameter corresponding to a specialized
4089      non-type argument shall not be dependent on a parameter of the
4090      specialization. 
4091
4092      Also, we verify that pack expansions only occur at the
4093      end of the argument list.  */
4094   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4095   tpd2.parms = 0;
4096   for (i = 0; i < nargs; ++i)
4097     {
4098       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4099       tree arg = TREE_VEC_ELT (inner_args, i);
4100       tree packed_args = NULL_TREE;
4101       int j, len = 1;
4102
4103       if (ARGUMENT_PACK_P (arg))
4104         {
4105           /* Extract the arguments from the argument pack. We'll be
4106              iterating over these in the following loop.  */
4107           packed_args = ARGUMENT_PACK_ARGS (arg);
4108           len = TREE_VEC_LENGTH (packed_args);
4109         }
4110
4111       for (j = 0; j < len; j++)
4112         {
4113           if (packed_args)
4114             /* Get the Jth argument in the parameter pack.  */
4115             arg = TREE_VEC_ELT (packed_args, j);
4116
4117           if (PACK_EXPANSION_P (arg))
4118             {
4119               /* Pack expansions must come at the end of the
4120                  argument list.  */
4121               if ((packed_args && j < len - 1)
4122                   || (!packed_args && i < nargs - 1))
4123                 {
4124                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4125                     error ("parameter pack argument %qE must be at the "
4126                            "end of the template argument list", arg);
4127                   else
4128                     error ("parameter pack argument %qT must be at the "
4129                            "end of the template argument list", arg);
4130                 }
4131             }
4132
4133           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4134             /* We only care about the pattern.  */
4135             arg = PACK_EXPANSION_PATTERN (arg);
4136
4137           if (/* These first two lines are the `non-type' bit.  */
4138               !TYPE_P (arg)
4139               && TREE_CODE (arg) != TEMPLATE_DECL
4140               /* This next line is the `argument expression is not just a
4141                  simple identifier' condition and also the `specialized
4142                  non-type argument' bit.  */
4143               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4144             {
4145               if ((!packed_args && tpd.arg_uses_template_parms[i])
4146                   || (packed_args && uses_template_parms (arg)))
4147                 error ("template argument %qE involves template parameter(s)",
4148                        arg);
4149               else 
4150                 {
4151                   /* Look at the corresponding template parameter,
4152                      marking which template parameters its type depends
4153                      upon.  */
4154                   tree type = TREE_TYPE (parm);
4155
4156                   if (!tpd2.parms)
4157                     {
4158                       /* We haven't yet initialized TPD2.  Do so now.  */
4159                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4160                       /* The number of parameters here is the number in the
4161                          main template, which, as checked in the assertion
4162                          above, is NARGS.  */
4163                       tpd2.parms = XALLOCAVEC (int, nargs);
4164                       tpd2.level = 
4165                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4166                     }
4167
4168                   /* Mark the template parameters.  But this time, we're
4169                      looking for the template parameters of the main
4170                      template, not in the specialization.  */
4171                   tpd2.current_arg = i;
4172                   tpd2.arg_uses_template_parms[i] = 0;
4173                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4174                   for_each_template_parm (type,
4175                                           &mark_template_parm,
4176                                           &tpd2,
4177                                           NULL,
4178                                           /*include_nondeduced_p=*/false);
4179
4180                   if (tpd2.arg_uses_template_parms [i])
4181                     {
4182                       /* The type depended on some template parameters.
4183                          If they are fully specialized in the
4184                          specialization, that's OK.  */
4185                       int j;
4186                       int count = 0;
4187                       for (j = 0; j < nargs; ++j)
4188                         if (tpd2.parms[j] != 0
4189                             && tpd.arg_uses_template_parms [j])
4190                           ++count;
4191                       if (count != 0)
4192                         error_n (input_location, count,
4193                                  "type %qT of template argument %qE depends "
4194                                  "on a template parameter",
4195                                  "type %qT of template argument %qE depends "
4196                                  "on template parameters",
4197                                  type,
4198                                  arg);
4199                     }
4200                 }
4201             }
4202         }
4203     }
4204
4205   /* We should only get here once.  */
4206   gcc_assert (!COMPLETE_TYPE_P (type));
4207
4208   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4209     = tree_cons (specargs, inner_parms,
4210                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4211   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4212
4213   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4214        inst = TREE_CHAIN (inst))
4215     {
4216       tree inst_type = TREE_VALUE (inst);
4217       if (COMPLETE_TYPE_P (inst_type)
4218           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4219         {
4220           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4221           if (spec && TREE_TYPE (spec) == type)
4222             permerror (input_location,
4223                        "partial specialization of %qT after instantiation "
4224                        "of %qT", type, inst_type);
4225         }
4226     }
4227
4228   return decl;
4229 }
4230
4231 /* Check that a template declaration's use of default arguments and
4232    parameter packs is not invalid.  Here, PARMS are the template
4233    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4234    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4235    specialization.
4236    
4237
4238    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4239    declaration (but not a definition); 1 indicates a declaration, 2
4240    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4241    emitted for extraneous default arguments.
4242
4243    Returns TRUE if there were no errors found, FALSE otherwise. */
4244
4245 bool
4246 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4247                          int is_partial, int is_friend_decl)
4248 {
4249   const char *msg;
4250   int last_level_to_check;
4251   tree parm_level;
4252   bool no_errors = true;
4253
4254   /* [temp.param]
4255
4256      A default template-argument shall not be specified in a
4257      function template declaration or a function template definition, nor
4258      in the template-parameter-list of the definition of a member of a
4259      class template.  */
4260
4261   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4262     /* You can't have a function template declaration in a local
4263        scope, nor you can you define a member of a class template in a
4264        local scope.  */
4265     return true;
4266
4267   if (current_class_type
4268       && !TYPE_BEING_DEFINED (current_class_type)
4269       && DECL_LANG_SPECIFIC (decl)
4270       && DECL_DECLARES_FUNCTION_P (decl)
4271       /* If this is either a friend defined in the scope of the class
4272          or a member function.  */
4273       && (DECL_FUNCTION_MEMBER_P (decl)
4274           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4275           : DECL_FRIEND_CONTEXT (decl)
4276           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4277           : false)
4278       /* And, if it was a member function, it really was defined in
4279          the scope of the class.  */
4280       && (!DECL_FUNCTION_MEMBER_P (decl)
4281           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4282     /* We already checked these parameters when the template was
4283        declared, so there's no need to do it again now.  This function
4284        was defined in class scope, but we're processing it's body now
4285        that the class is complete.  */
4286     return true;
4287
4288   /* Core issue 226 (C++0x only): the following only applies to class
4289      templates.  */
4290   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4291     {
4292       /* [temp.param]
4293
4294          If a template-parameter has a default template-argument, all
4295          subsequent template-parameters shall have a default
4296          template-argument supplied.  */
4297       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4298         {
4299           tree inner_parms = TREE_VALUE (parm_level);
4300           int ntparms = TREE_VEC_LENGTH (inner_parms);
4301           int seen_def_arg_p = 0;
4302           int i;
4303
4304           for (i = 0; i < ntparms; ++i)
4305             {
4306               tree parm = TREE_VEC_ELT (inner_parms, i);
4307
4308               if (parm == error_mark_node)
4309                 continue;
4310
4311               if (TREE_PURPOSE (parm))
4312                 seen_def_arg_p = 1;
4313               else if (seen_def_arg_p
4314                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4315                 {
4316                   error ("no default argument for %qD", TREE_VALUE (parm));
4317                   /* For better subsequent error-recovery, we indicate that
4318                      there should have been a default argument.  */
4319                   TREE_PURPOSE (parm) = error_mark_node;
4320                   no_errors = false;
4321                 }
4322               else if (is_primary
4323                        && !is_partial
4324                        && !is_friend_decl
4325                        /* Don't complain about an enclosing partial
4326                           specialization.  */
4327                        && parm_level == parms
4328                        && TREE_CODE (decl) == TYPE_DECL
4329                        && i < ntparms - 1
4330                        && template_parameter_pack_p (TREE_VALUE (parm)))
4331                 {
4332                   /* A primary class template can only have one
4333                      parameter pack, at the end of the template
4334                      parameter list.  */
4335
4336                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4337                     error ("parameter pack %qE must be at the end of the"
4338                            " template parameter list", TREE_VALUE (parm));
4339                   else
4340                     error ("parameter pack %qT must be at the end of the"
4341                            " template parameter list", 
4342                            TREE_TYPE (TREE_VALUE (parm)));
4343
4344                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4345                     = error_mark_node;
4346                   no_errors = false;
4347                 }
4348             }
4349         }
4350     }
4351
4352   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4353       || is_partial 
4354       || !is_primary
4355       || is_friend_decl)
4356     /* For an ordinary class template, default template arguments are
4357        allowed at the innermost level, e.g.:
4358          template <class T = int>
4359          struct S {};
4360        but, in a partial specialization, they're not allowed even
4361        there, as we have in [temp.class.spec]:
4362
4363          The template parameter list of a specialization shall not
4364          contain default template argument values.
4365
4366        So, for a partial specialization, or for a function template
4367        (in C++98/C++03), we look at all of them.  */
4368     ;
4369   else
4370     /* But, for a primary class template that is not a partial
4371        specialization we look at all template parameters except the
4372        innermost ones.  */
4373     parms = TREE_CHAIN (parms);
4374
4375   /* Figure out what error message to issue.  */
4376   if (is_friend_decl == 2)
4377     msg = G_("default template arguments may not be used in function template "
4378              "friend re-declaration");
4379   else if (is_friend_decl)
4380     msg = G_("default template arguments may not be used in function template "
4381              "friend declarations");
4382   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4383     msg = G_("default template arguments may not be used in function templates "
4384              "without -std=c++11 or -std=gnu++11");
4385   else if (is_partial)
4386     msg = G_("default template arguments may not be used in "
4387              "partial specializations");
4388   else
4389     msg = G_("default argument for template parameter for class enclosing %qD");
4390
4391   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4392     /* If we're inside a class definition, there's no need to
4393        examine the parameters to the class itself.  On the one
4394        hand, they will be checked when the class is defined, and,
4395        on the other, default arguments are valid in things like:
4396          template <class T = double>
4397          struct S { template <class U> void f(U); };
4398        Here the default argument for `S' has no bearing on the
4399        declaration of `f'.  */
4400     last_level_to_check = template_class_depth (current_class_type) + 1;
4401   else
4402     /* Check everything.  */
4403     last_level_to_check = 0;
4404
4405   for (parm_level = parms;
4406        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4407        parm_level = TREE_CHAIN (parm_level))
4408     {
4409       tree inner_parms = TREE_VALUE (parm_level);
4410       int i;
4411       int ntparms;
4412
4413       ntparms = TREE_VEC_LENGTH (inner_parms);
4414       for (i = 0; i < ntparms; ++i)
4415         {
4416           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4417             continue;
4418
4419           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4420             {
4421               if (msg)
4422                 {
4423                   no_errors = false;
4424                   if (is_friend_decl == 2)
4425                     return no_errors;
4426
4427                   error (msg, decl);
4428                   msg = 0;
4429                 }
4430
4431               /* Clear out the default argument so that we are not
4432                  confused later.  */
4433               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4434             }
4435         }
4436
4437       /* At this point, if we're still interested in issuing messages,
4438          they must apply to classes surrounding the object declared.  */
4439       if (msg)
4440         msg = G_("default argument for template parameter for class "
4441                  "enclosing %qD");
4442     }
4443
4444   return no_errors;
4445 }
4446
4447 /* Worker for push_template_decl_real, called via
4448    for_each_template_parm.  DATA is really an int, indicating the
4449    level of the parameters we are interested in.  If T is a template
4450    parameter of that level, return nonzero.  */
4451
4452 static int
4453 template_parm_this_level_p (tree t, void* data)
4454 {
4455   int this_level = *(int *)data;
4456   int level;
4457
4458   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4459     level = TEMPLATE_PARM_LEVEL (t);
4460   else
4461     level = TEMPLATE_TYPE_LEVEL (t);
4462   return level == this_level;
4463 }
4464
4465 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4466    parameters given by current_template_args, or reuses a
4467    previously existing one, if appropriate.  Returns the DECL, or an
4468    equivalent one, if it is replaced via a call to duplicate_decls.
4469
4470    If IS_FRIEND is true, DECL is a friend declaration.  */
4471
4472 tree
4473 push_template_decl_real (tree decl, bool is_friend)
4474 {
4475   tree tmpl;
4476   tree args;
4477   tree info;
4478   tree ctx;
4479   int primary;
4480   int is_partial;
4481   int new_template_p = 0;
4482   /* True if the template is a member template, in the sense of
4483      [temp.mem].  */
4484   bool member_template_p = false;
4485
4486   if (decl == error_mark_node || !current_template_parms)
4487     return error_mark_node;
4488
4489   /* See if this is a partial specialization.  */
4490   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4491                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4492                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4493
4494   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4495     is_friend = true;
4496
4497   if (is_friend)
4498     /* For a friend, we want the context of the friend function, not
4499        the type of which it is a friend.  */
4500     ctx = CP_DECL_CONTEXT (decl);
4501   else if (CP_DECL_CONTEXT (decl)
4502            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4503     /* In the case of a virtual function, we want the class in which
4504        it is defined.  */
4505     ctx = CP_DECL_CONTEXT (decl);
4506   else
4507     /* Otherwise, if we're currently defining some class, the DECL
4508        is assumed to be a member of the class.  */
4509     ctx = current_scope ();
4510
4511   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4512     ctx = NULL_TREE;
4513
4514   if (!DECL_CONTEXT (decl))
4515     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4516
4517   /* See if this is a primary template.  */
4518   if (is_friend && ctx)
4519     /* A friend template that specifies a class context, i.e.
4520          template <typename T> friend void A<T>::f();
4521        is not primary.  */
4522     primary = 0;
4523   else
4524     primary = template_parm_scope_p ();
4525
4526   if (primary)
4527     {
4528       if (DECL_CLASS_SCOPE_P (decl))
4529         member_template_p = true;
4530       if (TREE_CODE (decl) == TYPE_DECL
4531           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4532         {
4533           error ("template class without a name");
4534           return error_mark_node;
4535         }
4536       else if (TREE_CODE (decl) == FUNCTION_DECL)
4537         {
4538           if (DECL_DESTRUCTOR_P (decl))
4539             {
4540               /* [temp.mem]
4541
4542                  A destructor shall not be a member template.  */
4543               error ("destructor %qD declared as member template", decl);
4544               return error_mark_node;
4545             }
4546           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4547               && (!prototype_p (TREE_TYPE (decl))
4548                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4549                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4550                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4551                       == void_list_node)))
4552             {
4553               /* [basic.stc.dynamic.allocation]
4554
4555                  An allocation function can be a function
4556                  template. ... Template allocation functions shall
4557                  have two or more parameters.  */
4558               error ("invalid template declaration of %qD", decl);
4559               return error_mark_node;
4560             }
4561         }
4562       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4563                && CLASS_TYPE_P (TREE_TYPE (decl)))
4564         /* OK */;
4565       else if (TREE_CODE (decl) == TYPE_DECL
4566                && TYPE_DECL_ALIAS_P (decl))
4567         /* alias-declaration */
4568         gcc_assert (!DECL_ARTIFICIAL (decl));
4569       else
4570         {
4571           error ("template declaration of %q#D", decl);
4572           return error_mark_node;
4573         }
4574     }
4575
4576   /* Check to see that the rules regarding the use of default
4577      arguments are not being violated.  */
4578   check_default_tmpl_args (decl, current_template_parms,
4579                            primary, is_partial, /*is_friend_decl=*/0);
4580
4581   /* Ensure that there are no parameter packs in the type of this
4582      declaration that have not been expanded.  */
4583   if (TREE_CODE (decl) == FUNCTION_DECL)
4584     {
4585       /* Check each of the arguments individually to see if there are
4586          any bare parameter packs.  */
4587       tree type = TREE_TYPE (decl);
4588       tree arg = DECL_ARGUMENTS (decl);
4589       tree argtype = TYPE_ARG_TYPES (type);
4590
4591       while (arg && argtype)
4592         {
4593           if (!FUNCTION_PARAMETER_PACK_P (arg)
4594               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4595             {
4596             /* This is a PARM_DECL that contains unexpanded parameter
4597                packs. We have already complained about this in the
4598                check_for_bare_parameter_packs call, so just replace
4599                these types with ERROR_MARK_NODE.  */
4600               TREE_TYPE (arg) = error_mark_node;
4601               TREE_VALUE (argtype) = error_mark_node;
4602             }
4603
4604           arg = DECL_CHAIN (arg);
4605           argtype = TREE_CHAIN (argtype);
4606         }
4607
4608       /* Check for bare parameter packs in the return type and the
4609          exception specifiers.  */
4610       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4611         /* Errors were already issued, set return type to int
4612            as the frontend doesn't expect error_mark_node as
4613            the return type.  */
4614         TREE_TYPE (type) = integer_type_node;
4615       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4616         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4617     }
4618   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
4619                                             && TYPE_DECL_ALIAS_P (decl))
4620                                            ? DECL_ORIGINAL_TYPE (decl)
4621                                            : TREE_TYPE (decl)))
4622     {
4623       TREE_TYPE (decl) = error_mark_node;
4624       return error_mark_node;
4625     }
4626
4627   if (is_partial)
4628     return process_partial_specialization (decl);
4629
4630   args = current_template_args ();
4631
4632   if (!ctx
4633       || TREE_CODE (ctx) == FUNCTION_DECL
4634       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4635       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4636     {
4637       if (DECL_LANG_SPECIFIC (decl)
4638           && DECL_TEMPLATE_INFO (decl)
4639           && DECL_TI_TEMPLATE (decl))
4640         tmpl = DECL_TI_TEMPLATE (decl);
4641       /* If DECL is a TYPE_DECL for a class-template, then there won't
4642          be DECL_LANG_SPECIFIC.  The information equivalent to
4643          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4644       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4645                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4646                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4647         {
4648           /* Since a template declaration already existed for this
4649              class-type, we must be redeclaring it here.  Make sure
4650              that the redeclaration is valid.  */
4651           redeclare_class_template (TREE_TYPE (decl),
4652                                     current_template_parms);
4653           /* We don't need to create a new TEMPLATE_DECL; just use the
4654              one we already had.  */
4655           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4656         }
4657       else
4658         {
4659           tmpl = build_template_decl (decl, current_template_parms,
4660                                       member_template_p);
4661           new_template_p = 1;
4662
4663           if (DECL_LANG_SPECIFIC (decl)
4664               && DECL_TEMPLATE_SPECIALIZATION (decl))
4665             {
4666               /* A specialization of a member template of a template
4667                  class.  */
4668               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4669               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4670               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4671             }
4672         }
4673     }
4674   else
4675     {
4676       tree a, t, current, parms;
4677       int i;
4678       tree tinfo = get_template_info (decl);
4679
4680       if (!tinfo)
4681         {
4682           error ("template definition of non-template %q#D", decl);
4683           return error_mark_node;
4684         }
4685
4686       tmpl = TI_TEMPLATE (tinfo);
4687
4688       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4689           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4690           && DECL_TEMPLATE_SPECIALIZATION (decl)
4691           && DECL_MEMBER_TEMPLATE_P (tmpl))
4692         {
4693           tree new_tmpl;
4694
4695           /* The declaration is a specialization of a member
4696              template, declared outside the class.  Therefore, the
4697              innermost template arguments will be NULL, so we
4698              replace them with the arguments determined by the
4699              earlier call to check_explicit_specialization.  */
4700           args = DECL_TI_ARGS (decl);
4701
4702           new_tmpl
4703             = build_template_decl (decl, current_template_parms,
4704                                    member_template_p);
4705           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4706           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4707           DECL_TI_TEMPLATE (decl) = new_tmpl;
4708           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4709           DECL_TEMPLATE_INFO (new_tmpl)
4710             = build_template_info (tmpl, args);
4711
4712           register_specialization (new_tmpl,
4713                                    most_general_template (tmpl),
4714                                    args,
4715                                    is_friend, 0);
4716           return decl;
4717         }
4718
4719       /* Make sure the template headers we got make sense.  */
4720
4721       parms = DECL_TEMPLATE_PARMS (tmpl);
4722       i = TMPL_PARMS_DEPTH (parms);
4723       if (TMPL_ARGS_DEPTH (args) != i)
4724         {
4725           error ("expected %d levels of template parms for %q#D, got %d",
4726                  i, decl, TMPL_ARGS_DEPTH (args));
4727         }
4728       else
4729         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4730           {
4731             a = TMPL_ARGS_LEVEL (args, i);
4732             t = INNERMOST_TEMPLATE_PARMS (parms);
4733
4734             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4735               {
4736                 if (current == decl)
4737                   error ("got %d template parameters for %q#D",
4738                          TREE_VEC_LENGTH (a), decl);
4739                 else
4740                   error ("got %d template parameters for %q#T",
4741                          TREE_VEC_LENGTH (a), current);
4742                 error ("  but %d required", TREE_VEC_LENGTH (t));
4743                 /* Avoid crash in import_export_decl.  */
4744                 DECL_INTERFACE_KNOWN (decl) = 1;
4745                 return error_mark_node;
4746               }
4747
4748             if (current == decl)
4749               current = ctx;
4750             else if (current == NULL_TREE)
4751               /* Can happen in erroneous input.  */
4752               break;
4753             else
4754               current = (TYPE_P (current)
4755                          ? TYPE_CONTEXT (current)
4756                          : DECL_CONTEXT (current));
4757           }
4758
4759       /* Check that the parms are used in the appropriate qualifying scopes
4760          in the declarator.  */
4761       if (!comp_template_args
4762           (TI_ARGS (tinfo),
4763            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4764         {
4765           error ("\
4766 template arguments to %qD do not match original template %qD",
4767                  decl, DECL_TEMPLATE_RESULT (tmpl));
4768           if (!uses_template_parms (TI_ARGS (tinfo)))
4769             inform (input_location, "use template<> for an explicit specialization");
4770           /* Avoid crash in import_export_decl.  */
4771           DECL_INTERFACE_KNOWN (decl) = 1;
4772           return error_mark_node;
4773         }
4774     }
4775
4776   DECL_TEMPLATE_RESULT (tmpl) = decl;
4777   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4778
4779   /* Push template declarations for global functions and types.  Note
4780      that we do not try to push a global template friend declared in a
4781      template class; such a thing may well depend on the template
4782      parameters of the class.  */
4783   if (new_template_p && !ctx
4784       && !(is_friend && template_class_depth (current_class_type) > 0))
4785     {
4786       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4787       if (tmpl == error_mark_node)
4788         return error_mark_node;
4789
4790       /* Hide template friend classes that haven't been declared yet.  */
4791       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4792         {
4793           DECL_ANTICIPATED (tmpl) = 1;
4794           DECL_FRIEND_P (tmpl) = 1;
4795         }
4796     }
4797
4798   if (primary)
4799     {
4800       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4801       int i;
4802
4803       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4804       if (DECL_CONV_FN_P (tmpl))
4805         {
4806           int depth = TMPL_PARMS_DEPTH (parms);
4807
4808           /* It is a conversion operator. See if the type converted to
4809              depends on innermost template operands.  */
4810
4811           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4812                                          depth))
4813             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4814         }
4815
4816       /* Give template template parms a DECL_CONTEXT of the template
4817          for which they are a parameter.  */
4818       parms = INNERMOST_TEMPLATE_PARMS (parms);
4819       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4820         {
4821           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4822           if (TREE_CODE (parm) == TEMPLATE_DECL)
4823             DECL_CONTEXT (parm) = tmpl;
4824         }
4825     }
4826
4827   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4828      back to its most general template.  If TMPL is a specialization,
4829      ARGS may only have the innermost set of arguments.  Add the missing
4830      argument levels if necessary.  */
4831   if (DECL_TEMPLATE_INFO (tmpl))
4832     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4833
4834   info = build_template_info (tmpl, args);
4835
4836   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4837     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4838   else
4839     {
4840       if (primary && !DECL_LANG_SPECIFIC (decl))
4841         retrofit_lang_decl (decl);
4842       if (DECL_LANG_SPECIFIC (decl))
4843         DECL_TEMPLATE_INFO (decl) = info;
4844     }
4845
4846   return DECL_TEMPLATE_RESULT (tmpl);
4847 }
4848
4849 tree
4850 push_template_decl (tree decl)
4851 {
4852   return push_template_decl_real (decl, false);
4853 }
4854
4855 /* Called when a class template TYPE is redeclared with the indicated
4856    template PARMS, e.g.:
4857
4858      template <class T> struct S;
4859      template <class T> struct S {};  */
4860
4861 bool
4862 redeclare_class_template (tree type, tree parms)
4863 {
4864   tree tmpl;
4865   tree tmpl_parms;
4866   int i;
4867
4868   if (!TYPE_TEMPLATE_INFO (type))
4869     {
4870       error ("%qT is not a template type", type);
4871       return false;
4872     }
4873
4874   tmpl = TYPE_TI_TEMPLATE (type);
4875   if (!PRIMARY_TEMPLATE_P (tmpl))
4876     /* The type is nested in some template class.  Nothing to worry
4877        about here; there are no new template parameters for the nested
4878        type.  */
4879     return true;
4880
4881   if (!parms)
4882     {
4883       error ("template specifiers not specified in declaration of %qD",
4884              tmpl);
4885       return false;
4886     }
4887
4888   parms = INNERMOST_TEMPLATE_PARMS (parms);
4889   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4890
4891   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4892     {
4893       error_n (input_location, TREE_VEC_LENGTH (parms),
4894                "redeclared with %d template parameter",
4895                "redeclared with %d template parameters",
4896                TREE_VEC_LENGTH (parms));
4897       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4898                 "previous declaration %q+D used %d template parameter",
4899                 "previous declaration %q+D used %d template parameters",
4900                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4901       return false;
4902     }
4903
4904   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4905     {
4906       tree tmpl_parm;
4907       tree parm;
4908       tree tmpl_default;
4909       tree parm_default;
4910
4911       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4912           || TREE_VEC_ELT (parms, i) == error_mark_node)
4913         continue;
4914
4915       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4916       if (tmpl_parm == error_mark_node)
4917         return false;
4918
4919       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4920       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4921       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4922
4923       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4924          TEMPLATE_DECL.  */
4925       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4926           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4927               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4928           || (TREE_CODE (tmpl_parm) != PARM_DECL
4929               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4930                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4931           || (TREE_CODE (tmpl_parm) == PARM_DECL
4932               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4933                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4934         {
4935           error ("template parameter %q+#D", tmpl_parm);
4936           error ("redeclared here as %q#D", parm);
4937           return false;
4938         }
4939
4940       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4941         {
4942           /* We have in [temp.param]:
4943
4944              A template-parameter may not be given default arguments
4945              by two different declarations in the same scope.  */
4946           error_at (input_location, "redefinition of default argument for %q#D", parm);
4947           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4948                   "original definition appeared here");
4949           return false;
4950         }
4951
4952       if (parm_default != NULL_TREE)
4953         /* Update the previous template parameters (which are the ones
4954            that will really count) with the new default value.  */
4955         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4956       else if (tmpl_default != NULL_TREE)
4957         /* Update the new parameters, too; they'll be used as the
4958            parameters for any members.  */
4959         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4960     }
4961
4962     return true;
4963 }
4964
4965 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4966    (possibly simplified) expression.  */
4967
4968 static tree
4969 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
4970 {
4971   if (expr == NULL_TREE)
4972     return NULL_TREE;
4973
4974   /* If we're in a template, but EXPR isn't value dependent, simplify
4975      it.  We're supposed to treat:
4976
4977        template <typename T> void f(T[1 + 1]);
4978        template <typename T> void f(T[2]);
4979
4980      as two declarations of the same function, for example.  */
4981   if (processing_template_decl
4982       && !type_dependent_expression_p (expr)
4983       && potential_constant_expression (expr)
4984       && !value_dependent_expression_p (expr))
4985     {
4986       HOST_WIDE_INT saved_processing_template_decl;
4987
4988       saved_processing_template_decl = processing_template_decl;
4989       processing_template_decl = 0;
4990       expr = tsubst_copy_and_build (expr,
4991                                     /*args=*/NULL_TREE,
4992                                     complain,
4993                                     /*in_decl=*/NULL_TREE,
4994                                     /*function_p=*/false,
4995                                     /*integral_constant_expression_p=*/true);
4996       processing_template_decl = saved_processing_template_decl;
4997     }
4998   return expr;
4999 }
5000
5001 tree
5002 fold_non_dependent_expr (tree expr)
5003 {
5004   return fold_non_dependent_expr_sfinae (expr, tf_error);
5005 }
5006
5007 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5008    template declaration, or a TYPE_DECL for an alias declaration.  */
5009
5010 bool
5011 alias_type_or_template_p (tree t)
5012 {
5013   if (t == NULL_TREE)
5014     return false;
5015   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5016           || (TYPE_P (t)
5017               && TYPE_NAME (t)
5018               && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5019           || DECL_ALIAS_TEMPLATE_P (t));
5020 }
5021
5022 /* Return TRUE iff is a specialization of an alias template.  */
5023
5024 bool
5025 alias_template_specialization_p (tree t)
5026 {
5027   if (t == NULL_TREE)
5028     return false;
5029   return (primary_template_instantiation_p (t)
5030           && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (t)));
5031 }
5032
5033 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5034    must be a function or a pointer-to-function type, as specified
5035    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5036    and check that the resulting function has external linkage.  */
5037
5038 static tree
5039 convert_nontype_argument_function (tree type, tree expr)
5040 {
5041   tree fns = expr;
5042   tree fn, fn_no_ptr;
5043   linkage_kind linkage;
5044
5045   fn = instantiate_type (type, fns, tf_none);
5046   if (fn == error_mark_node)
5047     return error_mark_node;
5048
5049   fn_no_ptr = fn;
5050   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5051     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5052   if (BASELINK_P (fn_no_ptr))
5053     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5054  
5055   /* [temp.arg.nontype]/1
5056
5057      A template-argument for a non-type, non-template template-parameter
5058      shall be one of:
5059      [...]
5060      -- the address of an object or function with external [C++11: or
5061         internal] linkage.  */
5062   linkage = decl_linkage (fn_no_ptr);
5063   if (cxx_dialect >= cxx0x ? linkage == lk_none : linkage != lk_external)
5064     {
5065       if (cxx_dialect >= cxx0x)
5066         error ("%qE is not a valid template argument for type %qT "
5067                "because %qD has no linkage",
5068                expr, type, fn_no_ptr);
5069       else
5070         error ("%qE is not a valid template argument for type %qT "
5071                "because %qD does not have external linkage",
5072                expr, type, fn_no_ptr);
5073       return NULL_TREE;
5074     }
5075
5076   return fn;
5077 }
5078
5079 /* Subroutine of convert_nontype_argument.
5080    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5081    Emit an error otherwise.  */
5082
5083 static bool
5084 check_valid_ptrmem_cst_expr (tree type, tree expr,
5085                              tsubst_flags_t complain)
5086 {
5087   STRIP_NOPS (expr);
5088   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5089     return true;
5090   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5091     return true;
5092   if (complain & tf_error)
5093     {
5094       error ("%qE is not a valid template argument for type %qT",
5095              expr, type);
5096       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5097     }
5098   return false;
5099 }
5100
5101 /* Returns TRUE iff the address of OP is value-dependent.
5102
5103    14.6.2.4 [temp.dep.temp]:
5104    A non-integral non-type template-argument is dependent if its type is
5105    dependent or it has either of the following forms
5106      qualified-id
5107      & qualified-id
5108    and contains a nested-name-specifier which specifies a class-name that
5109    names a dependent type.
5110
5111    We generalize this to just say that the address of a member of a
5112    dependent class is value-dependent; the above doesn't cover the
5113    address of a static data member named with an unqualified-id.  */
5114
5115 static bool
5116 has_value_dependent_address (tree op)
5117 {
5118   /* We could use get_inner_reference here, but there's no need;
5119      this is only relevant for template non-type arguments, which
5120      can only be expressed as &id-expression.  */
5121   if (DECL_P (op))
5122     {
5123       tree ctx = CP_DECL_CONTEXT (op);
5124       if (TYPE_P (ctx) && dependent_type_p (ctx))
5125         return true;
5126     }
5127
5128   return false;
5129 }
5130
5131 /* The next set of functions are used for providing helpful explanatory
5132    diagnostics for failed overload resolution.  Their messages should be
5133    indented by two spaces for consistency with the messages in
5134    call.c  */
5135
5136 static int
5137 unify_success (bool explain_p ATTRIBUTE_UNUSED)
5138 {
5139   return 0;
5140 }
5141
5142 static int
5143 unify_parameter_deduction_failure (bool explain_p, tree parm)
5144 {
5145   if (explain_p)
5146     inform (input_location,
5147             "  couldn't deduce template parameter %qD", parm);
5148   return 1;
5149 }
5150
5151 static int
5152 unify_invalid (bool explain_p ATTRIBUTE_UNUSED)
5153 {
5154   return 1;
5155 }
5156
5157 static int
5158 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5159 {
5160   if (explain_p)
5161     inform (input_location,
5162             "  types %qT and %qT have incompatible cv-qualifiers",
5163             parm, arg);
5164   return 1;
5165 }
5166
5167 static int
5168 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5169 {
5170   if (explain_p)
5171     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5172   return 1;
5173 }
5174
5175 static int
5176 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5177 {
5178   if (explain_p)
5179     inform (input_location,
5180             "  template parameter %qD is not a parameter pack, but "
5181             "argument %qD is",
5182             parm, arg);
5183   return 1;
5184 }
5185
5186 static int
5187 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5188 {
5189   if (explain_p)
5190     inform (input_location,
5191             "  template argument %qE does not match "
5192             "pointer-to-member constant %qE",
5193             arg, parm);
5194   return 1;
5195 }
5196
5197 static int
5198 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5199 {
5200   if (explain_p)
5201     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5202   return 1;
5203 }
5204
5205 static int
5206 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5207 {
5208   if (explain_p)
5209     inform (input_location,
5210             "  inconsistent parameter pack deduction with %qT and %qT",
5211             old_arg, new_arg);
5212   return 1;
5213 }
5214
5215 static int
5216 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5217 {
5218   if (explain_p)
5219     {
5220       if (TYPE_P (parm))
5221         inform (input_location,
5222                 "  deduced conflicting types for parameter %qT (%qT and %qT)",
5223                 parm, first, second);
5224       else
5225         inform (input_location,
5226                 "  deduced conflicting values for non-type parameter "
5227                 "%qE (%qE and %qE)", parm, first, second);
5228     }
5229   return 1;
5230 }
5231
5232 static int
5233 unify_vla_arg (bool explain_p, tree arg)
5234 {
5235   if (explain_p)
5236     inform (input_location,
5237             "  variable-sized array type %qT is not "
5238             "a valid template argument",
5239             arg);
5240   return 1;
5241 }
5242
5243 static int
5244 unify_method_type_error (bool explain_p, tree arg)
5245 {
5246   if (explain_p)
5247     inform (input_location,
5248             "  member function type %qT is not a valid template argument",
5249             arg);
5250   return 1;
5251 }
5252
5253 static int
5254 unify_arity (bool explain_p, int have, int wanted)
5255 {
5256   if (explain_p)
5257     inform_n (input_location, wanted,
5258               "  candidate expects %d argument, %d provided",
5259               "  candidate expects %d arguments, %d provided",
5260               wanted, have);
5261   return 1;
5262 }
5263
5264 static int
5265 unify_too_many_arguments (bool explain_p, int have, int wanted)
5266 {
5267   return unify_arity (explain_p, have, wanted);
5268 }
5269
5270 static int
5271 unify_too_few_arguments (bool explain_p, int have, int wanted)
5272 {
5273   return unify_arity (explain_p, have, wanted);
5274 }
5275
5276 static int
5277 unify_arg_conversion (bool explain_p, tree to_type,
5278                       tree from_type, tree arg)
5279 {
5280   if (explain_p)
5281     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5282             arg, from_type, to_type);
5283   return 1;
5284 }
5285
5286 static int
5287 unify_no_common_base (bool explain_p, enum template_base_result r,
5288                       tree parm, tree arg)
5289 {
5290   if (explain_p)
5291     switch (r)
5292       {
5293       case tbr_ambiguous_baseclass:
5294         inform (input_location, "  %qT is an ambiguous base class of %qT",
5295                 arg, parm);
5296         break;
5297       default:
5298         inform (input_location, "  %qT is not derived from %qT", arg, parm);
5299         break;
5300       }
5301   return 1;
5302 }
5303
5304 static int
5305 unify_inconsistent_template_template_parameters (bool explain_p)
5306 {
5307   if (explain_p)
5308     inform (input_location,
5309             "  template parameters of a template template argument are "
5310             "inconsistent with other deduced template arguments");
5311   return 1;
5312 }
5313
5314 static int
5315 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5316 {
5317   if (explain_p)
5318     inform (input_location,
5319             "  can't deduce a template for %qT from non-template type %qT",
5320             parm, arg);
5321   return 1;
5322 }
5323
5324 static int
5325 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5326 {
5327   if (explain_p)
5328     inform (input_location,
5329             "  template argument %qE does not match %qD", arg, parm);
5330   return 1;
5331 }
5332
5333 static int
5334 unify_overload_resolution_failure (bool explain_p, tree arg)
5335 {
5336   if (explain_p)
5337     inform (input_location,
5338             "  could not resolve address from overloaded function %qE",
5339             arg);
5340   return 1;
5341 }
5342
5343 /* Attempt to convert the non-type template parameter EXPR to the
5344    indicated TYPE.  If the conversion is successful, return the
5345    converted value.  If the conversion is unsuccessful, return
5346    NULL_TREE if we issued an error message, or error_mark_node if we
5347    did not.  We issue error messages for out-and-out bad template
5348    parameters, but not simply because the conversion failed, since we
5349    might be just trying to do argument deduction.  Both TYPE and EXPR
5350    must be non-dependent.
5351
5352    The conversion follows the special rules described in
5353    [temp.arg.nontype], and it is much more strict than an implicit
5354    conversion.
5355
5356    This function is called twice for each template argument (see
5357    lookup_template_class for a more accurate description of this
5358    problem). This means that we need to handle expressions which
5359    are not valid in a C++ source, but can be created from the
5360    first call (for instance, casts to perform conversions). These
5361    hacks can go away after we fix the double coercion problem.  */
5362
5363 static tree
5364 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5365 {
5366   tree expr_type;
5367
5368   /* Detect immediately string literals as invalid non-type argument.
5369      This special-case is not needed for correctness (we would easily
5370      catch this later), but only to provide better diagnostic for this
5371      common user mistake. As suggested by DR 100, we do not mention
5372      linkage issues in the diagnostic as this is not the point.  */
5373   /* FIXME we're making this OK.  */
5374   if (TREE_CODE (expr) == STRING_CST)
5375     {
5376       if (complain & tf_error)
5377         error ("%qE is not a valid template argument for type %qT "
5378                "because string literals can never be used in this context",
5379                expr, type);
5380       return NULL_TREE;
5381     }
5382
5383   /* Add the ADDR_EXPR now for the benefit of
5384      value_dependent_expression_p.  */
5385   if (TYPE_PTROBV_P (type)
5386       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5387     expr = decay_conversion (expr);
5388
5389   /* If we are in a template, EXPR may be non-dependent, but still
5390      have a syntactic, rather than semantic, form.  For example, EXPR
5391      might be a SCOPE_REF, rather than the VAR_DECL to which the
5392      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5393      so that access checking can be performed when the template is
5394      instantiated -- but here we need the resolved form so that we can
5395      convert the argument.  */
5396   if (TYPE_REF_OBJ_P (type)
5397       && has_value_dependent_address (expr))
5398     /* If we want the address and it's value-dependent, don't fold.  */;
5399   else if (!type_unknown_p (expr))
5400     expr = fold_non_dependent_expr_sfinae (expr, complain);
5401   if (error_operand_p (expr))
5402     return error_mark_node;
5403   expr_type = TREE_TYPE (expr);
5404   if (TREE_CODE (type) == REFERENCE_TYPE)
5405     expr = mark_lvalue_use (expr);
5406   else
5407     expr = mark_rvalue_use (expr);
5408
5409   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5410      to a non-type argument of "nullptr".  */
5411   if (expr == nullptr_node
5412       && (TYPE_PTR_P (type) || TYPE_PTR_TO_MEMBER_P (type)))
5413     expr = convert (type, expr);
5414
5415   /* In C++11, integral or enumeration non-type template arguments can be
5416      arbitrary constant expressions.  Pointer and pointer to
5417      member arguments can be general constant expressions that evaluate
5418      to a null value, but otherwise still need to be of a specific form.  */
5419   if (cxx_dialect >= cxx0x)
5420     {
5421       if (TREE_CODE (expr) == PTRMEM_CST)
5422         /* A PTRMEM_CST is already constant, and a valid template
5423            argument for a parameter of pointer to member type, we just want
5424            to leave it in that form rather than lower it to a
5425            CONSTRUCTOR.  */;
5426       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5427         expr = maybe_constant_value (expr);
5428       else if (TYPE_PTR_P (type)
5429                || TYPE_PTR_TO_MEMBER_P (type))
5430         {
5431           tree folded = maybe_constant_value (expr);
5432           if (TYPE_PTR_P (type) ? integer_zerop (folded)
5433               : null_member_pointer_value_p (folded))
5434             expr = folded;
5435         }
5436     }
5437
5438   /* HACK: Due to double coercion, we can get a
5439      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5440      which is the tree that we built on the first call (see
5441      below when coercing to reference to object or to reference to
5442      function). We just strip everything and get to the arg.
5443      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5444      for examples.  */
5445   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5446     {
5447       tree probe_type, probe = expr;
5448       if (REFERENCE_REF_P (probe))
5449         probe = TREE_OPERAND (probe, 0);
5450       probe_type = TREE_TYPE (probe);
5451       if (TREE_CODE (probe) == NOP_EXPR)
5452         {
5453           /* ??? Maybe we could use convert_from_reference here, but we
5454              would need to relax its constraints because the NOP_EXPR
5455              could actually change the type to something more cv-qualified,
5456              and this is not folded by convert_from_reference.  */
5457           tree addr = TREE_OPERAND (probe, 0);
5458           gcc_assert (TREE_CODE (probe_type) == REFERENCE_TYPE);
5459           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5460           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5461           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5462                       (TREE_TYPE (probe_type),
5463                        TREE_TYPE (TREE_TYPE (addr))));
5464
5465           expr = TREE_OPERAND (addr, 0);
5466           expr_type = TREE_TYPE (expr);
5467         }
5468     }
5469
5470   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5471      parameter is a pointer to object, through decay and
5472      qualification conversion. Let's strip everything.  */
5473   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5474     {
5475       STRIP_NOPS (expr);
5476       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5477       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5478       /* Skip the ADDR_EXPR only if it is part of the decay for
5479          an array. Otherwise, it is part of the original argument
5480          in the source code.  */
5481       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5482         expr = TREE_OPERAND (expr, 0);
5483       expr_type = TREE_TYPE (expr);
5484     }
5485
5486   /* [temp.arg.nontype]/5, bullet 1
5487
5488      For a non-type template-parameter of integral or enumeration type,
5489      integral promotions (_conv.prom_) and integral conversions
5490      (_conv.integral_) are applied.  */
5491   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5492     {
5493       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5494       t = maybe_constant_value (t);
5495       if (t != error_mark_node)
5496         expr = t;
5497
5498       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5499         return error_mark_node;
5500
5501       /* Notice that there are constant expressions like '4 % 0' which
5502          do not fold into integer constants.  */
5503       if (TREE_CODE (expr) != INTEGER_CST)
5504         {
5505           if (complain & tf_error)
5506             {
5507               int errs = errorcount, warns = warningcount;
5508               if (processing_template_decl
5509                   && !require_potential_constant_expression (expr))
5510                 return NULL_TREE;
5511               expr = cxx_constant_value (expr);
5512               if (errorcount > errs || warningcount > warns)
5513                 inform (EXPR_LOC_OR_HERE (expr),
5514                         "in template argument for type %qT ", type);
5515               if (expr == error_mark_node)
5516                 return NULL_TREE;
5517               /* else cxx_constant_value complained but gave us
5518                  a real constant, so go ahead.  */
5519               gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5520             }
5521           else
5522             return NULL_TREE;
5523         }
5524     }
5525   /* [temp.arg.nontype]/5, bullet 2
5526
5527      For a non-type template-parameter of type pointer to object,
5528      qualification conversions (_conv.qual_) and the array-to-pointer
5529      conversion (_conv.array_) are applied.  */
5530   else if (TYPE_PTROBV_P (type))
5531     {
5532       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5533
5534          A template-argument for a non-type, non-template template-parameter
5535          shall be one of: [...]
5536
5537          -- the name of a non-type template-parameter;
5538          -- the address of an object or function with external linkage, [...]
5539             expressed as "& id-expression" where the & is optional if the name
5540             refers to a function or array, or if the corresponding
5541             template-parameter is a reference.
5542
5543         Here, we do not care about functions, as they are invalid anyway
5544         for a parameter of type pointer-to-object.  */
5545
5546       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5547         /* Non-type template parameters are OK.  */
5548         ;
5549       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5550         /* Null pointer values are OK in C++11.  */;
5551       else if (TREE_CODE (expr) != ADDR_EXPR
5552                && TREE_CODE (expr_type) != ARRAY_TYPE)
5553         {
5554           if (TREE_CODE (expr) == VAR_DECL)
5555             {
5556               error ("%qD is not a valid template argument "
5557                      "because %qD is a variable, not the address of "
5558                      "a variable",
5559                      expr, expr);
5560               return NULL_TREE;
5561             }
5562           /* Other values, like integer constants, might be valid
5563              non-type arguments of some other type.  */
5564           return error_mark_node;
5565         }
5566       else
5567         {
5568           tree decl;
5569
5570           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5571                   ? TREE_OPERAND (expr, 0) : expr);
5572           if (TREE_CODE (decl) != VAR_DECL)
5573             {
5574               error ("%qE is not a valid template argument of type %qT "
5575                      "because %qE is not a variable",
5576                      expr, type, decl);
5577               return NULL_TREE;
5578             }
5579           else if (cxx_dialect < cxx0x && !DECL_EXTERNAL_LINKAGE_P (decl))
5580             {
5581               error ("%qE is not a valid template argument of type %qT "
5582                      "because %qD does not have external linkage",
5583                      expr, type, decl);
5584               return NULL_TREE;
5585             }
5586           else if (cxx_dialect >= cxx0x && decl_linkage (decl) == lk_none)
5587             {
5588               error ("%qE is not a valid template argument of type %qT "
5589                      "because %qD has no linkage",
5590                      expr, type, decl);
5591               return NULL_TREE;
5592             }
5593         }
5594
5595       expr = decay_conversion (expr);
5596       if (expr == error_mark_node)
5597         return error_mark_node;
5598
5599       expr = perform_qualification_conversions (type, expr);
5600       if (expr == error_mark_node)
5601         return error_mark_node;
5602     }
5603   /* [temp.arg.nontype]/5, bullet 3
5604
5605      For a non-type template-parameter of type reference to object, no
5606      conversions apply. The type referred to by the reference may be more
5607      cv-qualified than the (otherwise identical) type of the
5608      template-argument. The template-parameter is bound directly to the
5609      template-argument, which must be an lvalue.  */
5610   else if (TYPE_REF_OBJ_P (type))
5611     {
5612       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5613                                                       expr_type))
5614         return error_mark_node;
5615
5616       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5617         {
5618           error ("%qE is not a valid template argument for type %qT "
5619                  "because of conflicts in cv-qualification", expr, type);
5620           return NULL_TREE;
5621         }
5622
5623       if (!real_lvalue_p (expr))
5624         {
5625           error ("%qE is not a valid template argument for type %qT "
5626                  "because it is not an lvalue", expr, type);
5627           return NULL_TREE;
5628         }
5629
5630       /* [temp.arg.nontype]/1
5631
5632          A template-argument for a non-type, non-template template-parameter
5633          shall be one of: [...]
5634
5635          -- the address of an object or function with external linkage.  */
5636       if (TREE_CODE (expr) == INDIRECT_REF
5637           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5638         {
5639           expr = TREE_OPERAND (expr, 0);
5640           if (DECL_P (expr))
5641             {
5642               error ("%q#D is not a valid template argument for type %qT "
5643                      "because a reference variable does not have a constant "
5644                      "address", expr, type);
5645               return NULL_TREE;
5646             }
5647         }
5648
5649       if (!DECL_P (expr))
5650         {
5651           error ("%qE is not a valid template argument for type %qT "
5652                  "because it is not an object with external linkage",
5653                  expr, type);
5654           return NULL_TREE;
5655         }
5656
5657       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5658         {
5659           error ("%qE is not a valid template argument for type %qT "
5660                  "because object %qD has not external linkage",
5661                  expr, type, expr);
5662           return NULL_TREE;
5663         }
5664
5665       expr = build_nop (type, build_address (expr));
5666     }
5667   /* [temp.arg.nontype]/5, bullet 4
5668
5669      For a non-type template-parameter of type pointer to function, only
5670      the function-to-pointer conversion (_conv.func_) is applied. If the
5671      template-argument represents a set of overloaded functions (or a
5672      pointer to such), the matching function is selected from the set
5673      (_over.over_).  */
5674   else if (TYPE_PTRFN_P (type))
5675     {
5676       /* If the argument is a template-id, we might not have enough
5677          context information to decay the pointer.  */
5678       if (!type_unknown_p (expr_type))
5679         {
5680           expr = decay_conversion (expr);
5681           if (expr == error_mark_node)
5682             return error_mark_node;
5683         }
5684
5685       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5686         /* Null pointer values are OK in C++11.  */
5687         return perform_qualification_conversions (type, expr);
5688
5689       expr = convert_nontype_argument_function (type, expr);
5690       if (!expr || expr == error_mark_node)
5691         return expr;
5692
5693       if (TREE_CODE (expr) != ADDR_EXPR)
5694         {
5695           error ("%qE is not a valid template argument for type %qT", expr, type);
5696           error ("it must be the address of a function with external linkage");
5697           return NULL_TREE;
5698         }
5699     }
5700   /* [temp.arg.nontype]/5, bullet 5
5701
5702      For a non-type template-parameter of type reference to function, no
5703      conversions apply. If the template-argument represents a set of
5704      overloaded functions, the matching function is selected from the set
5705      (_over.over_).  */
5706   else if (TYPE_REFFN_P (type))
5707     {
5708       if (TREE_CODE (expr) == ADDR_EXPR)
5709         {
5710           error ("%qE is not a valid template argument for type %qT "
5711                  "because it is a pointer", expr, type);
5712           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5713           return NULL_TREE;
5714         }
5715
5716       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5717       if (!expr || expr == error_mark_node)
5718         return expr;
5719
5720       expr = build_nop (type, build_address (expr));
5721     }
5722   /* [temp.arg.nontype]/5, bullet 6
5723
5724      For a non-type template-parameter of type pointer to member function,
5725      no conversions apply. If the template-argument represents a set of
5726      overloaded member functions, the matching member function is selected
5727      from the set (_over.over_).  */
5728   else if (TYPE_PTRMEMFUNC_P (type))
5729     {
5730       expr = instantiate_type (type, expr, tf_none);
5731       if (expr == error_mark_node)
5732         return error_mark_node;
5733
5734       /* [temp.arg.nontype] bullet 1 says the pointer to member
5735          expression must be a pointer-to-member constant.  */
5736       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5737         return error_mark_node;
5738
5739       /* There is no way to disable standard conversions in
5740          resolve_address_of_overloaded_function (called by
5741          instantiate_type). It is possible that the call succeeded by
5742          converting &B::I to &D::I (where B is a base of D), so we need
5743          to reject this conversion here.
5744
5745          Actually, even if there was a way to disable standard conversions,
5746          it would still be better to reject them here so that we can
5747          provide a superior diagnostic.  */
5748       if (!same_type_p (TREE_TYPE (expr), type))
5749         {
5750           error ("%qE is not a valid template argument for type %qT "
5751                  "because it is of type %qT", expr, type,
5752                  TREE_TYPE (expr));
5753           /* If we are just one standard conversion off, explain.  */
5754           if (can_convert (type, TREE_TYPE (expr)))
5755             inform (input_location,
5756                     "standard conversions are not allowed in this context");
5757           return NULL_TREE;
5758         }
5759     }
5760   /* [temp.arg.nontype]/5, bullet 7
5761
5762      For a non-type template-parameter of type pointer to data member,
5763      qualification conversions (_conv.qual_) are applied.  */
5764   else if (TYPE_PTRMEM_P (type))
5765     {
5766       /* [temp.arg.nontype] bullet 1 says the pointer to member
5767          expression must be a pointer-to-member constant.  */
5768       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5769         return error_mark_node;
5770
5771       expr = perform_qualification_conversions (type, expr);
5772       if (expr == error_mark_node)
5773         return expr;
5774     }
5775   else if (NULLPTR_TYPE_P (type))
5776     {
5777       if (expr != nullptr_node)
5778         {
5779           error ("%qE is not a valid template argument for type %qT "
5780                  "because it is of type %qT", expr, type, TREE_TYPE (expr));
5781           return NULL_TREE;
5782         }
5783       return expr;
5784     }
5785   /* A template non-type parameter must be one of the above.  */
5786   else
5787     gcc_unreachable ();
5788
5789   /* Sanity check: did we actually convert the argument to the
5790      right type?  */
5791   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5792               (type, TREE_TYPE (expr)));
5793   return expr;
5794 }
5795
5796 /* Subroutine of coerce_template_template_parms, which returns 1 if
5797    PARM_PARM and ARG_PARM match using the rule for the template
5798    parameters of template template parameters. Both PARM and ARG are
5799    template parameters; the rest of the arguments are the same as for
5800    coerce_template_template_parms.
5801  */
5802 static int
5803 coerce_template_template_parm (tree parm,
5804                               tree arg,
5805                               tsubst_flags_t complain,
5806                               tree in_decl,
5807                               tree outer_args)
5808 {
5809   if (arg == NULL_TREE || arg == error_mark_node
5810       || parm == NULL_TREE || parm == error_mark_node)
5811     return 0;
5812   
5813   if (TREE_CODE (arg) != TREE_CODE (parm))
5814     return 0;
5815   
5816   switch (TREE_CODE (parm))
5817     {
5818     case TEMPLATE_DECL:
5819       /* We encounter instantiations of templates like
5820          template <template <template <class> class> class TT>
5821          class C;  */
5822       {
5823         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5824         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5825         
5826         if (!coerce_template_template_parms
5827             (parmparm, argparm, complain, in_decl, outer_args))
5828           return 0;
5829       }
5830       /* Fall through.  */
5831       
5832     case TYPE_DECL:
5833       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5834           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5835         /* Argument is a parameter pack but parameter is not.  */
5836         return 0;
5837       break;
5838       
5839     case PARM_DECL:
5840       /* The tsubst call is used to handle cases such as
5841          
5842            template <int> class C {};
5843            template <class T, template <T> class TT> class D {};
5844            D<int, C> d;
5845
5846          i.e. the parameter list of TT depends on earlier parameters.  */
5847       if (!uses_template_parms (TREE_TYPE (arg))
5848           && !same_type_p
5849                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5850                  TREE_TYPE (arg)))
5851         return 0;
5852       
5853       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5854           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5855         /* Argument is a parameter pack but parameter is not.  */
5856         return 0;
5857       
5858       break;
5859
5860     default:
5861       gcc_unreachable ();
5862     }
5863
5864   return 1;
5865 }
5866
5867
5868 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5869    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5870    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5871    or PARM_DECL.
5872
5873    Consider the example:
5874      template <class T> class A;
5875      template<template <class U> class TT> class B;
5876
5877    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5878    the parameters to A, and OUTER_ARGS contains A.  */
5879
5880 static int
5881 coerce_template_template_parms (tree parm_parms,
5882                                 tree arg_parms,
5883                                 tsubst_flags_t complain,
5884                                 tree in_decl,
5885                                 tree outer_args)
5886 {
5887   int nparms, nargs, i;
5888   tree parm, arg;
5889   int variadic_p = 0;
5890
5891   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5892   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5893
5894   nparms = TREE_VEC_LENGTH (parm_parms);
5895   nargs = TREE_VEC_LENGTH (arg_parms);
5896
5897   /* Determine whether we have a parameter pack at the end of the
5898      template template parameter's template parameter list.  */
5899   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5900     {
5901       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5902       
5903       if (parm == error_mark_node)
5904         return 0;
5905
5906       switch (TREE_CODE (parm))
5907         {
5908         case TEMPLATE_DECL:
5909         case TYPE_DECL:
5910           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5911             variadic_p = 1;
5912           break;
5913           
5914         case PARM_DECL:
5915           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5916             variadic_p = 1;
5917           break;
5918           
5919         default:
5920           gcc_unreachable ();
5921         }
5922     }
5923  
5924   if (nargs != nparms
5925       && !(variadic_p && nargs >= nparms - 1))
5926     return 0;
5927
5928   /* Check all of the template parameters except the parameter pack at
5929      the end (if any).  */
5930   for (i = 0; i < nparms - variadic_p; ++i)
5931     {
5932       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5933           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5934         continue;
5935
5936       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5937       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5938
5939       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5940                                           outer_args))
5941         return 0;
5942
5943     }
5944
5945   if (variadic_p)
5946     {
5947       /* Check each of the template parameters in the template
5948          argument against the template parameter pack at the end of
5949          the template template parameter.  */
5950       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5951         return 0;
5952
5953       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5954
5955       for (; i < nargs; ++i)
5956         {
5957           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5958             continue;
5959  
5960           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5961  
5962           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5963                                               outer_args))
5964             return 0;
5965         }
5966     }
5967
5968   return 1;
5969 }
5970
5971 /* Verifies that the deduced template arguments (in TARGS) for the
5972    template template parameters (in TPARMS) represent valid bindings,
5973    by comparing the template parameter list of each template argument
5974    to the template parameter list of its corresponding template
5975    template parameter, in accordance with DR150. This
5976    routine can only be called after all template arguments have been
5977    deduced. It will return TRUE if all of the template template
5978    parameter bindings are okay, FALSE otherwise.  */
5979 bool 
5980 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5981 {
5982   int i, ntparms = TREE_VEC_LENGTH (tparms);
5983   bool ret = true;
5984
5985   /* We're dealing with template parms in this process.  */
5986   ++processing_template_decl;
5987
5988   targs = INNERMOST_TEMPLATE_ARGS (targs);
5989
5990   for (i = 0; i < ntparms; ++i)
5991     {
5992       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5993       tree targ = TREE_VEC_ELT (targs, i);
5994
5995       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5996         {
5997           tree packed_args = NULL_TREE;
5998           int idx, len = 1;
5999
6000           if (ARGUMENT_PACK_P (targ))
6001             {
6002               /* Look inside the argument pack.  */
6003               packed_args = ARGUMENT_PACK_ARGS (targ);
6004               len = TREE_VEC_LENGTH (packed_args);
6005             }
6006
6007           for (idx = 0; idx < len; ++idx)
6008             {
6009               tree targ_parms = NULL_TREE;
6010
6011               if (packed_args)
6012                 /* Extract the next argument from the argument
6013                    pack.  */
6014                 targ = TREE_VEC_ELT (packed_args, idx);
6015
6016               if (PACK_EXPANSION_P (targ))
6017                 /* Look at the pattern of the pack expansion.  */
6018                 targ = PACK_EXPANSION_PATTERN (targ);
6019
6020               /* Extract the template parameters from the template
6021                  argument.  */
6022               if (TREE_CODE (targ) == TEMPLATE_DECL)
6023                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6024               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6025                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6026
6027               /* Verify that we can coerce the template template
6028                  parameters from the template argument to the template
6029                  parameter.  This requires an exact match.  */
6030               if (targ_parms
6031                   && !coerce_template_template_parms
6032                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6033                         targ_parms,
6034                         tf_none,
6035                         tparm,
6036                         targs))
6037                 {
6038                   ret = false;
6039                   goto out;
6040                 }
6041             }
6042         }
6043     }
6044
6045  out:
6046
6047   --processing_template_decl;
6048   return ret;
6049 }
6050
6051 /* Since type attributes aren't mangled, we need to strip them from
6052    template type arguments.  */
6053
6054 static tree
6055 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6056 {
6057   tree mv;
6058   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6059     return arg;
6060   mv = TYPE_MAIN_VARIANT (arg);
6061   arg = strip_typedefs (arg);
6062   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6063       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6064     {
6065       if (complain & tf_warning)
6066         warning (0, "ignoring attributes on template argument %qT", arg);
6067       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6068       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6069     }
6070   return arg;
6071 }
6072
6073 /* Convert the indicated template ARG as necessary to match the
6074    indicated template PARM.  Returns the converted ARG, or
6075    error_mark_node if the conversion was unsuccessful.  Error and
6076    warning messages are issued under control of COMPLAIN.  This
6077    conversion is for the Ith parameter in the parameter list.  ARGS is
6078    the full set of template arguments deduced so far.  */
6079
6080 static tree
6081 convert_template_argument (tree parm,
6082                            tree arg,
6083                            tree args,
6084                            tsubst_flags_t complain,
6085                            int i,
6086                            tree in_decl)
6087 {
6088   tree orig_arg;
6089   tree val;
6090   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6091
6092   if (TREE_CODE (arg) == TREE_LIST
6093       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6094     {
6095       /* The template argument was the name of some
6096          member function.  That's usually
6097          invalid, but static members are OK.  In any
6098          case, grab the underlying fields/functions
6099          and issue an error later if required.  */
6100       orig_arg = TREE_VALUE (arg);
6101       TREE_TYPE (arg) = unknown_type_node;
6102     }
6103
6104   orig_arg = arg;
6105
6106   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6107   requires_type = (TREE_CODE (parm) == TYPE_DECL
6108                    || requires_tmpl_type);
6109
6110   /* When determining whether an argument pack expansion is a template,
6111      look at the pattern.  */
6112   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6113     arg = PACK_EXPANSION_PATTERN (arg);
6114
6115   /* Deal with an injected-class-name used as a template template arg.  */
6116   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6117     {
6118       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6119       if (TREE_CODE (t) == TEMPLATE_DECL)
6120         {
6121           if (cxx_dialect >= cxx0x)
6122             /* OK under DR 1004.  */;
6123           else if (complain & tf_warning_or_error)
6124             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
6125                      " used as template template argument", TYPE_NAME (arg));
6126           else if (flag_pedantic_errors)
6127             t = arg;
6128
6129           arg = t;
6130         }
6131     }
6132
6133   is_tmpl_type = 
6134     ((TREE_CODE (arg) == TEMPLATE_DECL
6135       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6136      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
6137      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6138      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6139
6140   if (is_tmpl_type
6141       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6142           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6143     arg = TYPE_STUB_DECL (arg);
6144
6145   is_type = TYPE_P (arg) || is_tmpl_type;
6146
6147   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6148       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6149     {
6150       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
6151         {
6152           if (complain & tf_error)
6153             error ("invalid use of destructor %qE as a type", orig_arg);
6154           return error_mark_node;
6155         }
6156
6157       permerror (input_location,
6158                  "to refer to a type member of a template parameter, "
6159                  "use %<typename %E%>", orig_arg);
6160
6161       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6162                                      TREE_OPERAND (arg, 1),
6163                                      typename_type,
6164                                      complain & tf_error);
6165       arg = orig_arg;
6166       is_type = 1;
6167     }
6168   if (is_type != requires_type)
6169     {
6170       if (in_decl)
6171         {
6172           if (complain & tf_error)
6173             {
6174               error ("type/value mismatch at argument %d in template "
6175                      "parameter list for %qD",
6176                      i + 1, in_decl);
6177               if (is_type)
6178                 error ("  expected a constant of type %qT, got %qT",
6179                        TREE_TYPE (parm),
6180                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6181               else if (requires_tmpl_type)
6182                 error ("  expected a class template, got %qE", orig_arg);
6183               else
6184                 error ("  expected a type, got %qE", orig_arg);
6185             }
6186         }
6187       return error_mark_node;
6188     }
6189   if (is_tmpl_type ^ requires_tmpl_type)
6190     {
6191       if (in_decl && (complain & tf_error))
6192         {
6193           error ("type/value mismatch at argument %d in template "
6194                  "parameter list for %qD",
6195                  i + 1, in_decl);
6196           if (is_tmpl_type)
6197             error ("  expected a type, got %qT", DECL_NAME (arg));
6198           else
6199             error ("  expected a class template, got %qT", orig_arg);
6200         }
6201       return error_mark_node;
6202     }
6203
6204   if (is_type)
6205     {
6206       if (requires_tmpl_type)
6207         {
6208           if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6209             val = orig_arg;
6210           else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6211             /* The number of argument required is not known yet.
6212                Just accept it for now.  */
6213             val = TREE_TYPE (arg);
6214           else
6215             {
6216               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6217               tree argparm;
6218
6219               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6220
6221               if (coerce_template_template_parms (parmparm, argparm,
6222                                                   complain, in_decl,
6223                                                   args))
6224                 {
6225                   val = arg;
6226
6227                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6228                      TEMPLATE_DECL.  */
6229                   if (val != error_mark_node)
6230                     {
6231                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6232                         val = TREE_TYPE (val);
6233                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6234                         val = make_pack_expansion (val);
6235                     }
6236                 }
6237               else
6238                 {
6239                   if (in_decl && (complain & tf_error))
6240                     {
6241                       error ("type/value mismatch at argument %d in "
6242                              "template parameter list for %qD",
6243                              i + 1, in_decl);
6244                       error ("  expected a template of type %qD, got %qT",
6245                              parm, orig_arg);
6246                     }
6247
6248                   val = error_mark_node;
6249                 }
6250             }
6251         }
6252       else
6253         val = orig_arg;
6254       /* We only form one instance of each template specialization.
6255          Therefore, if we use a non-canonical variant (i.e., a
6256          typedef), any future messages referring to the type will use
6257          the typedef, which is confusing if those future uses do not
6258          themselves also use the typedef.  */
6259       if (TYPE_P (val))
6260         val = canonicalize_type_argument (val, complain);
6261     }
6262   else
6263     {
6264       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6265
6266       if (invalid_nontype_parm_type_p (t, complain))
6267         return error_mark_node;
6268
6269       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6270         {
6271           if (same_type_p (t, TREE_TYPE (orig_arg)))
6272             val = orig_arg;
6273           else
6274             {
6275               /* Not sure if this is reachable, but it doesn't hurt
6276                  to be robust.  */
6277               error ("type mismatch in nontype parameter pack");
6278               val = error_mark_node;
6279             }
6280         }
6281       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6282         /* We used to call digest_init here.  However, digest_init
6283            will report errors, which we don't want when complain
6284            is zero.  More importantly, digest_init will try too
6285            hard to convert things: for example, `0' should not be
6286            converted to pointer type at this point according to
6287            the standard.  Accepting this is not merely an
6288            extension, since deciding whether or not these
6289            conversions can occur is part of determining which
6290            function template to call, or whether a given explicit
6291            argument specification is valid.  */
6292         val = convert_nontype_argument (t, orig_arg, complain);
6293       else
6294         val = strip_typedefs_expr (orig_arg);
6295
6296       if (val == NULL_TREE)
6297         val = error_mark_node;
6298       else if (val == error_mark_node && (complain & tf_error))
6299         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6300
6301       if (TREE_CODE (val) == SCOPE_REF)
6302         {
6303           /* Strip typedefs from the SCOPE_REF.  */
6304           tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6305           tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6306                                                    complain);
6307           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6308                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6309         }
6310     }
6311
6312   return val;
6313 }
6314
6315 /* Coerces the remaining template arguments in INNER_ARGS (from
6316    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6317    Returns the coerced argument pack. PARM_IDX is the position of this
6318    parameter in the template parameter list. ARGS is the original
6319    template argument list.  */
6320 static tree
6321 coerce_template_parameter_pack (tree parms,
6322                                 int parm_idx,
6323                                 tree args,
6324                                 tree inner_args,
6325                                 int arg_idx,
6326                                 tree new_args,
6327                                 int* lost,
6328                                 tree in_decl,
6329                                 tsubst_flags_t complain)
6330 {
6331   tree parm = TREE_VEC_ELT (parms, parm_idx);
6332   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6333   tree packed_args;
6334   tree argument_pack;
6335   tree packed_types = NULL_TREE;
6336
6337   if (arg_idx > nargs)
6338     arg_idx = nargs;
6339
6340   packed_args = make_tree_vec (nargs - arg_idx);
6341
6342   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6343       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6344     {
6345       /* When the template parameter is a non-type template
6346          parameter pack whose type uses parameter packs, we need
6347          to look at each of the template arguments
6348          separately. Build a vector of the types for these
6349          non-type template parameters in PACKED_TYPES.  */
6350       tree expansion 
6351         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6352       packed_types = tsubst_pack_expansion (expansion, args,
6353                                             complain, in_decl);
6354
6355       if (packed_types == error_mark_node)
6356         return error_mark_node;
6357
6358       /* Check that we have the right number of arguments.  */
6359       if (arg_idx < nargs
6360           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6361           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6362         {
6363           int needed_parms 
6364             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6365           error ("wrong number of template arguments (%d, should be %d)",
6366                  nargs, needed_parms);
6367           return error_mark_node;
6368         }
6369
6370       /* If we aren't able to check the actual arguments now
6371          (because they haven't been expanded yet), we can at least
6372          verify that all of the types used for the non-type
6373          template parameter pack are, in fact, valid for non-type
6374          template parameters.  */
6375       if (arg_idx < nargs 
6376           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6377         {
6378           int j, len = TREE_VEC_LENGTH (packed_types);
6379           for (j = 0; j < len; ++j)
6380             {
6381               tree t = TREE_VEC_ELT (packed_types, j);
6382               if (invalid_nontype_parm_type_p (t, complain))
6383                 return error_mark_node;
6384             }
6385         }
6386     }
6387
6388   /* Convert the remaining arguments, which will be a part of the
6389      parameter pack "parm".  */
6390   for (; arg_idx < nargs; ++arg_idx)
6391     {
6392       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6393       tree actual_parm = TREE_VALUE (parm);
6394
6395       if (packed_types && !PACK_EXPANSION_P (arg))
6396         {
6397           /* When we have a vector of types (corresponding to the
6398              non-type template parameter pack that uses parameter
6399              packs in its type, as mention above), and the
6400              argument is not an expansion (which expands to a
6401              currently unknown number of arguments), clone the
6402              parm and give it the next type in PACKED_TYPES.  */
6403           actual_parm = copy_node (actual_parm);
6404           TREE_TYPE (actual_parm) = 
6405             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6406         }
6407
6408       if (arg != error_mark_node)
6409         arg = convert_template_argument (actual_parm, 
6410                                          arg, new_args, complain, parm_idx,
6411                                          in_decl);
6412       if (arg == error_mark_node)
6413         (*lost)++;
6414       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6415     }
6416
6417   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6418       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6419     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6420   else
6421     {
6422       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6423       TREE_TYPE (argument_pack) 
6424         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6425       TREE_CONSTANT (argument_pack) = 1;
6426     }
6427
6428   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6429 #ifdef ENABLE_CHECKING
6430   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6431                                        TREE_VEC_LENGTH (packed_args));
6432 #endif
6433   return argument_pack;
6434 }
6435
6436 /* Returns true if the template argument vector ARGS contains
6437    any pack expansions, false otherwise.  */
6438
6439 static bool
6440 any_pack_expanson_args_p (tree args)
6441 {
6442   int i;
6443   if (args)
6444     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
6445       if (PACK_EXPANSION_P (TREE_VEC_ELT (args, i)))
6446         return true;
6447   return false;
6448 }
6449
6450 /* Convert all template arguments to their appropriate types, and
6451    return a vector containing the innermost resulting template
6452    arguments.  If any error occurs, return error_mark_node. Error and
6453    warning messages are issued under control of COMPLAIN.
6454
6455    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6456    for arguments not specified in ARGS.  Otherwise, if
6457    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6458    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6459    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6460    ARGS.  */
6461
6462 static tree
6463 coerce_template_parms (tree parms,
6464                        tree args,
6465                        tree in_decl,
6466                        tsubst_flags_t complain,
6467                        bool require_all_args,
6468                        bool use_default_args)
6469 {
6470   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6471   tree inner_args;
6472   tree new_args;
6473   tree new_inner_args;
6474   int saved_unevaluated_operand;
6475   int saved_inhibit_evaluation_warnings;
6476
6477   /* When used as a boolean value, indicates whether this is a
6478      variadic template parameter list. Since it's an int, we can also
6479      subtract it from nparms to get the number of non-variadic
6480      parameters.  */
6481   int variadic_p = 0;
6482   int post_variadic_parms = 0;
6483
6484   if (args == error_mark_node)
6485     return error_mark_node;
6486
6487   nparms = TREE_VEC_LENGTH (parms);
6488
6489   /* Determine if there are any parameter packs.  */
6490   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6491     {
6492       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6493       if (variadic_p)
6494         ++post_variadic_parms;
6495       if (template_parameter_pack_p (tparm))
6496         ++variadic_p;
6497     }
6498
6499   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6500   /* If there are no parameters that follow a parameter pack, we need to
6501      expand any argument packs so that we can deduce a parameter pack from
6502      some non-packed args followed by an argument pack, as in variadic85.C.
6503      If there are such parameters, we need to leave argument packs intact
6504      so the arguments are assigned properly.  This can happen when dealing
6505      with a nested class inside a partial specialization of a class
6506      template, as in variadic92.C, or when deducing a template parameter pack
6507      from a sub-declarator, as in variadic114.C.  */
6508   if (!post_variadic_parms)
6509     inner_args = expand_template_argument_pack (inner_args);
6510
6511   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6512   if ((nargs > nparms && !variadic_p)
6513       || (nargs < nparms - variadic_p
6514           && require_all_args
6515           && !any_pack_expanson_args_p (inner_args)
6516           && (!use_default_args
6517               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6518                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6519     {
6520       if (complain & tf_error)
6521         {
6522           if (variadic_p)
6523             {
6524               nparms -= variadic_p;
6525               error ("wrong number of template arguments "
6526                      "(%d, should be %d or more)", nargs, nparms);
6527             }
6528           else
6529              error ("wrong number of template arguments "
6530                     "(%d, should be %d)", nargs, nparms);
6531
6532           if (in_decl)
6533             error ("provided for %q+D", in_decl);
6534         }
6535
6536       return error_mark_node;
6537     }
6538
6539   /* We need to evaluate the template arguments, even though this
6540      template-id may be nested within a "sizeof".  */
6541   saved_unevaluated_operand = cp_unevaluated_operand;
6542   cp_unevaluated_operand = 0;
6543   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6544   c_inhibit_evaluation_warnings = 0;
6545   new_inner_args = make_tree_vec (nparms);
6546   new_args = add_outermost_template_args (args, new_inner_args);
6547   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6548     {
6549       tree arg;
6550       tree parm;
6551
6552       /* Get the Ith template parameter.  */
6553       parm = TREE_VEC_ELT (parms, parm_idx);
6554  
6555       if (parm == error_mark_node)
6556       {
6557         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6558         continue;
6559       }
6560
6561       /* Calculate the next argument.  */
6562       if (arg_idx < nargs)
6563         arg = TREE_VEC_ELT (inner_args, arg_idx);
6564       else
6565         arg = NULL_TREE;
6566
6567       if (template_parameter_pack_p (TREE_VALUE (parm))
6568           && !(arg && ARGUMENT_PACK_P (arg)))
6569         {
6570           /* All remaining arguments will be placed in the
6571              template parameter pack PARM.  */
6572           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6573                                                 inner_args, arg_idx,
6574                                                 new_args, &lost,
6575                                                 in_decl, complain);
6576
6577           /* Store this argument.  */
6578           if (arg == error_mark_node)
6579             lost++;
6580           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6581
6582           /* We are done with all of the arguments.  */
6583           arg_idx = nargs;
6584           
6585           continue;
6586         }
6587       else if (arg)
6588         {
6589           if (PACK_EXPANSION_P (arg))
6590             {
6591               /* We don't know how many args we have yet, just
6592                  use the unconverted ones for now.  */
6593               new_inner_args = inner_args;
6594               break;
6595             }
6596         }
6597       else if (require_all_args)
6598         {
6599           /* There must be a default arg in this case.  */
6600           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6601                                      complain, in_decl);
6602           /* The position of the first default template argument,
6603              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6604              Record that.  */
6605           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6606             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6607         }
6608       else
6609         break;
6610
6611       if (arg == error_mark_node)
6612         {
6613           if (complain & tf_error)
6614             error ("template argument %d is invalid", arg_idx + 1);
6615         }
6616       else if (!arg)
6617         /* This only occurs if there was an error in the template
6618            parameter list itself (which we would already have
6619            reported) that we are trying to recover from, e.g., a class
6620            template with a parameter list such as
6621            template<typename..., typename>.  */
6622         ++lost;
6623       else
6624         arg = convert_template_argument (TREE_VALUE (parm),
6625                                          arg, new_args, complain, 
6626                                          parm_idx, in_decl);
6627
6628       if (arg == error_mark_node)
6629         lost++;
6630       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6631     }
6632   cp_unevaluated_operand = saved_unevaluated_operand;
6633   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6634
6635   if (lost)
6636     return error_mark_node;
6637
6638 #ifdef ENABLE_CHECKING
6639   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6640     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6641                                          TREE_VEC_LENGTH (new_inner_args));
6642 #endif
6643
6644   return new_inner_args;
6645 }
6646
6647 /* Returns 1 if template args OT and NT are equivalent.  */
6648
6649 static int
6650 template_args_equal (tree ot, tree nt)
6651 {
6652   if (nt == ot)
6653     return 1;
6654   if (nt == NULL_TREE || ot == NULL_TREE)
6655     return false;
6656
6657   if (TREE_CODE (nt) == TREE_VEC)
6658     /* For member templates */
6659     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6660   else if (PACK_EXPANSION_P (ot))
6661     return (PACK_EXPANSION_P (nt)
6662             && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6663                                     PACK_EXPANSION_PATTERN (nt))
6664             && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
6665                                     PACK_EXPANSION_EXTRA_ARGS (nt)));
6666   else if (ARGUMENT_PACK_P (ot))
6667     {
6668       int i, len;
6669       tree opack, npack;
6670
6671       if (!ARGUMENT_PACK_P (nt))
6672         return 0;
6673
6674       opack = ARGUMENT_PACK_ARGS (ot);
6675       npack = ARGUMENT_PACK_ARGS (nt);
6676       len = TREE_VEC_LENGTH (opack);
6677       if (TREE_VEC_LENGTH (npack) != len)
6678         return 0;
6679       for (i = 0; i < len; ++i)
6680         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6681                                   TREE_VEC_ELT (npack, i)))
6682           return 0;
6683       return 1;
6684     }
6685   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6686     {
6687       /* We get here probably because we are in the middle of substituting
6688          into the pattern of a pack expansion. In that case the
6689          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6690          interested in. So we want to use the initial pack argument for
6691          the comparison.  */
6692       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6693       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6694         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6695       return template_args_equal (ot, nt);
6696     }
6697   else if (TYPE_P (nt))
6698     return TYPE_P (ot) && same_type_p (ot, nt);
6699   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6700     return 0;
6701   else
6702     return cp_tree_equal (ot, nt);
6703 }
6704
6705 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6706    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6707    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6708
6709 static int
6710 comp_template_args_with_info (tree oldargs, tree newargs,
6711                               tree *oldarg_ptr, tree *newarg_ptr)
6712 {
6713   int i;
6714
6715   if (oldargs == newargs)
6716     return 1;
6717
6718   if (!oldargs || !newargs)
6719     return 0;
6720
6721   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6722     return 0;
6723
6724   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6725     {
6726       tree nt = TREE_VEC_ELT (newargs, i);
6727       tree ot = TREE_VEC_ELT (oldargs, i);
6728
6729       if (! template_args_equal (ot, nt))
6730         {
6731           if (oldarg_ptr != NULL)
6732             *oldarg_ptr = ot;
6733           if (newarg_ptr != NULL)
6734             *newarg_ptr = nt;
6735           return 0;
6736         }
6737     }
6738   return 1;
6739 }
6740
6741 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6742    of template arguments.  Returns 0 otherwise.  */
6743
6744 int
6745 comp_template_args (tree oldargs, tree newargs)
6746 {
6747   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6748 }
6749
6750 static void
6751 add_pending_template (tree d)
6752 {
6753   tree ti = (TYPE_P (d)
6754              ? CLASSTYPE_TEMPLATE_INFO (d)
6755              : DECL_TEMPLATE_INFO (d));
6756   struct pending_template *pt;
6757   int level;
6758
6759   if (TI_PENDING_TEMPLATE_FLAG (ti))
6760     return;
6761
6762   /* We are called both from instantiate_decl, where we've already had a
6763      tinst_level pushed, and instantiate_template, where we haven't.
6764      Compensate.  */
6765   level = !current_tinst_level || current_tinst_level->decl != d;
6766
6767   if (level)
6768     push_tinst_level (d);
6769
6770   pt = ggc_alloc_pending_template ();
6771   pt->next = NULL;
6772   pt->tinst = current_tinst_level;
6773   if (last_pending_template)
6774     last_pending_template->next = pt;
6775   else
6776     pending_templates = pt;
6777
6778   last_pending_template = pt;
6779
6780   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6781
6782   if (level)
6783     pop_tinst_level ();
6784 }
6785
6786
6787 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6788    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6789    documentation for TEMPLATE_ID_EXPR.  */
6790
6791 tree
6792 lookup_template_function (tree fns, tree arglist)
6793 {
6794   tree type;
6795
6796   if (fns == error_mark_node || arglist == error_mark_node)
6797     return error_mark_node;
6798
6799   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6800
6801   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6802     {
6803       error ("%q#D is not a function template", fns);
6804       return error_mark_node;
6805     }
6806
6807   if (BASELINK_P (fns))
6808     {
6809       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6810                                          unknown_type_node,
6811                                          BASELINK_FUNCTIONS (fns),
6812                                          arglist);
6813       return fns;
6814     }
6815
6816   type = TREE_TYPE (fns);
6817   if (TREE_CODE (fns) == OVERLOAD || !type)
6818     type = unknown_type_node;
6819
6820   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6821 }
6822
6823 /* Within the scope of a template class S<T>, the name S gets bound
6824    (in build_self_reference) to a TYPE_DECL for the class, not a
6825    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6826    or one of its enclosing classes, and that type is a template,
6827    return the associated TEMPLATE_DECL.  Otherwise, the original
6828    DECL is returned.
6829
6830    Also handle the case when DECL is a TREE_LIST of ambiguous
6831    injected-class-names from different bases.  */
6832
6833 tree
6834 maybe_get_template_decl_from_type_decl (tree decl)
6835 {
6836   if (decl == NULL_TREE)
6837     return decl;
6838
6839   /* DR 176: A lookup that finds an injected-class-name (10.2
6840      [class.member.lookup]) can result in an ambiguity in certain cases
6841      (for example, if it is found in more than one base class). If all of
6842      the injected-class-names that are found refer to specializations of
6843      the same class template, and if the name is followed by a
6844      template-argument-list, the reference refers to the class template
6845      itself and not a specialization thereof, and is not ambiguous.  */
6846   if (TREE_CODE (decl) == TREE_LIST)
6847     {
6848       tree t, tmpl = NULL_TREE;
6849       for (t = decl; t; t = TREE_CHAIN (t))
6850         {
6851           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6852           if (!tmpl)
6853             tmpl = elt;
6854           else if (tmpl != elt)
6855             break;
6856         }
6857       if (tmpl && t == NULL_TREE)
6858         return tmpl;
6859       else
6860         return decl;
6861     }
6862
6863   return (decl != NULL_TREE
6864           && DECL_SELF_REFERENCE_P (decl)
6865           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6866     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6867 }
6868
6869 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6870    parameters, find the desired type.
6871
6872    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6873
6874    IN_DECL, if non-NULL, is the template declaration we are trying to
6875    instantiate.
6876
6877    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6878    the class we are looking up.
6879
6880    Issue error and warning messages under control of COMPLAIN.
6881
6882    If the template class is really a local class in a template
6883    function, then the FUNCTION_CONTEXT is the function in which it is
6884    being instantiated.
6885
6886    ??? Note that this function is currently called *twice* for each
6887    template-id: the first time from the parser, while creating the
6888    incomplete type (finish_template_type), and the second type during the
6889    real instantiation (instantiate_template_class). This is surely something
6890    that we want to avoid. It also causes some problems with argument
6891    coercion (see convert_nontype_argument for more information on this).  */
6892
6893 static tree
6894 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
6895                          int entering_scope, tsubst_flags_t complain)
6896 {
6897   tree templ = NULL_TREE, parmlist;
6898   tree t;
6899   void **slot;
6900   spec_entry *entry;
6901   spec_entry elt;
6902   hashval_t hash;
6903
6904   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6905     {
6906       tree value = innermost_non_namespace_value (d1);
6907       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6908         templ = value;
6909       else
6910         {
6911           if (context)
6912             push_decl_namespace (context);
6913           templ = lookup_name (d1);
6914           templ = maybe_get_template_decl_from_type_decl (templ);
6915           if (context)
6916             pop_decl_namespace ();
6917         }
6918       if (templ)
6919         context = DECL_CONTEXT (templ);
6920     }
6921   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6922     {
6923       tree type = TREE_TYPE (d1);
6924
6925       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6926          an implicit typename for the second A.  Deal with it.  */
6927       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6928         type = TREE_TYPE (type);
6929
6930       if (CLASSTYPE_TEMPLATE_INFO (type))
6931         {
6932           templ = CLASSTYPE_TI_TEMPLATE (type);
6933           d1 = DECL_NAME (templ);
6934         }
6935     }
6936   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6937            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6938     {
6939       templ = TYPE_TI_TEMPLATE (d1);
6940       d1 = DECL_NAME (templ);
6941     }
6942   else if (TREE_CODE (d1) == TEMPLATE_DECL
6943            && DECL_TEMPLATE_RESULT (d1)
6944            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6945     {
6946       templ = d1;
6947       d1 = DECL_NAME (templ);
6948       context = DECL_CONTEXT (templ);
6949     }
6950
6951   /* Issue an error message if we didn't find a template.  */
6952   if (! templ)
6953     {
6954       if (complain & tf_error)
6955         error ("%qT is not a template", d1);
6956       return error_mark_node;
6957     }
6958
6959   if (TREE_CODE (templ) != TEMPLATE_DECL
6960          /* Make sure it's a user visible template, if it was named by
6961             the user.  */
6962       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6963           && !PRIMARY_TEMPLATE_P (templ)))
6964     {
6965       if (complain & tf_error)
6966         {
6967           error ("non-template type %qT used as a template", d1);
6968           if (in_decl)
6969             error ("for template declaration %q+D", in_decl);
6970         }
6971       return error_mark_node;
6972     }
6973
6974   complain &= ~tf_user;
6975
6976   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6977     {
6978       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6979          template arguments */
6980
6981       tree parm;
6982       tree arglist2;
6983       tree outer;
6984
6985       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6986
6987       /* Consider an example where a template template parameter declared as
6988
6989            template <class T, class U = std::allocator<T> > class TT
6990
6991          The template parameter level of T and U are one level larger than
6992          of TT.  To proper process the default argument of U, say when an
6993          instantiation `TT<int>' is seen, we need to build the full
6994          arguments containing {int} as the innermost level.  Outer levels,
6995          available when not appearing as default template argument, can be
6996          obtained from the arguments of the enclosing template.
6997
6998          Suppose that TT is later substituted with std::vector.  The above
6999          instantiation is `TT<int, std::allocator<T> >' with TT at
7000          level 1, and T at level 2, while the template arguments at level 1
7001          becomes {std::vector} and the inner level 2 is {int}.  */
7002
7003       outer = DECL_CONTEXT (templ);
7004       if (outer)
7005         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7006       else if (current_template_parms)
7007         /* This is an argument of the current template, so we haven't set
7008            DECL_CONTEXT yet.  */
7009         outer = current_template_args ();
7010
7011       if (outer)
7012         arglist = add_to_template_args (outer, arglist);
7013
7014       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7015                                         complain,
7016                                         /*require_all_args=*/true,
7017                                         /*use_default_args=*/true);
7018       if (arglist2 == error_mark_node
7019           || (!uses_template_parms (arglist2)
7020               && check_instantiated_args (templ, arglist2, complain)))
7021         return error_mark_node;
7022
7023       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7024       return parm;
7025     }
7026   else
7027     {
7028       tree template_type = TREE_TYPE (templ);
7029       tree gen_tmpl;
7030       tree type_decl;
7031       tree found = NULL_TREE;
7032       int arg_depth;
7033       int parm_depth;
7034       int is_dependent_type;
7035       int use_partial_inst_tmpl = false;
7036
7037       if (template_type == error_mark_node)
7038         /* An error occured while building the template TEMPL, and a
7039            diagnostic has most certainly been emitted for that
7040            already.  Let's propagate that error.  */
7041         return error_mark_node;
7042
7043       gen_tmpl = most_general_template (templ);
7044       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7045       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7046       arg_depth = TMPL_ARGS_DEPTH (arglist);
7047
7048       if (arg_depth == 1 && parm_depth > 1)
7049         {
7050           /* We've been given an incomplete set of template arguments.
7051              For example, given:
7052
7053                template <class T> struct S1 {
7054                  template <class U> struct S2 {};
7055                  template <class U> struct S2<U*> {};
7056                 };
7057
7058              we will be called with an ARGLIST of `U*', but the
7059              TEMPLATE will be `template <class T> template
7060              <class U> struct S1<T>::S2'.  We must fill in the missing
7061              arguments.  */
7062           arglist
7063             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7064                                            arglist);
7065           arg_depth = TMPL_ARGS_DEPTH (arglist);
7066         }
7067
7068       /* Now we should have enough arguments.  */
7069       gcc_assert (parm_depth == arg_depth);
7070
7071       /* From here on, we're only interested in the most general
7072          template.  */
7073
7074       /* Calculate the BOUND_ARGS.  These will be the args that are
7075          actually tsubst'd into the definition to create the
7076          instantiation.  */
7077       if (parm_depth > 1)
7078         {
7079           /* We have multiple levels of arguments to coerce, at once.  */
7080           int i;
7081           int saved_depth = TMPL_ARGS_DEPTH (arglist);
7082
7083           tree bound_args = make_tree_vec (parm_depth);
7084
7085           for (i = saved_depth,
7086                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
7087                i > 0 && t != NULL_TREE;
7088                --i, t = TREE_CHAIN (t))
7089             {
7090               tree a;
7091               if (i == saved_depth)
7092                 a = coerce_template_parms (TREE_VALUE (t),
7093                                            arglist, gen_tmpl,
7094                                            complain,
7095                                            /*require_all_args=*/true,
7096                                            /*use_default_args=*/true);
7097               else
7098                 /* Outer levels should have already been coerced.  */
7099                 a = TMPL_ARGS_LEVEL (arglist, i);
7100
7101               /* Don't process further if one of the levels fails.  */
7102               if (a == error_mark_node)
7103                 {
7104                   /* Restore the ARGLIST to its full size.  */
7105                   TREE_VEC_LENGTH (arglist) = saved_depth;
7106                   return error_mark_node;
7107                 }
7108
7109               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7110
7111               /* We temporarily reduce the length of the ARGLIST so
7112                  that coerce_template_parms will see only the arguments
7113                  corresponding to the template parameters it is
7114                  examining.  */
7115               TREE_VEC_LENGTH (arglist)--;
7116             }
7117
7118           /* Restore the ARGLIST to its full size.  */
7119           TREE_VEC_LENGTH (arglist) = saved_depth;
7120
7121           arglist = bound_args;
7122         }
7123       else
7124         arglist
7125           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7126                                    INNERMOST_TEMPLATE_ARGS (arglist),
7127                                    gen_tmpl,
7128                                    complain,
7129                                    /*require_all_args=*/true,
7130                                    /*use_default_args=*/true);
7131
7132       if (arglist == error_mark_node)
7133         /* We were unable to bind the arguments.  */
7134         return error_mark_node;
7135
7136       /* In the scope of a template class, explicit references to the
7137          template class refer to the type of the template, not any
7138          instantiation of it.  For example, in:
7139
7140            template <class T> class C { void f(C<T>); }
7141
7142          the `C<T>' is just the same as `C'.  Outside of the
7143          class, however, such a reference is an instantiation.  */
7144       if ((entering_scope
7145            || !PRIMARY_TEMPLATE_P (gen_tmpl)
7146            || currently_open_class (template_type))
7147           /* comp_template_args is expensive, check it last.  */
7148           && comp_template_args (TYPE_TI_ARGS (template_type),
7149                                  arglist))
7150         return template_type;
7151
7152       /* If we already have this specialization, return it.  */
7153       elt.tmpl = gen_tmpl;
7154       elt.args = arglist;
7155       hash = hash_specialization (&elt);
7156       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7157                                                   &elt, hash);
7158
7159       if (entry)
7160         return entry->spec;
7161
7162       is_dependent_type = uses_template_parms (arglist);
7163
7164       /* If the deduced arguments are invalid, then the binding
7165          failed.  */
7166       if (!is_dependent_type
7167           && check_instantiated_args (gen_tmpl,
7168                                       INNERMOST_TEMPLATE_ARGS (arglist),
7169                                       complain))
7170         return error_mark_node;
7171
7172       if (!is_dependent_type
7173           && !PRIMARY_TEMPLATE_P (gen_tmpl)
7174           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7175           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7176         {
7177           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7178                                       DECL_NAME (gen_tmpl),
7179                                       /*tag_scope=*/ts_global);
7180           return found;
7181         }
7182
7183       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7184                         complain, in_decl);
7185       if (context == error_mark_node)
7186         return error_mark_node;
7187
7188       if (!context)
7189         context = global_namespace;
7190
7191       /* Create the type.  */
7192       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7193         {
7194           if (!is_dependent_type)
7195             {
7196               set_current_access_from_decl (TYPE_NAME (template_type));
7197               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7198                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
7199                                       arglist, complain, in_decl),
7200                               SCOPED_ENUM_P (template_type), NULL);
7201             }
7202           else
7203             {
7204               /* We don't want to call start_enum for this type, since
7205                  the values for the enumeration constants may involve
7206                  template parameters.  And, no one should be interested
7207                  in the enumeration constants for such a type.  */
7208               t = cxx_make_type (ENUMERAL_TYPE);
7209               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7210             }
7211           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7212           ENUM_FIXED_UNDERLYING_TYPE_P (t)
7213             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7214         }
7215       else if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7216         {
7217           /* The user referred to a specialization of an alias
7218             template represented by GEN_TMPL.
7219
7220             [temp.alias]/2 says:
7221
7222                 When a template-id refers to the specialization of an
7223                 alias template, it is equivalent to the associated
7224                 type obtained by substitution of its
7225                 template-arguments for the template-parameters in the
7226                 type-id of the alias template.  */
7227
7228           t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
7229           /* Note that the call above (by indirectly calling
7230              register_specialization in tsubst_decl) registers the
7231              TYPE_DECL representing the specialization of the alias
7232              template.  So next time someone substitutes ARGLIST for
7233              the template parms into the alias template (GEN_TMPL),
7234              she'll get that TYPE_DECL back.  */
7235
7236           if (t == error_mark_node)
7237             return t;
7238         }
7239       else if (CLASS_TYPE_P (template_type))
7240         {
7241           t = make_class_type (TREE_CODE (template_type));
7242           CLASSTYPE_DECLARED_CLASS (t)
7243             = CLASSTYPE_DECLARED_CLASS (template_type);
7244           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7245           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7246
7247           /* A local class.  Make sure the decl gets registered properly.  */
7248           if (context == current_function_decl)
7249             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_global);
7250
7251           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7252             /* This instantiation is another name for the primary
7253                template type. Set the TYPE_CANONICAL field
7254                appropriately. */
7255             TYPE_CANONICAL (t) = template_type;
7256           else if (any_template_arguments_need_structural_equality_p (arglist))
7257             /* Some of the template arguments require structural
7258                equality testing, so this template class requires
7259                structural equality testing. */
7260             SET_TYPE_STRUCTURAL_EQUALITY (t);
7261         }
7262       else
7263         gcc_unreachable ();
7264
7265       /* If we called start_enum or pushtag above, this information
7266          will already be set up.  */
7267       if (!TYPE_NAME (t))
7268         {
7269           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7270
7271           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7272           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7273           DECL_SOURCE_LOCATION (type_decl)
7274             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7275         }
7276       else
7277         type_decl = TYPE_NAME (t);
7278
7279       if (CLASS_TYPE_P (template_type))
7280         {
7281           TREE_PRIVATE (type_decl)
7282             = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7283           TREE_PROTECTED (type_decl)
7284             = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7285           if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7286             {
7287               DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7288               DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7289             }
7290         }
7291
7292       /* Let's consider the explicit specialization of a member
7293          of a class template specialization that is implicitely instantiated,
7294          e.g.:
7295              template<class T>
7296              struct S
7297              {
7298                template<class U> struct M {}; //#0
7299              };
7300
7301              template<>
7302              template<>
7303              struct S<int>::M<char> //#1
7304              {
7305                int i;
7306              };
7307         [temp.expl.spec]/4 says this is valid.
7308
7309         In this case, when we write:
7310         S<int>::M<char> m;
7311
7312         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7313         the one of #0.
7314
7315         When we encounter #1, we want to store the partial instantiation
7316         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7317
7318         For all cases other than this "explicit specialization of member of a
7319         class template", we just want to store the most general template into
7320         the CLASSTYPE_TI_TEMPLATE of M.
7321
7322         This case of "explicit specialization of member of a class template"
7323         only happens when:
7324         1/ the enclosing class is an instantiation of, and therefore not
7325         the same as, the context of the most general template, and
7326         2/ we aren't looking at the partial instantiation itself, i.e.
7327         the innermost arguments are not the same as the innermost parms of
7328         the most general template.
7329
7330         So it's only when 1/ and 2/ happens that we want to use the partial
7331         instantiation of the member template in lieu of its most general
7332         template.  */
7333
7334       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7335           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7336           /* the enclosing class must be an instantiation...  */
7337           && CLASS_TYPE_P (context)
7338           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7339         {
7340           tree partial_inst_args;
7341           TREE_VEC_LENGTH (arglist)--;
7342           ++processing_template_decl;
7343           partial_inst_args =
7344             tsubst (INNERMOST_TEMPLATE_ARGS
7345                         (TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7346                     arglist, complain, NULL_TREE);
7347           --processing_template_decl;
7348           TREE_VEC_LENGTH (arglist)++;
7349           use_partial_inst_tmpl =
7350             /*...and we must not be looking at the partial instantiation
7351              itself. */
7352             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7353                                  partial_inst_args);
7354         }
7355
7356       if (!use_partial_inst_tmpl)
7357         /* This case is easy; there are no member templates involved.  */
7358         found = gen_tmpl;
7359       else
7360         {
7361           /* This is a full instantiation of a member template.  Find
7362              the partial instantiation of which this is an instance.  */
7363
7364           /* Temporarily reduce by one the number of levels in the ARGLIST
7365              so as to avoid comparing the last set of arguments.  */
7366           TREE_VEC_LENGTH (arglist)--;
7367           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7368           TREE_VEC_LENGTH (arglist)++;
7369           /* FOUND is either a proper class type, or an alias
7370              template specialization.  In the later case, it's a
7371              TYPE_DECL, resulting from the substituting of arguments
7372              for parameters in the TYPE_DECL of the alias template
7373              done earlier.  So be careful while getting the template
7374              of FOUND.  */
7375           found = TREE_CODE (found) == TYPE_DECL
7376             ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
7377             : CLASSTYPE_TI_TEMPLATE (found);
7378         }
7379
7380       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7381
7382       elt.spec = t;
7383       slot = htab_find_slot_with_hash (type_specializations,
7384                                        &elt, hash, INSERT);
7385       entry = ggc_alloc_spec_entry ();
7386       *entry = elt;
7387       *slot = entry;
7388
7389       /* Note this use of the partial instantiation so we can check it
7390          later in maybe_process_partial_specialization.  */
7391       DECL_TEMPLATE_INSTANTIATIONS (templ)
7392         = tree_cons (arglist, t,
7393                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7394
7395       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7396         /* Now that the type has been registered on the instantiations
7397            list, we set up the enumerators.  Because the enumeration
7398            constants may involve the enumeration type itself, we make
7399            sure to register the type first, and then create the
7400            constants.  That way, doing tsubst_expr for the enumeration
7401            constants won't result in recursive calls here; we'll find
7402            the instantiation and exit above.  */
7403         tsubst_enum (template_type, t, arglist);
7404
7405       if (CLASS_TYPE_P (template_type) && is_dependent_type)
7406         /* If the type makes use of template parameters, the
7407            code that generates debugging information will crash.  */
7408         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7409
7410       /* Possibly limit visibility based on template args.  */
7411       TREE_PUBLIC (type_decl) = 1;
7412       determine_visibility (type_decl);
7413
7414       return t;
7415     }
7416 }
7417
7418 /* Wrapper for lookup_template_class_1.  */
7419
7420 tree
7421 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7422                        int entering_scope, tsubst_flags_t complain)
7423 {
7424   tree ret;
7425   timevar_push (TV_TEMPLATE_INST);
7426   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7427                                  entering_scope, complain);
7428   timevar_pop (TV_TEMPLATE_INST);
7429   return ret;
7430 }
7431 \f
7432 struct pair_fn_data
7433 {
7434   tree_fn_t fn;
7435   void *data;
7436   /* True when we should also visit template parameters that occur in
7437      non-deduced contexts.  */
7438   bool include_nondeduced_p;
7439   struct pointer_set_t *visited;
7440 };
7441
7442 /* Called from for_each_template_parm via walk_tree.  */
7443
7444 static tree
7445 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7446 {
7447   tree t = *tp;
7448   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7449   tree_fn_t fn = pfd->fn;
7450   void *data = pfd->data;
7451
7452   if (TYPE_P (t)
7453       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7454       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7455                                  pfd->include_nondeduced_p))
7456     return error_mark_node;
7457
7458   switch (TREE_CODE (t))
7459     {
7460     case RECORD_TYPE:
7461       if (TYPE_PTRMEMFUNC_P (t))
7462         break;
7463       /* Fall through.  */
7464
7465     case UNION_TYPE:
7466     case ENUMERAL_TYPE:
7467       if (!TYPE_TEMPLATE_INFO (t))
7468         *walk_subtrees = 0;
7469       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7470                                        fn, data, pfd->visited, 
7471                                        pfd->include_nondeduced_p))
7472         return error_mark_node;
7473       break;
7474
7475     case INTEGER_TYPE:
7476       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7477                                   fn, data, pfd->visited, 
7478                                   pfd->include_nondeduced_p)
7479           || for_each_template_parm (TYPE_MAX_VALUE (t),
7480                                      fn, data, pfd->visited,
7481                                      pfd->include_nondeduced_p))
7482         return error_mark_node;
7483       break;
7484
7485     case METHOD_TYPE:
7486       /* Since we're not going to walk subtrees, we have to do this
7487          explicitly here.  */
7488       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7489                                   pfd->visited, pfd->include_nondeduced_p))
7490         return error_mark_node;
7491       /* Fall through.  */
7492
7493     case FUNCTION_TYPE:
7494       /* Check the return type.  */
7495       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7496                                   pfd->include_nondeduced_p))
7497         return error_mark_node;
7498
7499       /* Check the parameter types.  Since default arguments are not
7500          instantiated until they are needed, the TYPE_ARG_TYPES may
7501          contain expressions that involve template parameters.  But,
7502          no-one should be looking at them yet.  And, once they're
7503          instantiated, they don't contain template parameters, so
7504          there's no point in looking at them then, either.  */
7505       {
7506         tree parm;
7507
7508         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7509           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7510                                       pfd->visited, pfd->include_nondeduced_p))
7511             return error_mark_node;
7512
7513         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7514            want walk_tree walking into them itself.  */
7515         *walk_subtrees = 0;
7516       }
7517       break;
7518
7519     case TYPEOF_TYPE:
7520     case UNDERLYING_TYPE:
7521       if (pfd->include_nondeduced_p
7522           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7523                                      pfd->visited, 
7524                                      pfd->include_nondeduced_p))
7525         return error_mark_node;
7526       break;
7527
7528     case FUNCTION_DECL:
7529     case VAR_DECL:
7530       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7531           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7532                                      pfd->visited, pfd->include_nondeduced_p))
7533         return error_mark_node;
7534       /* Fall through.  */
7535
7536     case PARM_DECL:
7537     case CONST_DECL:
7538       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7539           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7540                                      pfd->visited, pfd->include_nondeduced_p))
7541         return error_mark_node;
7542       if (DECL_CONTEXT (t)
7543           && pfd->include_nondeduced_p
7544           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7545                                      pfd->visited, pfd->include_nondeduced_p))
7546         return error_mark_node;
7547       break;
7548
7549     case BOUND_TEMPLATE_TEMPLATE_PARM:
7550       /* Record template parameters such as `T' inside `TT<T>'.  */
7551       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7552                                   pfd->include_nondeduced_p))
7553         return error_mark_node;
7554       /* Fall through.  */
7555
7556     case TEMPLATE_TEMPLATE_PARM:
7557     case TEMPLATE_TYPE_PARM:
7558     case TEMPLATE_PARM_INDEX:
7559       if (fn && (*fn)(t, data))
7560         return error_mark_node;
7561       else if (!fn)
7562         return error_mark_node;
7563       break;
7564
7565     case TEMPLATE_DECL:
7566       /* A template template parameter is encountered.  */
7567       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7568           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7569                                      pfd->include_nondeduced_p))
7570         return error_mark_node;
7571
7572       /* Already substituted template template parameter */
7573       *walk_subtrees = 0;
7574       break;
7575
7576     case TYPENAME_TYPE:
7577       if (!fn
7578           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7579                                      data, pfd->visited, 
7580                                      pfd->include_nondeduced_p))
7581         return error_mark_node;
7582       break;
7583
7584     case CONSTRUCTOR:
7585       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7586           && pfd->include_nondeduced_p
7587           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7588                                      (TREE_TYPE (t)), fn, data,
7589                                      pfd->visited, pfd->include_nondeduced_p))
7590         return error_mark_node;
7591       break;
7592
7593     case INDIRECT_REF:
7594     case COMPONENT_REF:
7595       /* If there's no type, then this thing must be some expression
7596          involving template parameters.  */
7597       if (!fn && !TREE_TYPE (t))
7598         return error_mark_node;
7599       break;
7600
7601     case MODOP_EXPR:
7602     case CAST_EXPR:
7603     case IMPLICIT_CONV_EXPR:
7604     case REINTERPRET_CAST_EXPR:
7605     case CONST_CAST_EXPR:
7606     case STATIC_CAST_EXPR:
7607     case DYNAMIC_CAST_EXPR:
7608     case ARROW_EXPR:
7609     case DOTSTAR_EXPR:
7610     case TYPEID_EXPR:
7611     case PSEUDO_DTOR_EXPR:
7612       if (!fn)
7613         return error_mark_node;
7614       break;
7615
7616     default:
7617       break;
7618     }
7619
7620   /* We didn't find any template parameters we liked.  */
7621   return NULL_TREE;
7622 }
7623
7624 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7625    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7626    call FN with the parameter and the DATA.
7627    If FN returns nonzero, the iteration is terminated, and
7628    for_each_template_parm returns 1.  Otherwise, the iteration
7629    continues.  If FN never returns a nonzero value, the value
7630    returned by for_each_template_parm is 0.  If FN is NULL, it is
7631    considered to be the function which always returns 1.
7632
7633    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7634    parameters that occur in non-deduced contexts.  When false, only
7635    visits those template parameters that can be deduced.  */
7636
7637 static int
7638 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7639                         struct pointer_set_t *visited,
7640                         bool include_nondeduced_p)
7641 {
7642   struct pair_fn_data pfd;
7643   int result;
7644
7645   /* Set up.  */
7646   pfd.fn = fn;
7647   pfd.data = data;
7648   pfd.include_nondeduced_p = include_nondeduced_p;
7649
7650   /* Walk the tree.  (Conceptually, we would like to walk without
7651      duplicates, but for_each_template_parm_r recursively calls
7652      for_each_template_parm, so we would need to reorganize a fair
7653      bit to use walk_tree_without_duplicates, so we keep our own
7654      visited list.)  */
7655   if (visited)
7656     pfd.visited = visited;
7657   else
7658     pfd.visited = pointer_set_create ();
7659   result = cp_walk_tree (&t,
7660                          for_each_template_parm_r,
7661                          &pfd,
7662                          pfd.visited) != NULL_TREE;
7663
7664   /* Clean up.  */
7665   if (!visited)
7666     {
7667       pointer_set_destroy (pfd.visited);
7668       pfd.visited = 0;
7669     }
7670
7671   return result;
7672 }
7673
7674 /* Returns true if T depends on any template parameter.  */
7675
7676 int
7677 uses_template_parms (tree t)
7678 {
7679   bool dependent_p;
7680   int saved_processing_template_decl;
7681
7682   saved_processing_template_decl = processing_template_decl;
7683   if (!saved_processing_template_decl)
7684     processing_template_decl = 1;
7685   if (TYPE_P (t))
7686     dependent_p = dependent_type_p (t);
7687   else if (TREE_CODE (t) == TREE_VEC)
7688     dependent_p = any_dependent_template_arguments_p (t);
7689   else if (TREE_CODE (t) == TREE_LIST)
7690     dependent_p = (uses_template_parms (TREE_VALUE (t))
7691                    || uses_template_parms (TREE_CHAIN (t)));
7692   else if (TREE_CODE (t) == TYPE_DECL)
7693     dependent_p = dependent_type_p (TREE_TYPE (t));
7694   else if (DECL_P (t)
7695            || EXPR_P (t)
7696            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7697            || TREE_CODE (t) == OVERLOAD
7698            || BASELINK_P (t)
7699            || TREE_CODE (t) == IDENTIFIER_NODE
7700            || TREE_CODE (t) == TRAIT_EXPR
7701            || TREE_CODE (t) == CONSTRUCTOR
7702            || CONSTANT_CLASS_P (t))
7703     dependent_p = (type_dependent_expression_p (t)
7704                    || value_dependent_expression_p (t));
7705   else
7706     {
7707       gcc_assert (t == error_mark_node);
7708       dependent_p = false;
7709     }
7710
7711   processing_template_decl = saved_processing_template_decl;
7712
7713   return dependent_p;
7714 }
7715
7716 /* Returns true if T depends on any template parameter with level LEVEL.  */
7717
7718 int
7719 uses_template_parms_level (tree t, int level)
7720 {
7721   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7722                                  /*include_nondeduced_p=*/true);
7723 }
7724
7725 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7726    ill-formed translation unit, i.e. a variable or function that isn't
7727    usable in a constant expression.  */
7728
7729 static inline bool
7730 neglectable_inst_p (tree d)
7731 {
7732   return (DECL_P (d)
7733           && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7734                : decl_maybe_constant_var_p (d)));
7735 }
7736
7737 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7738    neglectable and instantiated from within an erroneous instantiation.  */
7739
7740 static bool
7741 limit_bad_template_recursion (tree decl)
7742 {
7743   struct tinst_level *lev = current_tinst_level;
7744   int errs = errorcount + sorrycount;
7745   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7746     return false;
7747
7748   for (; lev; lev = lev->next)
7749     if (neglectable_inst_p (lev->decl))
7750       break;
7751
7752   return (lev && errs > lev->errors);
7753 }
7754
7755 static int tinst_depth;
7756 extern int max_tinst_depth;
7757 #ifdef GATHER_STATISTICS
7758 int depth_reached;
7759 #endif
7760 static GTY(()) struct tinst_level *last_error_tinst_level;
7761
7762 /* We're starting to instantiate D; record the template instantiation context
7763    for diagnostics and to restore it later.  */
7764
7765 int
7766 push_tinst_level (tree d)
7767 {
7768   struct tinst_level *new_level;
7769
7770   if (tinst_depth >= max_tinst_depth)
7771     {
7772       last_error_tinst_level = current_tinst_level;
7773       if (TREE_CODE (d) == TREE_LIST)
7774         error ("template instantiation depth exceeds maximum of %d (use "
7775                "-ftemplate-depth= to increase the maximum) substituting %qS",
7776                max_tinst_depth, d);
7777       else
7778         error ("template instantiation depth exceeds maximum of %d (use "
7779                "-ftemplate-depth= to increase the maximum) instantiating %qD",
7780                max_tinst_depth, d);
7781
7782       print_instantiation_context ();
7783
7784       return 0;
7785     }
7786
7787   /* If the current instantiation caused problems, don't let it instantiate
7788      anything else.  Do allow deduction substitution and decls usable in
7789      constant expressions.  */
7790   if (limit_bad_template_recursion (d))
7791     return 0;
7792
7793   new_level = ggc_alloc_tinst_level ();
7794   new_level->decl = d;
7795   new_level->locus = input_location;
7796   new_level->errors = errorcount+sorrycount;
7797   new_level->in_system_header_p = in_system_header;
7798   new_level->next = current_tinst_level;
7799   current_tinst_level = new_level;
7800
7801   ++tinst_depth;
7802 #ifdef GATHER_STATISTICS
7803   if (tinst_depth > depth_reached)
7804     depth_reached = tinst_depth;
7805 #endif
7806
7807   return 1;
7808 }
7809
7810 /* We're done instantiating this template; return to the instantiation
7811    context.  */
7812
7813 void
7814 pop_tinst_level (void)
7815 {
7816   /* Restore the filename and line number stashed away when we started
7817      this instantiation.  */
7818   input_location = current_tinst_level->locus;
7819   current_tinst_level = current_tinst_level->next;
7820   --tinst_depth;
7821 }
7822
7823 /* We're instantiating a deferred template; restore the template
7824    instantiation context in which the instantiation was requested, which
7825    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7826
7827 static tree
7828 reopen_tinst_level (struct tinst_level *level)
7829 {
7830   struct tinst_level *t;
7831
7832   tinst_depth = 0;
7833   for (t = level; t; t = t->next)
7834     ++tinst_depth;
7835
7836   current_tinst_level = level;
7837   pop_tinst_level ();
7838   if (current_tinst_level)
7839     current_tinst_level->errors = errorcount+sorrycount;
7840   return level->decl;
7841 }
7842
7843 /* Returns the TINST_LEVEL which gives the original instantiation
7844    context.  */
7845
7846 struct tinst_level *
7847 outermost_tinst_level (void)
7848 {
7849   struct tinst_level *level = current_tinst_level;
7850   if (level)
7851     while (level->next)
7852       level = level->next;
7853   return level;
7854 }
7855
7856 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7857
7858 bool
7859 parameter_of_template_p (tree parm, tree templ)
7860 {
7861   tree parms;
7862   int i;
7863
7864   if (!parm || !templ)
7865     return false;
7866
7867   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7868   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7869
7870   parms = DECL_TEMPLATE_PARMS (templ);
7871   parms = INNERMOST_TEMPLATE_PARMS (parms);
7872
7873   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7874     {
7875       tree p = TREE_VALUE (TREE_VEC_ELT (parms, i));
7876       if (p == error_mark_node)
7877         continue;
7878
7879       if (parm == p
7880           || (DECL_INITIAL (parm)
7881               && DECL_INITIAL (parm) == DECL_INITIAL (p)))
7882         return true;
7883     }
7884
7885   return false;
7886 }
7887
7888 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7889    vector of template arguments, as for tsubst.
7890
7891    Returns an appropriate tsubst'd friend declaration.  */
7892
7893 static tree
7894 tsubst_friend_function (tree decl, tree args)
7895 {
7896   tree new_friend;
7897
7898   if (TREE_CODE (decl) == FUNCTION_DECL
7899       && DECL_TEMPLATE_INSTANTIATION (decl)
7900       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7901     /* This was a friend declared with an explicit template
7902        argument list, e.g.:
7903
7904        friend void f<>(T);
7905
7906        to indicate that f was a template instantiation, not a new
7907        function declaration.  Now, we have to figure out what
7908        instantiation of what template.  */
7909     {
7910       tree template_id, arglist, fns;
7911       tree new_args;
7912       tree tmpl;
7913       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7914
7915       /* Friend functions are looked up in the containing namespace scope.
7916          We must enter that scope, to avoid finding member functions of the
7917          current class with same name.  */
7918       push_nested_namespace (ns);
7919       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7920                          tf_warning_or_error, NULL_TREE,
7921                          /*integral_constant_expression_p=*/false);
7922       pop_nested_namespace (ns);
7923       arglist = tsubst (DECL_TI_ARGS (decl), args,
7924                         tf_warning_or_error, NULL_TREE);
7925       template_id = lookup_template_function (fns, arglist);
7926
7927       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7928       tmpl = determine_specialization (template_id, new_friend,
7929                                        &new_args,
7930                                        /*need_member_template=*/0,
7931                                        TREE_VEC_LENGTH (args),
7932                                        tsk_none);
7933       return instantiate_template (tmpl, new_args, tf_error);
7934     }
7935
7936   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7937
7938   /* The NEW_FRIEND will look like an instantiation, to the
7939      compiler, but is not an instantiation from the point of view of
7940      the language.  For example, we might have had:
7941
7942      template <class T> struct S {
7943        template <class U> friend void f(T, U);
7944      };
7945
7946      Then, in S<int>, template <class U> void f(int, U) is not an
7947      instantiation of anything.  */
7948   if (new_friend == error_mark_node)
7949     return error_mark_node;
7950
7951   DECL_USE_TEMPLATE (new_friend) = 0;
7952   if (TREE_CODE (decl) == TEMPLATE_DECL)
7953     {
7954       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7955       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7956         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7957     }
7958
7959   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7960      is not a template instantiation and should not be mangled like
7961      one.  Therefore, we forget the mangling here; we'll recompute it
7962      later if we need it.  */
7963   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7964     {
7965       SET_DECL_RTL (new_friend, NULL);
7966       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7967     }
7968
7969   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7970     {
7971       tree old_decl;
7972       tree new_friend_template_info;
7973       tree new_friend_result_template_info;
7974       tree ns;
7975       int  new_friend_is_defn;
7976
7977       /* We must save some information from NEW_FRIEND before calling
7978          duplicate decls since that function will free NEW_FRIEND if
7979          possible.  */
7980       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7981       new_friend_is_defn =
7982             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7983                            (template_for_substitution (new_friend)))
7984              != NULL_TREE);
7985       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7986         {
7987           /* This declaration is a `primary' template.  */
7988           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7989
7990           new_friend_result_template_info
7991             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7992         }
7993       else
7994         new_friend_result_template_info = NULL_TREE;
7995
7996       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7997       if (new_friend_is_defn)
7998         DECL_INITIAL (new_friend) = error_mark_node;
7999
8000       /* Inside pushdecl_namespace_level, we will push into the
8001          current namespace. However, the friend function should go
8002          into the namespace of the template.  */
8003       ns = decl_namespace_context (new_friend);
8004       push_nested_namespace (ns);
8005       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8006       pop_nested_namespace (ns);
8007
8008       if (old_decl == error_mark_node)
8009         return error_mark_node;
8010
8011       if (old_decl != new_friend)
8012         {
8013           /* This new friend declaration matched an existing
8014              declaration.  For example, given:
8015
8016                template <class T> void f(T);
8017                template <class U> class C {
8018                  template <class T> friend void f(T) {}
8019                };
8020
8021              the friend declaration actually provides the definition
8022              of `f', once C has been instantiated for some type.  So,
8023              old_decl will be the out-of-class template declaration,
8024              while new_friend is the in-class definition.
8025
8026              But, if `f' was called before this point, the
8027              instantiation of `f' will have DECL_TI_ARGS corresponding
8028              to `T' but not to `U', references to which might appear
8029              in the definition of `f'.  Previously, the most general
8030              template for an instantiation of `f' was the out-of-class
8031              version; now it is the in-class version.  Therefore, we
8032              run through all specialization of `f', adding to their
8033              DECL_TI_ARGS appropriately.  In particular, they need a
8034              new set of outer arguments, corresponding to the
8035              arguments for this class instantiation.
8036
8037              The same situation can arise with something like this:
8038
8039                friend void f(int);
8040                template <class T> class C {
8041                  friend void f(T) {}
8042                };
8043
8044              when `C<int>' is instantiated.  Now, `f(int)' is defined
8045              in the class.  */
8046
8047           if (!new_friend_is_defn)
8048             /* On the other hand, if the in-class declaration does
8049                *not* provide a definition, then we don't want to alter
8050                existing definitions.  We can just leave everything
8051                alone.  */
8052             ;
8053           else
8054             {
8055               tree new_template = TI_TEMPLATE (new_friend_template_info);
8056               tree new_args = TI_ARGS (new_friend_template_info);
8057
8058               /* Overwrite whatever template info was there before, if
8059                  any, with the new template information pertaining to
8060                  the declaration.  */
8061               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8062
8063               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8064                 {
8065                   /* We should have called reregister_specialization in
8066                      duplicate_decls.  */
8067                   gcc_assert (retrieve_specialization (new_template,
8068                                                        new_args, 0)
8069                               == old_decl);
8070
8071                   /* Instantiate it if the global has already been used.  */
8072                   if (DECL_ODR_USED (old_decl))
8073                     instantiate_decl (old_decl, /*defer_ok=*/true,
8074                                       /*expl_inst_class_mem_p=*/false);
8075                 }
8076               else
8077                 {
8078                   tree t;
8079
8080                   /* Indicate that the old function template is a partial
8081                      instantiation.  */
8082                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8083                     = new_friend_result_template_info;
8084
8085                   gcc_assert (new_template
8086                               == most_general_template (new_template));
8087                   gcc_assert (new_template != old_decl);
8088
8089                   /* Reassign any specializations already in the hash table
8090                      to the new more general template, and add the
8091                      additional template args.  */
8092                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8093                        t != NULL_TREE;
8094                        t = TREE_CHAIN (t))
8095                     {
8096                       tree spec = TREE_VALUE (t);
8097                       spec_entry elt;
8098
8099                       elt.tmpl = old_decl;
8100                       elt.args = DECL_TI_ARGS (spec);
8101                       elt.spec = NULL_TREE;
8102
8103                       htab_remove_elt (decl_specializations, &elt);
8104
8105                       DECL_TI_ARGS (spec)
8106                         = add_outermost_template_args (new_args,
8107                                                        DECL_TI_ARGS (spec));
8108
8109                       register_specialization
8110                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
8111
8112                     }
8113                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8114                 }
8115             }
8116
8117           /* The information from NEW_FRIEND has been merged into OLD_DECL
8118              by duplicate_decls.  */
8119           new_friend = old_decl;
8120         }
8121     }
8122   else
8123     {
8124       tree context = DECL_CONTEXT (new_friend);
8125       bool dependent_p;
8126
8127       /* In the code
8128            template <class T> class C {
8129              template <class U> friend void C1<U>::f (); // case 1
8130              friend void C2<T>::f ();                    // case 2
8131            };
8132          we only need to make sure CONTEXT is a complete type for
8133          case 2.  To distinguish between the two cases, we note that
8134          CONTEXT of case 1 remains dependent type after tsubst while
8135          this isn't true for case 2.  */
8136       ++processing_template_decl;
8137       dependent_p = dependent_type_p (context);
8138       --processing_template_decl;
8139
8140       if (!dependent_p
8141           && !complete_type_or_else (context, NULL_TREE))
8142         return error_mark_node;
8143
8144       if (COMPLETE_TYPE_P (context))
8145         {
8146           /* Check to see that the declaration is really present, and,
8147              possibly obtain an improved declaration.  */
8148           tree fn = check_classfn (context,
8149                                    new_friend, NULL_TREE);
8150
8151           if (fn)
8152             new_friend = fn;
8153         }
8154     }
8155
8156   return new_friend;
8157 }
8158
8159 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8160    template arguments, as for tsubst.
8161
8162    Returns an appropriate tsubst'd friend type or error_mark_node on
8163    failure.  */
8164
8165 static tree
8166 tsubst_friend_class (tree friend_tmpl, tree args)
8167 {
8168   tree friend_type;
8169   tree tmpl;
8170   tree context;
8171
8172   context = CP_DECL_CONTEXT (friend_tmpl);
8173
8174   if (context != global_namespace)
8175     {
8176       if (TREE_CODE (context) == NAMESPACE_DECL)
8177         push_nested_namespace (context);
8178       else
8179         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8180     }
8181
8182   /* Look for a class template declaration.  We look for hidden names
8183      because two friend declarations of the same template are the
8184      same.  For example, in:
8185
8186        struct A { 
8187          template <typename> friend class F;
8188        };
8189        template <typename> struct B { 
8190          template <typename> friend class F;
8191        };
8192
8193      both F templates are the same.  */
8194   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8195                            /*block_p=*/true, 0, 
8196                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
8197
8198   /* But, if we don't find one, it might be because we're in a
8199      situation like this:
8200
8201        template <class T>
8202        struct S {
8203          template <class U>
8204          friend struct S;
8205        };
8206
8207      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8208      for `S<int>', not the TEMPLATE_DECL.  */
8209   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8210     {
8211       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8212       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8213     }
8214
8215   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8216     {
8217       /* The friend template has already been declared.  Just
8218          check to see that the declarations match, and install any new
8219          default parameters.  We must tsubst the default parameters,
8220          of course.  We only need the innermost template parameters
8221          because that is all that redeclare_class_template will look
8222          at.  */
8223       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8224           > TMPL_ARGS_DEPTH (args))
8225         {
8226           tree parms;
8227           location_t saved_input_location;
8228           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8229                                          args, tf_warning_or_error);
8230
8231           saved_input_location = input_location;
8232           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8233           redeclare_class_template (TREE_TYPE (tmpl), parms);
8234           input_location = saved_input_location;
8235           
8236         }
8237
8238       friend_type = TREE_TYPE (tmpl);
8239     }
8240   else
8241     {
8242       /* The friend template has not already been declared.  In this
8243          case, the instantiation of the template class will cause the
8244          injection of this template into the global scope.  */
8245       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8246       if (tmpl == error_mark_node)
8247         return error_mark_node;
8248
8249       /* The new TMPL is not an instantiation of anything, so we
8250          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8251          the new type because that is supposed to be the corresponding
8252          template decl, i.e., TMPL.  */
8253       DECL_USE_TEMPLATE (tmpl) = 0;
8254       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8255       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8256       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8257         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8258
8259       /* Inject this template into the global scope.  */
8260       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8261     }
8262
8263   if (context != global_namespace)
8264     {
8265       if (TREE_CODE (context) == NAMESPACE_DECL)
8266         pop_nested_namespace (context);
8267       else
8268         pop_nested_class ();
8269     }
8270
8271   return friend_type;
8272 }
8273
8274 /* Returns zero if TYPE cannot be completed later due to circularity.
8275    Otherwise returns one.  */
8276
8277 static int
8278 can_complete_type_without_circularity (tree type)
8279 {
8280   if (type == NULL_TREE || type == error_mark_node)
8281     return 0;
8282   else if (COMPLETE_TYPE_P (type))
8283     return 1;
8284   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8285     return can_complete_type_without_circularity (TREE_TYPE (type));
8286   else if (CLASS_TYPE_P (type)
8287            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8288     return 0;
8289   else
8290     return 1;
8291 }
8292
8293 /* Apply any attributes which had to be deferred until instantiation
8294    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8295    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8296
8297 static void
8298 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8299                                 tree args, tsubst_flags_t complain, tree in_decl)
8300 {
8301   tree last_dep = NULL_TREE;
8302   tree t;
8303   tree *p;
8304
8305   for (t = attributes; t; t = TREE_CHAIN (t))
8306     if (ATTR_IS_DEPENDENT (t))
8307       {
8308         last_dep = t;
8309         attributes = copy_list (attributes);
8310         break;
8311       }
8312
8313   if (DECL_P (*decl_p))
8314     {
8315       if (TREE_TYPE (*decl_p) == error_mark_node)
8316         return;
8317       p = &DECL_ATTRIBUTES (*decl_p);
8318     }
8319   else
8320     p = &TYPE_ATTRIBUTES (*decl_p);
8321
8322   if (last_dep)
8323     {
8324       tree late_attrs = NULL_TREE;
8325       tree *q = &late_attrs;
8326
8327       for (*p = attributes; *p; )
8328         {
8329           t = *p;
8330           if (ATTR_IS_DEPENDENT (t))
8331             {
8332               *p = TREE_CHAIN (t);
8333               TREE_CHAIN (t) = NULL_TREE;
8334               /* If the first attribute argument is an identifier, don't
8335                  pass it through tsubst.  Attributes like mode, format,
8336                  cleanup and several target specific attributes expect it
8337                  unmodified.  */
8338               if (TREE_VALUE (t)
8339                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8340                   && TREE_VALUE (TREE_VALUE (t))
8341                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8342                       == IDENTIFIER_NODE))
8343                 {
8344                   tree chain
8345                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8346                                    in_decl,
8347                                    /*integral_constant_expression_p=*/false);
8348                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8349                     TREE_VALUE (t)
8350                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8351                                    chain);
8352                 }
8353               else
8354                 TREE_VALUE (t)
8355                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8356                                  /*integral_constant_expression_p=*/false);
8357               *q = t;
8358               q = &TREE_CHAIN (t);
8359             }
8360           else
8361             p = &TREE_CHAIN (t);
8362         }
8363
8364       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8365     }
8366 }
8367
8368 /* Perform (or defer) access check for typedefs that were referenced
8369    from within the template TMPL code.
8370    This is a subroutine of instantiate_template and instantiate_class_template.
8371    TMPL is the template to consider and TARGS is the list of arguments of
8372    that template.  */
8373
8374 static void
8375 perform_typedefs_access_check (tree tmpl, tree targs)
8376 {
8377   location_t saved_location;
8378   int i;
8379   qualified_typedef_usage_t *iter;
8380
8381   if (!tmpl
8382       || (!CLASS_TYPE_P (tmpl)
8383           && TREE_CODE (tmpl) != FUNCTION_DECL))
8384     return;
8385
8386   saved_location = input_location;
8387   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8388                     get_types_needing_access_check (tmpl),
8389                     i, iter)
8390     {
8391       tree type_decl = iter->typedef_decl;
8392       tree type_scope = iter->context;
8393
8394       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8395         continue;
8396
8397       if (uses_template_parms (type_decl))
8398         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8399       if (uses_template_parms (type_scope))
8400         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8401
8402       /* Make access check error messages point to the location
8403          of the use of the typedef.  */
8404       input_location = iter->locus;
8405       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8406                                      type_decl, type_decl);
8407     }
8408     input_location = saved_location;
8409 }
8410
8411 static tree
8412 instantiate_class_template_1 (tree type)
8413 {
8414   tree templ, args, pattern, t, member;
8415   tree typedecl;
8416   tree pbinfo;
8417   tree base_list;
8418   unsigned int saved_maximum_field_alignment;
8419   tree fn_context;
8420
8421   if (type == error_mark_node)
8422     return error_mark_node;
8423
8424   if (COMPLETE_OR_OPEN_TYPE_P (type)
8425       || uses_template_parms (type))
8426     return type;
8427
8428   /* Figure out which template is being instantiated.  */
8429   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8430   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8431
8432   /* Determine what specialization of the original template to
8433      instantiate.  */
8434   t = most_specialized_class (type, templ, tf_warning_or_error);
8435   if (t == error_mark_node)
8436     {
8437       TYPE_BEING_DEFINED (type) = 1;
8438       return error_mark_node;
8439     }
8440   else if (t)
8441     {
8442       /* This TYPE is actually an instantiation of a partial
8443          specialization.  We replace the innermost set of ARGS with
8444          the arguments appropriate for substitution.  For example,
8445          given:
8446
8447            template <class T> struct S {};
8448            template <class T> struct S<T*> {};
8449
8450          and supposing that we are instantiating S<int*>, ARGS will
8451          presently be {int*} -- but we need {int}.  */
8452       pattern = TREE_TYPE (t);
8453       args = TREE_PURPOSE (t);
8454     }
8455   else
8456     {
8457       pattern = TREE_TYPE (templ);
8458       args = CLASSTYPE_TI_ARGS (type);
8459     }
8460
8461   /* If the template we're instantiating is incomplete, then clearly
8462      there's nothing we can do.  */
8463   if (!COMPLETE_TYPE_P (pattern))
8464     return type;
8465
8466   /* If we've recursively instantiated too many templates, stop.  */
8467   if (! push_tinst_level (type))
8468     return type;
8469
8470   /* Now we're really doing the instantiation.  Mark the type as in
8471      the process of being defined.  */
8472   TYPE_BEING_DEFINED (type) = 1;
8473
8474   /* We may be in the middle of deferred access check.  Disable
8475      it now.  */
8476   push_deferring_access_checks (dk_no_deferred);
8477
8478   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
8479   if (!fn_context)
8480     push_to_top_level ();
8481   /* Use #pragma pack from the template context.  */
8482   saved_maximum_field_alignment = maximum_field_alignment;
8483   maximum_field_alignment = TYPE_PRECISION (pattern);
8484
8485   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8486
8487   /* Set the input location to the most specialized template definition.
8488      This is needed if tsubsting causes an error.  */
8489   typedecl = TYPE_MAIN_DECL (pattern);
8490   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8491     DECL_SOURCE_LOCATION (typedecl);
8492
8493   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8494   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8495   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8496   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8497   if (ANON_AGGR_TYPE_P (pattern))
8498     SET_ANON_AGGR_TYPE_P (type);
8499   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8500     {
8501       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8502       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8503       /* Adjust visibility for template arguments.  */
8504       determine_visibility (TYPE_MAIN_DECL (type));
8505     }
8506   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8507
8508   pbinfo = TYPE_BINFO (pattern);
8509
8510   /* We should never instantiate a nested class before its enclosing
8511      class; we need to look up the nested class by name before we can
8512      instantiate it, and that lookup should instantiate the enclosing
8513      class.  */
8514   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8515               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8516
8517   base_list = NULL_TREE;
8518   if (BINFO_N_BASE_BINFOS (pbinfo))
8519     {
8520       tree pbase_binfo;
8521       tree pushed_scope;
8522       int i;
8523
8524       /* We must enter the scope containing the type, as that is where
8525          the accessibility of types named in dependent bases are
8526          looked up from.  */
8527       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8528
8529       /* Substitute into each of the bases to determine the actual
8530          basetypes.  */
8531       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8532         {
8533           tree base;
8534           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8535           tree expanded_bases = NULL_TREE;
8536           int idx, len = 1;
8537
8538           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8539             {
8540               expanded_bases = 
8541                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8542                                        args, tf_error, NULL_TREE);
8543               if (expanded_bases == error_mark_node)
8544                 continue;
8545
8546               len = TREE_VEC_LENGTH (expanded_bases);
8547             }
8548
8549           for (idx = 0; idx < len; idx++)
8550             {
8551               if (expanded_bases)
8552                 /* Extract the already-expanded base class.  */
8553                 base = TREE_VEC_ELT (expanded_bases, idx);
8554               else
8555                 /* Substitute to figure out the base class.  */
8556                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8557                                NULL_TREE);
8558
8559               if (base == error_mark_node)
8560                 continue;
8561
8562               base_list = tree_cons (access, base, base_list);
8563               if (BINFO_VIRTUAL_P (pbase_binfo))
8564                 TREE_TYPE (base_list) = integer_type_node;
8565             }
8566         }
8567
8568       /* The list is now in reverse order; correct that.  */
8569       base_list = nreverse (base_list);
8570
8571       if (pushed_scope)
8572         pop_scope (pushed_scope);
8573     }
8574   /* Now call xref_basetypes to set up all the base-class
8575      information.  */
8576   xref_basetypes (type, base_list);
8577
8578   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8579                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8580                                   args, tf_error, NULL_TREE);
8581   fixup_attribute_variants (type);
8582
8583   /* Now that our base classes are set up, enter the scope of the
8584      class, so that name lookups into base classes, etc. will work
8585      correctly.  This is precisely analogous to what we do in
8586      begin_class_definition when defining an ordinary non-template
8587      class, except we also need to push the enclosing classes.  */
8588   push_nested_class (type);
8589
8590   /* Now members are processed in the order of declaration.  */
8591   for (member = CLASSTYPE_DECL_LIST (pattern);
8592        member; member = TREE_CHAIN (member))
8593     {
8594       tree t = TREE_VALUE (member);
8595
8596       if (TREE_PURPOSE (member))
8597         {
8598           if (TYPE_P (t))
8599             {
8600               /* Build new CLASSTYPE_NESTED_UTDS.  */
8601
8602               tree newtag;
8603               bool class_template_p;
8604
8605               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8606                                   && TYPE_LANG_SPECIFIC (t)
8607                                   && CLASSTYPE_IS_TEMPLATE (t));
8608               /* If the member is a class template, then -- even after
8609                  substitution -- there may be dependent types in the
8610                  template argument list for the class.  We increment
8611                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8612                  that function will assume that no types are dependent
8613                  when outside of a template.  */
8614               if (class_template_p)
8615                 ++processing_template_decl;
8616               newtag = tsubst (t, args, tf_error, NULL_TREE);
8617               if (class_template_p)
8618                 --processing_template_decl;
8619               if (newtag == error_mark_node)
8620                 continue;
8621
8622               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8623                 {
8624                   tree name = TYPE_IDENTIFIER (t);
8625
8626                   if (class_template_p)
8627                     /* Unfortunately, lookup_template_class sets
8628                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8629                        instantiation (i.e., for the type of a member
8630                        template class nested within a template class.)
8631                        This behavior is required for
8632                        maybe_process_partial_specialization to work
8633                        correctly, but is not accurate in this case;
8634                        the TAG is not an instantiation of anything.
8635                        (The corresponding TEMPLATE_DECL is an
8636                        instantiation, but the TYPE is not.) */
8637                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8638
8639                   /* Now, we call pushtag to put this NEWTAG into the scope of
8640                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8641                      pushtag calling push_template_decl.  We don't have to do
8642                      this for enums because it will already have been done in
8643                      tsubst_enum.  */
8644                   if (name)
8645                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8646                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8647                 }
8648             }
8649           else if (TREE_CODE (t) == FUNCTION_DECL
8650                    || DECL_FUNCTION_TEMPLATE_P (t))
8651             {
8652               /* Build new TYPE_METHODS.  */
8653               tree r;
8654
8655               if (TREE_CODE (t) == TEMPLATE_DECL)
8656                 ++processing_template_decl;
8657               r = tsubst (t, args, tf_error, NULL_TREE);
8658               if (TREE_CODE (t) == TEMPLATE_DECL)
8659                 --processing_template_decl;
8660               set_current_access_from_decl (r);
8661               finish_member_declaration (r);
8662               /* Instantiate members marked with attribute used.  */
8663               if (r != error_mark_node && DECL_PRESERVE_P (r))
8664                 mark_used (r);
8665             }
8666           else
8667             {
8668               /* Build new TYPE_FIELDS.  */
8669               if (TREE_CODE (t) == STATIC_ASSERT)
8670                 {
8671                   tree condition = 
8672                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8673                                  tf_warning_or_error, NULL_TREE,
8674                                  /*integral_constant_expression_p=*/true);
8675                   finish_static_assert (condition,
8676                                         STATIC_ASSERT_MESSAGE (t), 
8677                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8678                                         /*member_p=*/true);
8679                 }
8680               else if (TREE_CODE (t) != CONST_DECL)
8681                 {
8682                   tree r;
8683
8684                   /* The file and line for this declaration, to
8685                      assist in error message reporting.  Since we
8686                      called push_tinst_level above, we don't need to
8687                      restore these.  */
8688                   input_location = DECL_SOURCE_LOCATION (t);
8689
8690                   if (TREE_CODE (t) == TEMPLATE_DECL)
8691                     ++processing_template_decl;
8692                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8693                   if (TREE_CODE (t) == TEMPLATE_DECL)
8694                     --processing_template_decl;
8695                   if (TREE_CODE (r) == VAR_DECL)
8696                     {
8697                       /* In [temp.inst]:
8698
8699                            [t]he initialization (and any associated
8700                            side-effects) of a static data member does
8701                            not occur unless the static data member is
8702                            itself used in a way that requires the
8703                            definition of the static data member to
8704                            exist.
8705
8706                          Therefore, we do not substitute into the
8707                          initialized for the static data member here.  */
8708                       finish_static_data_member_decl
8709                         (r,
8710                          /*init=*/NULL_TREE,
8711                          /*init_const_expr_p=*/false,
8712                          /*asmspec_tree=*/NULL_TREE,
8713                          /*flags=*/0);
8714                       /* Instantiate members marked with attribute used.  */
8715                       if (r != error_mark_node && DECL_PRESERVE_P (r))
8716                         mark_used (r);
8717                     }
8718                   else if (TREE_CODE (r) == FIELD_DECL)
8719                     {
8720                       /* Determine whether R has a valid type and can be
8721                          completed later.  If R is invalid, then it is
8722                          replaced by error_mark_node so that it will not be
8723                          added to TYPE_FIELDS.  */
8724                       tree rtype = TREE_TYPE (r);
8725                       if (can_complete_type_without_circularity (rtype))
8726                         complete_type (rtype);
8727
8728                       if (!COMPLETE_TYPE_P (rtype))
8729                         {
8730                           cxx_incomplete_type_error (r, rtype);
8731                           r = error_mark_node;
8732                         }
8733                     }
8734
8735                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8736                      such a thing will already have been added to the field
8737                      list by tsubst_enum in finish_member_declaration in the
8738                      CLASSTYPE_NESTED_UTDS case above.  */
8739                   if (!(TREE_CODE (r) == TYPE_DECL
8740                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8741                         && DECL_ARTIFICIAL (r)))
8742                     {
8743                       set_current_access_from_decl (r);
8744                       finish_member_declaration (r);
8745                     }
8746                 }
8747             }
8748         }
8749       else
8750         {
8751           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8752             {
8753               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8754
8755               tree friend_type = t;
8756               bool adjust_processing_template_decl = false;
8757
8758               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8759                 {
8760                   /* template <class T> friend class C;  */
8761                   friend_type = tsubst_friend_class (friend_type, args);
8762                   adjust_processing_template_decl = true;
8763                 }
8764               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8765                 {
8766                   /* template <class T> friend class C::D;  */
8767                   friend_type = tsubst (friend_type, args,
8768                                         tf_warning_or_error, NULL_TREE);
8769                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8770                     friend_type = TREE_TYPE (friend_type);
8771                   adjust_processing_template_decl = true;
8772                 }
8773               else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8774                        || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8775                 {
8776                   /* This could be either
8777
8778                        friend class T::C;
8779
8780                      when dependent_type_p is false or
8781
8782                        template <class U> friend class T::C;
8783
8784                      otherwise.  */
8785                   friend_type = tsubst (friend_type, args,
8786                                         tf_warning_or_error, NULL_TREE);
8787                   /* Bump processing_template_decl for correct
8788                      dependent_type_p calculation.  */
8789                   ++processing_template_decl;
8790                   if (dependent_type_p (friend_type))
8791                     adjust_processing_template_decl = true;
8792                   --processing_template_decl;
8793                 }
8794               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8795                        && hidden_name_p (TYPE_NAME (friend_type)))
8796                 {
8797                   /* friend class C;
8798
8799                      where C hasn't been declared yet.  Let's lookup name
8800                      from namespace scope directly, bypassing any name that
8801                      come from dependent base class.  */
8802                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8803
8804                   /* The call to xref_tag_from_type does injection for friend
8805                      classes.  */
8806                   push_nested_namespace (ns);
8807                   friend_type =
8808                     xref_tag_from_type (friend_type, NULL_TREE,
8809                                         /*tag_scope=*/ts_current);
8810                   pop_nested_namespace (ns);
8811                 }
8812               else if (uses_template_parms (friend_type))
8813                 /* friend class C<T>;  */
8814                 friend_type = tsubst (friend_type, args,
8815                                       tf_warning_or_error, NULL_TREE);
8816               /* Otherwise it's
8817
8818                    friend class C;
8819
8820                  where C is already declared or
8821
8822                    friend class C<int>;
8823
8824                  We don't have to do anything in these cases.  */
8825
8826               if (adjust_processing_template_decl)
8827                 /* Trick make_friend_class into realizing that the friend
8828                    we're adding is a template, not an ordinary class.  It's
8829                    important that we use make_friend_class since it will
8830                    perform some error-checking and output cross-reference
8831                    information.  */
8832                 ++processing_template_decl;
8833
8834               if (friend_type != error_mark_node)
8835                 make_friend_class (type, friend_type, /*complain=*/false);
8836
8837               if (adjust_processing_template_decl)
8838                 --processing_template_decl;
8839             }
8840           else
8841             {
8842               /* Build new DECL_FRIENDLIST.  */
8843               tree r;
8844
8845               /* The file and line for this declaration, to
8846                  assist in error message reporting.  Since we
8847                  called push_tinst_level above, we don't need to
8848                  restore these.  */
8849               input_location = DECL_SOURCE_LOCATION (t);
8850
8851               if (TREE_CODE (t) == TEMPLATE_DECL)
8852                 {
8853                   ++processing_template_decl;
8854                   push_deferring_access_checks (dk_no_check);
8855                 }
8856
8857               r = tsubst_friend_function (t, args);
8858               add_friend (type, r, /*complain=*/false);
8859               if (TREE_CODE (t) == TEMPLATE_DECL)
8860                 {
8861                   pop_deferring_access_checks ();
8862                   --processing_template_decl;
8863                 }
8864             }
8865         }
8866     }
8867
8868   if (CLASSTYPE_LAMBDA_EXPR (type))
8869     {
8870       tree decl = lambda_function (type);
8871       if (decl)
8872         {
8873           tree lambda = CLASSTYPE_LAMBDA_EXPR (type);
8874           if (LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (lambda))
8875             {
8876               apply_lambda_return_type (lambda, void_type_node);
8877               LAMBDA_EXPR_RETURN_TYPE (lambda) = NULL_TREE;
8878             }
8879
8880           instantiate_decl (decl, false, false);
8881           maybe_add_lambda_conv_op (type);
8882         }
8883       else
8884         gcc_assert (errorcount);
8885     }
8886
8887   /* Set the file and line number information to whatever is given for
8888      the class itself.  This puts error messages involving generated
8889      implicit functions at a predictable point, and the same point
8890      that would be used for non-template classes.  */
8891   input_location = DECL_SOURCE_LOCATION (typedecl);
8892
8893   unreverse_member_declarations (type);
8894   finish_struct_1 (type);
8895   TYPE_BEING_DEFINED (type) = 0;
8896
8897   /* We don't instantiate default arguments for member functions.  14.7.1:
8898
8899      The implicit instantiation of a class template specialization causes
8900      the implicit instantiation of the declarations, but not of the
8901      definitions or default arguments, of the class member functions,
8902      member classes, static data members and member templates....  */
8903
8904   /* Some typedefs referenced from within the template code need to be access
8905      checked at template instantiation time, i.e now. These types were
8906      added to the template at parsing time. Let's get those and perform
8907      the access checks then.  */
8908   perform_typedefs_access_check (pattern, args);
8909   perform_deferred_access_checks ();
8910   pop_nested_class ();
8911   maximum_field_alignment = saved_maximum_field_alignment;
8912   if (!fn_context)
8913     pop_from_top_level ();
8914   pop_deferring_access_checks ();
8915   pop_tinst_level ();
8916
8917   /* The vtable for a template class can be emitted in any translation
8918      unit in which the class is instantiated.  When there is no key
8919      method, however, finish_struct_1 will already have added TYPE to
8920      the keyed_classes list.  */
8921   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8922     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8923
8924   return type;
8925 }
8926
8927 /* Wrapper for instantiate_class_template_1.  */
8928
8929 tree
8930 instantiate_class_template (tree type)
8931 {
8932   tree ret;
8933   timevar_push (TV_TEMPLATE_INST);
8934   ret = instantiate_class_template_1 (type);
8935   timevar_pop (TV_TEMPLATE_INST);
8936   return ret;
8937 }
8938
8939 static tree
8940 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8941 {
8942   tree r;
8943
8944   if (!t)
8945     r = t;
8946   else if (TYPE_P (t))
8947     r = tsubst (t, args, complain, in_decl);
8948   else
8949     {
8950       if (!(complain & tf_warning))
8951         ++c_inhibit_evaluation_warnings;
8952       r = tsubst_expr (t, args, complain, in_decl,
8953                        /*integral_constant_expression_p=*/true);
8954       if (!(complain & tf_warning))
8955         --c_inhibit_evaluation_warnings;
8956       /* Preserve the raw-reference nature of T.  */
8957       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
8958           && REFERENCE_REF_P (r))
8959         r = TREE_OPERAND (r, 0);
8960     }
8961   return r;
8962 }
8963
8964 /* Given a function parameter pack TMPL_PARM and some function parameters
8965    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
8966    and set *SPEC_P to point at the next point in the list.  */
8967
8968 static tree
8969 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
8970 {
8971   /* Collect all of the extra "packed" parameters into an
8972      argument pack.  */
8973   tree parmvec;
8974   tree parmtypevec;
8975   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8976   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8977   tree spec_parm = *spec_p;
8978   int i, len;
8979
8980   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
8981     if (tmpl_parm
8982         && !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
8983       break;
8984
8985   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8986   parmvec = make_tree_vec (len);
8987   parmtypevec = make_tree_vec (len);
8988   spec_parm = *spec_p;
8989   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8990     {
8991       TREE_VEC_ELT (parmvec, i) = spec_parm;
8992       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8993     }
8994
8995   /* Build the argument packs.  */
8996   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8997   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8998   TREE_TYPE (argpack) = argtypepack;
8999   *spec_p = spec_parm;
9000
9001   return argpack;
9002 }
9003
9004 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9005    NONTYPE_ARGUMENT_PACK.  */
9006
9007 static tree
9008 make_fnparm_pack (tree spec_parm)
9009 {
9010   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9011 }
9012
9013 /* Substitute ARGS into T, which is an pack expansion
9014    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9015    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9016    (if only a partial substitution could be performed) or
9017    ERROR_MARK_NODE if there was an error.  */
9018 tree
9019 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9020                        tree in_decl)
9021 {
9022   tree pattern;
9023   tree pack, packs = NULL_TREE;
9024   bool unsubstituted_packs = false;
9025   bool real_packs = false;
9026   int missing_level = 0;
9027   int i, len = -1;
9028   tree result;
9029   htab_t saved_local_specializations = NULL;
9030   bool need_local_specializations = false;
9031   int levels;
9032
9033   gcc_assert (PACK_EXPANSION_P (t));
9034   pattern = PACK_EXPANSION_PATTERN (t);
9035
9036   /* Add in any args remembered from an earlier partial instantiation.  */
9037   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
9038
9039   levels = TMPL_ARGS_DEPTH (args);
9040
9041   /* Determine the argument packs that will instantiate the parameter
9042      packs used in the expansion expression. While we're at it,
9043      compute the number of arguments to be expanded and make sure it
9044      is consistent.  */
9045   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
9046        pack = TREE_CHAIN (pack))
9047     {
9048       tree parm_pack = TREE_VALUE (pack);
9049       tree arg_pack = NULL_TREE;
9050       tree orig_arg = NULL_TREE;
9051       int level = 0;
9052
9053       if (TREE_CODE (parm_pack) == BASES)
9054        {
9055          if (BASES_DIRECT (parm_pack))
9056            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9057                                                         args, complain, in_decl, false));
9058          else
9059            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9060                                                  args, complain, in_decl, false));
9061        }
9062       if (TREE_CODE (parm_pack) == PARM_DECL)
9063         {
9064           if (PACK_EXPANSION_LOCAL_P (t))
9065             arg_pack = retrieve_local_specialization (parm_pack);
9066           else
9067             {
9068               /* We can't rely on local_specializations for a parameter
9069                  name used later in a function declaration (such as in a
9070                  late-specified return type).  Even if it exists, it might
9071                  have the wrong value for a recursive call.  Just make a
9072                  dummy decl, since it's only used for its type.  */
9073               /* Copy before tsubsting so that we don't recurse into any
9074                  later PARM_DECLs.  */
9075               arg_pack = tsubst_decl (copy_node (parm_pack), args, complain);
9076               if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9077                 /* Partial instantiation of the parm_pack, we can't build
9078                    up an argument pack yet.  */
9079                 arg_pack = NULL_TREE;
9080               else
9081                 arg_pack = make_fnparm_pack (arg_pack);
9082               need_local_specializations = true;
9083             }
9084         }
9085       else
9086         {
9087           int idx;
9088           template_parm_level_and_index (parm_pack, &level, &idx);
9089
9090           if (level <= levels)
9091             arg_pack = TMPL_ARG (args, level, idx);
9092         }
9093
9094       orig_arg = arg_pack;
9095       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9096         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9097       
9098       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9099         /* This can only happen if we forget to expand an argument
9100            pack somewhere else. Just return an error, silently.  */
9101         {
9102           result = make_tree_vec (1);
9103           TREE_VEC_ELT (result, 0) = error_mark_node;
9104           return result;
9105         }
9106
9107       if (arg_from_parm_pack_p (arg_pack, parm_pack))
9108         /* The argument pack that the parameter maps to is just an
9109            expansion of the parameter itself, such as one would find
9110            in the implicit typedef of a class inside the class itself.
9111            Consider this parameter "unsubstituted", so that we will
9112            maintain the outer pack expansion.  */
9113         arg_pack = NULL_TREE;
9114           
9115       if (arg_pack)
9116         {
9117           int my_len = 
9118             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9119
9120           /* Don't bother trying to do a partial substitution with
9121              incomplete packs; we'll try again after deduction.  */
9122           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9123             return t;
9124
9125           if (len < 0)
9126             len = my_len;
9127           else if (len != my_len)
9128             {
9129               if (!(complain & tf_error))
9130                 /* Fail quietly.  */;
9131               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9132                 error ("mismatched argument pack lengths while expanding "
9133                        "%<%T%>",
9134                        pattern);
9135               else
9136                 error ("mismatched argument pack lengths while expanding "
9137                        "%<%E%>",
9138                        pattern);
9139               return error_mark_node;
9140             }
9141
9142           if (TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
9143               && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack),
9144                                                  0)))
9145             /* This isn't a real argument pack yet.  */;
9146           else
9147             real_packs = true;
9148
9149           /* Keep track of the parameter packs and their corresponding
9150              argument packs.  */
9151           packs = tree_cons (parm_pack, arg_pack, packs);
9152           TREE_TYPE (packs) = orig_arg;
9153         }
9154       else
9155         {
9156           /* We can't substitute for this parameter pack.  We use a flag as
9157              well as the missing_level counter because function parameter
9158              packs don't have a level.  */
9159           unsubstituted_packs = true;
9160           if (!missing_level || missing_level > level)
9161             missing_level = level;
9162         }
9163     }
9164
9165   /* We cannot expand this expansion expression, because we don't have
9166      all of the argument packs we need.  */
9167   if (unsubstituted_packs)
9168     {
9169       if (real_packs)
9170         {
9171           /* We got some full packs, but we can't substitute them in until we
9172              have values for all the packs.  So remember these until then.  */
9173           tree save_args;
9174
9175           t = make_pack_expansion (pattern);
9176
9177           /* The call to add_to_template_args above assumes no overlap
9178              between saved args and new args, so prune away any fake
9179              args, i.e. those that satisfied arg_from_parm_pack_p above.  */
9180           if (missing_level && levels >= missing_level)
9181             {
9182               gcc_assert (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args)
9183                           && missing_level > 1);
9184               TREE_VEC_LENGTH (args) = missing_level - 1;
9185               save_args = copy_node (args);
9186               TREE_VEC_LENGTH (args) = levels;
9187             }
9188           else
9189             save_args = args;
9190
9191           PACK_EXPANSION_EXTRA_ARGS (t) = save_args;
9192         }
9193       else
9194         {
9195           /* There were no real arguments, we're just replacing a parameter
9196              pack with another version of itself. Substitute into the
9197              pattern and return a PACK_EXPANSION_*. The caller will need to
9198              deal with that.  */
9199           if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9200             t = tsubst_expr (pattern, args, complain, in_decl,
9201                              /*integral_constant_expression_p=*/false);
9202           else
9203             t = tsubst (pattern, args, complain, in_decl);
9204           t = make_pack_expansion (t);
9205         }
9206       return t;
9207     }
9208
9209   /* We could not find any argument packs that work.  */
9210   if (len < 0)
9211     return error_mark_node;
9212
9213   if (need_local_specializations)
9214     {
9215       /* We're in a late-specified return type, so create our own local
9216          specializations table; the current table is either NULL or (in the
9217          case of recursive unification) might have bindings that we don't
9218          want to use or alter.  */
9219       saved_local_specializations = local_specializations;
9220       local_specializations = htab_create (37,
9221                                            hash_local_specialization,
9222                                            eq_local_specializations,
9223                                            NULL);
9224     }
9225
9226   /* For each argument in each argument pack, substitute into the
9227      pattern.  */
9228   result = make_tree_vec (len);
9229   for (i = 0; i < len; ++i)
9230     {
9231       /* For parameter pack, change the substitution of the parameter
9232          pack to the ith argument in its argument pack, then expand
9233          the pattern.  */
9234       for (pack = packs; pack; pack = TREE_CHAIN (pack))
9235         {
9236           tree parm = TREE_PURPOSE (pack);
9237           tree arg;
9238
9239           /* Select the Ith argument from the pack.  */
9240           if (TREE_CODE (parm) == PARM_DECL)
9241             {
9242               if (i == 0)
9243                 {
9244                   arg = make_node (ARGUMENT_PACK_SELECT);
9245                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9246                   mark_used (parm);
9247                   register_local_specialization (arg, parm);
9248                 }
9249               else
9250                 arg = retrieve_local_specialization (parm);
9251             }
9252           else
9253             {
9254               int idx, level;
9255               template_parm_level_and_index (parm, &level, &idx);
9256
9257               if (i == 0)
9258                 {
9259                   arg = make_node (ARGUMENT_PACK_SELECT);
9260                   ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
9261                   /* Update the corresponding argument.  */
9262                   TMPL_ARG (args, level, idx) = arg;
9263                 }
9264               else
9265                 /* Re-use the ARGUMENT_PACK_SELECT.  */
9266                 arg = TMPL_ARG (args, level, idx);
9267             }
9268           ARGUMENT_PACK_SELECT_INDEX (arg) = i;
9269         }
9270
9271       /* Substitute into the PATTERN with the altered arguments.  */
9272       if (!TYPE_P (pattern))
9273         TREE_VEC_ELT (result, i) = 
9274           tsubst_expr (pattern, args, complain, in_decl,
9275                        /*integral_constant_expression_p=*/false);
9276       else
9277         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
9278
9279       if (TREE_VEC_ELT (result, i) == error_mark_node)
9280         {
9281           result = error_mark_node;
9282           break;
9283         }
9284     }
9285
9286   /* Update ARGS to restore the substitution from parameter packs to
9287      their argument packs.  */
9288   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9289     {
9290       tree parm = TREE_PURPOSE (pack);
9291
9292       if (TREE_CODE (parm) == PARM_DECL)
9293         register_local_specialization (TREE_TYPE (pack), parm);
9294       else
9295         {
9296           int idx, level;
9297           template_parm_level_and_index (parm, &level, &idx);
9298           
9299           /* Update the corresponding argument.  */
9300           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9301             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9302               TREE_TYPE (pack);
9303           else
9304             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9305         }
9306     }
9307
9308   if (need_local_specializations)
9309     {
9310       htab_delete (local_specializations);
9311       local_specializations = saved_local_specializations;
9312     }
9313   
9314   return result;
9315 }
9316
9317 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9318    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9319    parameter packs; all parms generated from a function parameter pack will
9320    have the same DECL_PARM_INDEX.  */
9321
9322 tree
9323 get_pattern_parm (tree parm, tree tmpl)
9324 {
9325   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9326   tree patparm;
9327
9328   if (DECL_ARTIFICIAL (parm))
9329     {
9330       for (patparm = DECL_ARGUMENTS (pattern);
9331            patparm; patparm = DECL_CHAIN (patparm))
9332         if (DECL_ARTIFICIAL (patparm)
9333             && DECL_NAME (parm) == DECL_NAME (patparm))
9334           break;
9335     }
9336   else
9337     {
9338       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9339       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9340       gcc_assert (DECL_PARM_INDEX (patparm)
9341                   == DECL_PARM_INDEX (parm));
9342     }
9343
9344   return patparm;
9345 }
9346
9347 /* Substitute ARGS into the vector or list of template arguments T.  */
9348
9349 static tree
9350 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9351 {
9352   tree orig_t = t;
9353   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9354   tree *elts;
9355
9356   if (t == error_mark_node)
9357     return error_mark_node;
9358
9359   len = TREE_VEC_LENGTH (t);
9360   elts = XALLOCAVEC (tree, len);
9361
9362   for (i = 0; i < len; i++)
9363     {
9364       tree orig_arg = TREE_VEC_ELT (t, i);
9365       tree new_arg;
9366
9367       if (TREE_CODE (orig_arg) == TREE_VEC)
9368         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9369       else if (PACK_EXPANSION_P (orig_arg))
9370         {
9371           /* Substitute into an expansion expression.  */
9372           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9373
9374           if (TREE_CODE (new_arg) == TREE_VEC)
9375             /* Add to the expanded length adjustment the number of
9376                expanded arguments. We subtract one from this
9377                measurement, because the argument pack expression
9378                itself is already counted as 1 in
9379                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9380                the argument pack is empty.  */
9381             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9382         }
9383       else if (ARGUMENT_PACK_P (orig_arg))
9384         {
9385           /* Substitute into each of the arguments.  */
9386           new_arg = TYPE_P (orig_arg)
9387             ? cxx_make_type (TREE_CODE (orig_arg))
9388             : make_node (TREE_CODE (orig_arg));
9389           
9390           SET_ARGUMENT_PACK_ARGS (
9391             new_arg,
9392             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9393                                   args, complain, in_decl));
9394
9395           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9396             new_arg = error_mark_node;
9397
9398           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9399             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9400                                           complain, in_decl);
9401             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9402
9403             if (TREE_TYPE (new_arg) == error_mark_node)
9404               new_arg = error_mark_node;
9405           }
9406         }
9407       else
9408         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9409
9410       if (new_arg == error_mark_node)
9411         return error_mark_node;
9412
9413       elts[i] = new_arg;
9414       if (new_arg != orig_arg)
9415         need_new = 1;
9416     }
9417
9418   if (!need_new)
9419     return t;
9420
9421   /* Make space for the expanded arguments coming from template
9422      argument packs.  */
9423   t = make_tree_vec (len + expanded_len_adjust);
9424   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9425      arguments for a member template.
9426      In that case each TREE_VEC in ORIG_T represents a level of template
9427      arguments, and ORIG_T won't carry any non defaulted argument count.
9428      It will rather be the nested TREE_VECs that will carry one.
9429      In other words, ORIG_T carries a non defaulted argument count only
9430      if it doesn't contain any nested TREE_VEC.  */
9431   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9432     {
9433       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9434       count += expanded_len_adjust;
9435       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9436     }
9437   for (i = 0, out = 0; i < len; i++)
9438     {
9439       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9440            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9441           && TREE_CODE (elts[i]) == TREE_VEC)
9442         {
9443           int idx;
9444
9445           /* Now expand the template argument pack "in place".  */
9446           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9447             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9448         }
9449       else
9450         {
9451           TREE_VEC_ELT (t, out) = elts[i];
9452           out++;
9453         }
9454     }
9455
9456   return t;
9457 }
9458
9459 /* Return the result of substituting ARGS into the template parameters
9460    given by PARMS.  If there are m levels of ARGS and m + n levels of
9461    PARMS, then the result will contain n levels of PARMS.  For
9462    example, if PARMS is `template <class T> template <class U>
9463    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9464    result will be `template <int*, double, class V>'.  */
9465
9466 static tree
9467 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9468 {
9469   tree r = NULL_TREE;
9470   tree* new_parms;
9471
9472   /* When substituting into a template, we must set
9473      PROCESSING_TEMPLATE_DECL as the template parameters may be
9474      dependent if they are based on one-another, and the dependency
9475      predicates are short-circuit outside of templates.  */
9476   ++processing_template_decl;
9477
9478   for (new_parms = &r;
9479        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9480        new_parms = &(TREE_CHAIN (*new_parms)),
9481          parms = TREE_CHAIN (parms))
9482     {
9483       tree new_vec =
9484         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9485       int i;
9486
9487       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9488         {
9489           tree tuple;
9490
9491           if (parms == error_mark_node)
9492             continue;
9493
9494           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9495
9496           if (tuple == error_mark_node)
9497             continue;
9498
9499           TREE_VEC_ELT (new_vec, i) =
9500             tsubst_template_parm (tuple, args, complain);
9501         }
9502
9503       *new_parms =
9504         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9505                              - TMPL_ARGS_DEPTH (args)),
9506                    new_vec, NULL_TREE);
9507     }
9508
9509   --processing_template_decl;
9510
9511   return r;
9512 }
9513
9514 /* Return the result of substituting ARGS into one template parameter
9515    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9516    parameter and which TREE_PURPOSE is the default argument of the
9517    template parameter.  */
9518
9519 static tree
9520 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9521 {
9522   tree default_value, parm_decl;
9523
9524   if (args == NULL_TREE
9525       || t == NULL_TREE
9526       || t == error_mark_node)
9527     return t;
9528
9529   gcc_assert (TREE_CODE (t) == TREE_LIST);
9530
9531   default_value = TREE_PURPOSE (t);
9532   parm_decl = TREE_VALUE (t);
9533
9534   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9535   if (TREE_CODE (parm_decl) == PARM_DECL
9536       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9537     parm_decl = error_mark_node;
9538   default_value = tsubst_template_arg (default_value, args,
9539                                        complain, NULL_TREE);
9540
9541   return build_tree_list (default_value, parm_decl);
9542 }
9543
9544 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9545    type T.  If T is not an aggregate or enumeration type, it is
9546    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9547    ENTERING_SCOPE is nonzero, T is the context for a template which
9548    we are presently tsubst'ing.  Return the substituted value.  */
9549
9550 static tree
9551 tsubst_aggr_type (tree t,
9552                   tree args,
9553                   tsubst_flags_t complain,
9554                   tree in_decl,
9555                   int entering_scope)
9556 {
9557   if (t == NULL_TREE)
9558     return NULL_TREE;
9559
9560   switch (TREE_CODE (t))
9561     {
9562     case RECORD_TYPE:
9563       if (TYPE_PTRMEMFUNC_P (t))
9564         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9565
9566       /* Else fall through.  */
9567     case ENUMERAL_TYPE:
9568     case UNION_TYPE:
9569       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9570         {
9571           tree argvec;
9572           tree context;
9573           tree r;
9574           int saved_unevaluated_operand;
9575           int saved_inhibit_evaluation_warnings;
9576
9577           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9578           saved_unevaluated_operand = cp_unevaluated_operand;
9579           cp_unevaluated_operand = 0;
9580           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9581           c_inhibit_evaluation_warnings = 0;
9582
9583           /* First, determine the context for the type we are looking
9584              up.  */
9585           context = TYPE_CONTEXT (t);
9586           if (context && TYPE_P (context))
9587             {
9588               context = tsubst_aggr_type (context, args, complain,
9589                                           in_decl, /*entering_scope=*/1);
9590               /* If context is a nested class inside a class template,
9591                  it may still need to be instantiated (c++/33959).  */
9592               context = complete_type (context);
9593             }
9594
9595           /* Then, figure out what arguments are appropriate for the
9596              type we are trying to find.  For example, given:
9597
9598                template <class T> struct S;
9599                template <class T, class U> void f(T, U) { S<U> su; }
9600
9601              and supposing that we are instantiating f<int, double>,
9602              then our ARGS will be {int, double}, but, when looking up
9603              S we only want {double}.  */
9604           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9605                                          complain, in_decl);
9606           if (argvec == error_mark_node)
9607             r = error_mark_node;
9608           else
9609             {
9610               r = lookup_template_class (t, argvec, in_decl, context,
9611                                          entering_scope, complain);
9612               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9613             }
9614
9615           cp_unevaluated_operand = saved_unevaluated_operand;
9616           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9617
9618           return r;
9619         }
9620       else
9621         /* This is not a template type, so there's nothing to do.  */
9622         return t;
9623
9624     default:
9625       return tsubst (t, args, complain, in_decl);
9626     }
9627 }
9628
9629 /* Substitute into the default argument ARG (a default argument for
9630    FN), which has the indicated TYPE.  */
9631
9632 tree
9633 tsubst_default_argument (tree fn, tree type, tree arg)
9634 {
9635   tree saved_class_ptr = NULL_TREE;
9636   tree saved_class_ref = NULL_TREE;
9637
9638   /* This can happen in invalid code.  */
9639   if (TREE_CODE (arg) == DEFAULT_ARG)
9640     return arg;
9641
9642   /* This default argument came from a template.  Instantiate the
9643      default argument here, not in tsubst.  In the case of
9644      something like:
9645
9646        template <class T>
9647        struct S {
9648          static T t();
9649          void f(T = t());
9650        };
9651
9652      we must be careful to do name lookup in the scope of S<T>,
9653      rather than in the current class.  */
9654   push_access_scope (fn);
9655   /* The "this" pointer is not valid in a default argument.  */
9656   if (cfun)
9657     {
9658       saved_class_ptr = current_class_ptr;
9659       cp_function_chain->x_current_class_ptr = NULL_TREE;
9660       saved_class_ref = current_class_ref;
9661       cp_function_chain->x_current_class_ref = NULL_TREE;
9662     }
9663
9664   push_deferring_access_checks(dk_no_deferred);
9665   /* The default argument expression may cause implicitly defined
9666      member functions to be synthesized, which will result in garbage
9667      collection.  We must treat this situation as if we were within
9668      the body of function so as to avoid collecting live data on the
9669      stack.  */
9670   ++function_depth;
9671   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9672                      tf_warning_or_error, NULL_TREE,
9673                      /*integral_constant_expression_p=*/false);
9674   --function_depth;
9675   pop_deferring_access_checks();
9676
9677   /* Restore the "this" pointer.  */
9678   if (cfun)
9679     {
9680       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9681       cp_function_chain->x_current_class_ref = saved_class_ref;
9682     }
9683
9684   /* Make sure the default argument is reasonable.  */
9685   arg = check_default_argument (type, arg);
9686
9687   pop_access_scope (fn);
9688
9689   return arg;
9690 }
9691
9692 /* Substitute into all the default arguments for FN.  */
9693
9694 static void
9695 tsubst_default_arguments (tree fn)
9696 {
9697   tree arg;
9698   tree tmpl_args;
9699
9700   tmpl_args = DECL_TI_ARGS (fn);
9701
9702   /* If this function is not yet instantiated, we certainly don't need
9703      its default arguments.  */
9704   if (uses_template_parms (tmpl_args))
9705     return;
9706   /* Don't do this again for clones.  */
9707   if (DECL_CLONED_FUNCTION_P (fn))
9708     return;
9709
9710   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9711        arg;
9712        arg = TREE_CHAIN (arg))
9713     if (TREE_PURPOSE (arg))
9714       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9715                                                     TREE_VALUE (arg),
9716                                                     TREE_PURPOSE (arg));
9717 }
9718
9719 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9720    result of the substitution.  Issue error and warning messages under
9721    control of COMPLAIN.  */
9722
9723 static tree
9724 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9725 {
9726 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9727   location_t saved_loc;
9728   tree r = NULL_TREE;
9729   tree in_decl = t;
9730   hashval_t hash = 0;
9731
9732   /* Set the filename and linenumber to improve error-reporting.  */
9733   saved_loc = input_location;
9734   input_location = DECL_SOURCE_LOCATION (t);
9735
9736   switch (TREE_CODE (t))
9737     {
9738     case TEMPLATE_DECL:
9739       {
9740         /* We can get here when processing a member function template,
9741            member class template, or template template parameter.  */
9742         tree decl = DECL_TEMPLATE_RESULT (t);
9743         tree spec;
9744         tree tmpl_args;
9745         tree full_args;
9746
9747         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9748           {
9749             /* Template template parameter is treated here.  */
9750             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9751             if (new_type == error_mark_node)
9752               RETURN (error_mark_node);
9753
9754             r = copy_decl (t);
9755             DECL_CHAIN (r) = NULL_TREE;
9756             TREE_TYPE (r) = new_type;
9757             DECL_TEMPLATE_RESULT (r)
9758               = build_decl (DECL_SOURCE_LOCATION (decl),
9759                             TYPE_DECL, DECL_NAME (decl), new_type);
9760             DECL_TEMPLATE_PARMS (r)
9761               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9762                                        complain);
9763             TYPE_NAME (new_type) = r;
9764             break;
9765           }
9766
9767         /* We might already have an instance of this template.
9768            The ARGS are for the surrounding class type, so the
9769            full args contain the tsubst'd args for the context,
9770            plus the innermost args from the template decl.  */
9771         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9772           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9773           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9774         /* Because this is a template, the arguments will still be
9775            dependent, even after substitution.  If
9776            PROCESSING_TEMPLATE_DECL is not set, the dependency
9777            predicates will short-circuit.  */
9778         ++processing_template_decl;
9779         full_args = tsubst_template_args (tmpl_args, args,
9780                                           complain, in_decl);
9781         --processing_template_decl;
9782         if (full_args == error_mark_node)
9783           RETURN (error_mark_node);
9784
9785         /* If this is a default template template argument,
9786            tsubst might not have changed anything.  */
9787         if (full_args == tmpl_args)
9788           RETURN (t);
9789
9790         hash = hash_tmpl_and_args (t, full_args);
9791         spec = retrieve_specialization (t, full_args, hash);
9792         if (spec != NULL_TREE)
9793           {
9794             r = spec;
9795             break;
9796           }
9797
9798         /* Make a new template decl.  It will be similar to the
9799            original, but will record the current template arguments.
9800            We also create a new function declaration, which is just
9801            like the old one, but points to this new template, rather
9802            than the old one.  */
9803         r = copy_decl (t);
9804         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9805         DECL_CHAIN (r) = NULL_TREE;
9806
9807         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9808
9809         if (TREE_CODE (decl) == TYPE_DECL
9810             && !TYPE_DECL_ALIAS_P (decl))
9811           {
9812             tree new_type;
9813             ++processing_template_decl;
9814             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9815             --processing_template_decl;
9816             if (new_type == error_mark_node)
9817               RETURN (error_mark_node);
9818
9819             TREE_TYPE (r) = new_type;
9820             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9821             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9822             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9823             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9824           }
9825         else
9826           {
9827             tree new_decl;
9828             ++processing_template_decl;
9829             new_decl = tsubst (decl, args, complain, in_decl);
9830             --processing_template_decl;
9831             if (new_decl == error_mark_node)
9832               RETURN (error_mark_node);
9833
9834             DECL_TEMPLATE_RESULT (r) = new_decl;
9835             DECL_TI_TEMPLATE (new_decl) = r;
9836             TREE_TYPE (r) = TREE_TYPE (new_decl);
9837             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9838             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9839           }
9840
9841         SET_DECL_IMPLICIT_INSTANTIATION (r);
9842         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9843         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9844
9845         /* The template parameters for this new template are all the
9846            template parameters for the old template, except the
9847            outermost level of parameters.  */
9848         DECL_TEMPLATE_PARMS (r)
9849           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9850                                    complain);
9851
9852         if (PRIMARY_TEMPLATE_P (t))
9853           DECL_PRIMARY_TEMPLATE (r) = r;
9854
9855         if (TREE_CODE (decl) != TYPE_DECL)
9856           /* Record this non-type partial instantiation.  */
9857           register_specialization (r, t,
9858                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9859                                    false, hash);
9860       }
9861       break;
9862
9863     case FUNCTION_DECL:
9864       {
9865         tree ctx;
9866         tree argvec = NULL_TREE;
9867         tree *friends;
9868         tree gen_tmpl;
9869         tree type;
9870         int member;
9871         int args_depth;
9872         int parms_depth;
9873
9874         /* Nobody should be tsubst'ing into non-template functions.  */
9875         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9876
9877         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9878           {
9879             tree spec;
9880             bool dependent_p;
9881
9882             /* If T is not dependent, just return it.  We have to
9883                increment PROCESSING_TEMPLATE_DECL because
9884                value_dependent_expression_p assumes that nothing is
9885                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9886             ++processing_template_decl;
9887             dependent_p = value_dependent_expression_p (t);
9888             --processing_template_decl;
9889             if (!dependent_p)
9890               RETURN (t);
9891
9892             /* Calculate the most general template of which R is a
9893                specialization, and the complete set of arguments used to
9894                specialize R.  */
9895             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9896             argvec = tsubst_template_args (DECL_TI_ARGS
9897                                           (DECL_TEMPLATE_RESULT
9898                                                  (DECL_TI_TEMPLATE (t))),
9899                                            args, complain, in_decl);
9900             if (argvec == error_mark_node)
9901               RETURN (error_mark_node);
9902
9903             /* Check to see if we already have this specialization.  */
9904             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9905             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9906
9907             if (spec)
9908               {
9909                 r = spec;
9910                 break;
9911               }
9912
9913             /* We can see more levels of arguments than parameters if
9914                there was a specialization of a member template, like
9915                this:
9916
9917                  template <class T> struct S { template <class U> void f(); }
9918                  template <> template <class U> void S<int>::f(U);
9919
9920                Here, we'll be substituting into the specialization,
9921                because that's where we can find the code we actually
9922                want to generate, but we'll have enough arguments for
9923                the most general template.
9924
9925                We also deal with the peculiar case:
9926
9927                  template <class T> struct S {
9928                    template <class U> friend void f();
9929                  };
9930                  template <class U> void f() {}
9931                  template S<int>;
9932                  template void f<double>();
9933
9934                Here, the ARGS for the instantiation of will be {int,
9935                double}.  But, we only need as many ARGS as there are
9936                levels of template parameters in CODE_PATTERN.  We are
9937                careful not to get fooled into reducing the ARGS in
9938                situations like:
9939
9940                  template <class T> struct S { template <class U> void f(U); }
9941                  template <class T> template <> void S<T>::f(int) {}
9942
9943                which we can spot because the pattern will be a
9944                specialization in this case.  */
9945             args_depth = TMPL_ARGS_DEPTH (args);
9946             parms_depth =
9947               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9948             if (args_depth > parms_depth
9949                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9950               args = get_innermost_template_args (args, parms_depth);
9951           }
9952         else
9953           {
9954             /* This special case arises when we have something like this:
9955
9956                  template <class T> struct S {
9957                    friend void f<int>(int, double);
9958                  };
9959
9960                Here, the DECL_TI_TEMPLATE for the friend declaration
9961                will be an IDENTIFIER_NODE.  We are being called from
9962                tsubst_friend_function, and we want only to create a
9963                new decl (R) with appropriate types so that we can call
9964                determine_specialization.  */
9965             gen_tmpl = NULL_TREE;
9966           }
9967
9968         if (DECL_CLASS_SCOPE_P (t))
9969           {
9970             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9971               member = 2;
9972             else
9973               member = 1;
9974             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9975                                     complain, t, /*entering_scope=*/1);
9976           }
9977         else
9978           {
9979             member = 0;
9980             ctx = DECL_CONTEXT (t);
9981           }
9982         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9983         if (type == error_mark_node)
9984           RETURN (error_mark_node);
9985
9986         /* We do NOT check for matching decls pushed separately at this
9987            point, as they may not represent instantiations of this
9988            template, and in any case are considered separate under the
9989            discrete model.  */
9990         r = copy_decl (t);
9991         DECL_USE_TEMPLATE (r) = 0;
9992         TREE_TYPE (r) = type;
9993         /* Clear out the mangled name and RTL for the instantiation.  */
9994         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9995         SET_DECL_RTL (r, NULL);
9996         /* Leave DECL_INITIAL set on deleted instantiations.  */
9997         if (!DECL_DELETED_FN (r))
9998           DECL_INITIAL (r) = NULL_TREE;
9999         DECL_CONTEXT (r) = ctx;
10000
10001         if (member && DECL_CONV_FN_P (r))
10002           /* Type-conversion operator.  Reconstruct the name, in
10003              case it's the name of one of the template's parameters.  */
10004           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10005
10006         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10007                                      complain, t);
10008         DECL_RESULT (r) = NULL_TREE;
10009
10010         TREE_STATIC (r) = 0;
10011         TREE_PUBLIC (r) = TREE_PUBLIC (t);
10012         DECL_EXTERNAL (r) = 1;
10013         /* If this is an instantiation of a function with internal
10014            linkage, we already know what object file linkage will be
10015            assigned to the instantiation.  */
10016         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10017         DECL_DEFER_OUTPUT (r) = 0;
10018         DECL_CHAIN (r) = NULL_TREE;
10019         DECL_PENDING_INLINE_INFO (r) = 0;
10020         DECL_PENDING_INLINE_P (r) = 0;
10021         DECL_SAVED_TREE (r) = NULL_TREE;
10022         DECL_STRUCT_FUNCTION (r) = NULL;
10023         TREE_USED (r) = 0;
10024         /* We'll re-clone as appropriate in instantiate_template.  */
10025         DECL_CLONED_FUNCTION (r) = NULL_TREE;
10026
10027         /* If we aren't complaining now, return on error before we register
10028            the specialization so that we'll complain eventually.  */
10029         if ((complain & tf_error) == 0
10030             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10031             && !grok_op_properties (r, /*complain=*/false))
10032           RETURN (error_mark_node);
10033
10034         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10035            this in the special friend case mentioned above where
10036            GEN_TMPL is NULL.  */
10037         if (gen_tmpl)
10038           {
10039             DECL_TEMPLATE_INFO (r)
10040               = build_template_info (gen_tmpl, argvec);
10041             SET_DECL_IMPLICIT_INSTANTIATION (r);
10042             register_specialization (r, gen_tmpl, argvec, false, hash);
10043
10044             /* We're not supposed to instantiate default arguments
10045                until they are called, for a template.  But, for a
10046                declaration like:
10047
10048                  template <class T> void f ()
10049                  { extern void g(int i = T()); }
10050
10051                we should do the substitution when the template is
10052                instantiated.  We handle the member function case in
10053                instantiate_class_template since the default arguments
10054                might refer to other members of the class.  */
10055             if (!member
10056                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
10057                 && !uses_template_parms (argvec))
10058               tsubst_default_arguments (r);
10059           }
10060         else
10061           DECL_TEMPLATE_INFO (r) = NULL_TREE;
10062
10063         /* Copy the list of befriending classes.  */
10064         for (friends = &DECL_BEFRIENDING_CLASSES (r);
10065              *friends;
10066              friends = &TREE_CHAIN (*friends))
10067           {
10068             *friends = copy_node (*friends);
10069             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10070                                             args, complain,
10071                                             in_decl);
10072           }
10073
10074         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10075           {
10076             maybe_retrofit_in_chrg (r);
10077             if (DECL_CONSTRUCTOR_P (r))
10078               grok_ctor_properties (ctx, r);
10079             /* If this is an instantiation of a member template, clone it.
10080                If it isn't, that'll be handled by
10081                clone_constructors_and_destructors.  */
10082             if (PRIMARY_TEMPLATE_P (gen_tmpl))
10083               clone_function_decl (r, /*update_method_vec_p=*/0);
10084           }
10085         else if ((complain & tf_error) != 0
10086                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10087                  && !grok_op_properties (r, /*complain=*/true))
10088           RETURN (error_mark_node);
10089
10090         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10091           SET_DECL_FRIEND_CONTEXT (r,
10092                                    tsubst (DECL_FRIEND_CONTEXT (t),
10093                                             args, complain, in_decl));
10094
10095         /* Possibly limit visibility based on template args.  */
10096         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10097         if (DECL_VISIBILITY_SPECIFIED (t))
10098           {
10099             DECL_VISIBILITY_SPECIFIED (r) = 0;
10100             DECL_ATTRIBUTES (r)
10101               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10102           }
10103         determine_visibility (r);
10104         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10105             && !processing_template_decl)
10106           defaulted_late_check (r);
10107
10108         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10109                                         args, complain, in_decl);
10110       }
10111       break;
10112
10113     case PARM_DECL:
10114       {
10115         tree type = NULL_TREE;
10116         int i, len = 1;
10117         tree expanded_types = NULL_TREE;
10118         tree prev_r = NULL_TREE;
10119         tree first_r = NULL_TREE;
10120
10121         if (FUNCTION_PARAMETER_PACK_P (t))
10122           {
10123             /* If there is a local specialization that isn't a
10124                parameter pack, it means that we're doing a "simple"
10125                substitution from inside tsubst_pack_expansion. Just
10126                return the local specialization (which will be a single
10127                parm).  */
10128             tree spec = retrieve_local_specialization (t);
10129             if (spec 
10130                 && TREE_CODE (spec) == PARM_DECL
10131                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10132               RETURN (spec);
10133
10134             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10135                the parameters in this function parameter pack.  */
10136             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10137                                                     complain, in_decl);
10138             if (TREE_CODE (expanded_types) == TREE_VEC)
10139               {
10140                 len = TREE_VEC_LENGTH (expanded_types);
10141
10142                 /* Zero-length parameter packs are boring. Just substitute
10143                    into the chain.  */
10144                 if (len == 0)
10145                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10146                                   TREE_CHAIN (t)));
10147               }
10148             else
10149               {
10150                 /* All we did was update the type. Make a note of that.  */
10151                 type = expanded_types;
10152                 expanded_types = NULL_TREE;
10153               }
10154           }
10155
10156         /* Loop through all of the parameter's we'll build. When T is
10157            a function parameter pack, LEN is the number of expanded
10158            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10159         r = NULL_TREE;
10160         for (i = 0; i < len; ++i)
10161           {
10162             prev_r = r;
10163             r = copy_node (t);
10164             if (DECL_TEMPLATE_PARM_P (t))
10165               SET_DECL_TEMPLATE_PARM_P (r);
10166
10167             if (expanded_types)
10168               /* We're on the Ith parameter of the function parameter
10169                  pack.  */
10170               {
10171                 /* An argument of a function parameter pack is not a parameter
10172                    pack.  */
10173                 FUNCTION_PARAMETER_PACK_P (r) = false;
10174
10175                 /* Get the Ith type.  */
10176                 type = TREE_VEC_ELT (expanded_types, i);
10177
10178                 /* Rename the parameter to include the index.  */
10179                 DECL_NAME (r)
10180                   = make_ith_pack_parameter_name (DECL_NAME (r), i);
10181               }
10182             else if (!type)
10183               /* We're dealing with a normal parameter.  */
10184               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10185
10186             type = type_decays_to (type);
10187             TREE_TYPE (r) = type;
10188             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10189
10190             if (DECL_INITIAL (r))
10191               {
10192                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10193                   DECL_INITIAL (r) = TREE_TYPE (r);
10194                 else
10195                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10196                                              complain, in_decl);
10197               }
10198
10199             DECL_CONTEXT (r) = NULL_TREE;
10200
10201             if (!DECL_TEMPLATE_PARM_P (r))
10202               DECL_ARG_TYPE (r) = type_passed_as (type);
10203
10204             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10205                                             args, complain, in_decl);
10206
10207             /* Keep track of the first new parameter we
10208                generate. That's what will be returned to the
10209                caller.  */
10210             if (!first_r)
10211               first_r = r;
10212
10213             /* Build a proper chain of parameters when substituting
10214                into a function parameter pack.  */
10215             if (prev_r)
10216               DECL_CHAIN (prev_r) = r;
10217           }
10218
10219         if (DECL_CHAIN (t))
10220           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10221                                    complain, DECL_CHAIN (t));
10222
10223         /* FIRST_R contains the start of the chain we've built.  */
10224         r = first_r;
10225       }
10226       break;
10227
10228     case FIELD_DECL:
10229       {
10230         tree type;
10231
10232         r = copy_decl (t);
10233         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10234         if (type == error_mark_node)
10235           RETURN (error_mark_node);
10236         TREE_TYPE (r) = type;
10237         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10238
10239         if (DECL_C_BIT_FIELD (r))
10240           /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10241              non-bit-fields DECL_INITIAL is a non-static data member
10242              initializer, which gets deferred instantiation.  */
10243           DECL_INITIAL (r)
10244             = tsubst_expr (DECL_INITIAL (t), args,
10245                            complain, in_decl,
10246                            /*integral_constant_expression_p=*/true);
10247         else if (DECL_INITIAL (t))
10248           {
10249             /* Set up DECL_TEMPLATE_INFO so that we can get at the
10250                NSDMI in perform_member_init.  Still set DECL_INITIAL
10251                so that we know there is one.  */
10252             DECL_INITIAL (r) = void_zero_node;
10253             gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10254             retrofit_lang_decl (r);
10255             DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10256           }
10257         /* We don't have to set DECL_CONTEXT here; it is set by
10258            finish_member_declaration.  */
10259         DECL_CHAIN (r) = NULL_TREE;
10260         if (VOID_TYPE_P (type))
10261           error ("instantiation of %q+D as type %qT", r, type);
10262
10263         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10264                                         args, complain, in_decl);
10265       }
10266       break;
10267
10268     case USING_DECL:
10269       /* We reach here only for member using decls.  We also need to check
10270          uses_template_parms because DECL_DEPENDENT_P is not set for a
10271          using-declaration that designates a member of the current
10272          instantiation (c++/53549).  */
10273       if (DECL_DEPENDENT_P (t)
10274           || uses_template_parms (USING_DECL_SCOPE (t)))
10275         {
10276           r = do_class_using_decl
10277             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
10278              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
10279           if (!r)
10280             r = error_mark_node;
10281           else
10282             {
10283               TREE_PROTECTED (r) = TREE_PROTECTED (t);
10284               TREE_PRIVATE (r) = TREE_PRIVATE (t);
10285             }
10286         }
10287       else
10288         {
10289           r = copy_node (t);
10290           DECL_CHAIN (r) = NULL_TREE;
10291         }
10292       break;
10293
10294     case TYPE_DECL:
10295     case VAR_DECL:
10296       {
10297         tree argvec = NULL_TREE;
10298         tree gen_tmpl = NULL_TREE;
10299         tree spec;
10300         tree tmpl = NULL_TREE;
10301         tree ctx;
10302         tree type = NULL_TREE;
10303         bool local_p;
10304
10305         if (TREE_CODE (t) == TYPE_DECL
10306             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10307           {
10308             /* If this is the canonical decl, we don't have to
10309                mess with instantiations, and often we can't (for
10310                typename, template type parms and such).  Note that
10311                TYPE_NAME is not correct for the above test if
10312                we've copied the type for a typedef.  */
10313             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10314             if (type == error_mark_node)
10315               RETURN (error_mark_node);
10316             r = TYPE_NAME (type);
10317             break;
10318           }
10319
10320         /* Check to see if we already have the specialization we
10321            need.  */
10322         spec = NULL_TREE;
10323         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10324           {
10325             /* T is a static data member or namespace-scope entity.
10326                We have to substitute into namespace-scope variables
10327                (even though such entities are never templates) because
10328                of cases like:
10329                
10330                  template <class T> void f() { extern T t; }
10331
10332                where the entity referenced is not known until
10333                instantiation time.  */
10334             local_p = false;
10335             ctx = DECL_CONTEXT (t);
10336             if (DECL_CLASS_SCOPE_P (t))
10337               {
10338                 ctx = tsubst_aggr_type (ctx, args,
10339                                         complain,
10340                                         in_decl, /*entering_scope=*/1);
10341                 /* If CTX is unchanged, then T is in fact the
10342                    specialization we want.  That situation occurs when
10343                    referencing a static data member within in its own
10344                    class.  We can use pointer equality, rather than
10345                    same_type_p, because DECL_CONTEXT is always
10346                    canonical...  */
10347                 if (ctx == DECL_CONTEXT (t)
10348                     && (TREE_CODE (t) != TYPE_DECL
10349                         /* ... unless T is a member template; in which
10350                            case our caller can be willing to create a
10351                            specialization of that template represented
10352                            by T.  */
10353                         || !(DECL_TI_TEMPLATE (t)
10354                              && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t)))))
10355                   spec = t;
10356               }
10357
10358             if (!spec)
10359               {
10360                 tmpl = DECL_TI_TEMPLATE (t);
10361                 gen_tmpl = most_general_template (tmpl);
10362                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10363                 if (argvec == error_mark_node)
10364                   RETURN (error_mark_node);
10365                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
10366                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
10367               }
10368           }
10369         else
10370           {
10371             /* A local variable.  */
10372             local_p = true;
10373             /* Subsequent calls to pushdecl will fill this in.  */
10374             ctx = NULL_TREE;
10375             spec = retrieve_local_specialization (t);
10376           }
10377         /* If we already have the specialization we need, there is
10378            nothing more to do.  */ 
10379         if (spec)
10380           {
10381             r = spec;
10382             break;
10383           }
10384
10385         if (TREE_CODE (t) == VAR_DECL && DECL_ANON_UNION_VAR_P (t))
10386           {
10387             /* Just use name lookup to find a member alias for an anonymous
10388                union, but then add it to the hash table.  */
10389             r = lookup_name (DECL_NAME (t));
10390             gcc_assert (DECL_ANON_UNION_VAR_P (r));
10391             register_local_specialization (r, t);
10392             break;
10393           }
10394
10395         /* Create a new node for the specialization we need.  */
10396         r = copy_decl (t);
10397         if (type == NULL_TREE)
10398           {
10399             if (is_typedef_decl (t))
10400               type = DECL_ORIGINAL_TYPE (t);
10401             else
10402               type = TREE_TYPE (t);
10403             if (TREE_CODE (t) == VAR_DECL
10404                 && VAR_HAD_UNKNOWN_BOUND (t)
10405                 && type != error_mark_node)
10406               type = strip_array_domain (type);
10407             type = tsubst (type, args, complain, in_decl);
10408           }
10409         if (TREE_CODE (r) == VAR_DECL)
10410           {
10411             /* Even if the original location is out of scope, the
10412                newly substituted one is not.  */
10413             DECL_DEAD_FOR_LOCAL (r) = 0;
10414             DECL_INITIALIZED_P (r) = 0;
10415             DECL_TEMPLATE_INSTANTIATED (r) = 0;
10416             if (type == error_mark_node)
10417               RETURN (error_mark_node);
10418             if (TREE_CODE (type) == FUNCTION_TYPE)
10419               {
10420                 /* It may seem that this case cannot occur, since:
10421
10422                      typedef void f();
10423                      void g() { f x; }
10424
10425                    declares a function, not a variable.  However:
10426       
10427                      typedef void f();
10428                      template <typename T> void g() { T t; }
10429                      template void g<f>();
10430
10431                    is an attempt to declare a variable with function
10432                    type.  */
10433                 error ("variable %qD has function type",
10434                        /* R is not yet sufficiently initialized, so we
10435                           just use its name.  */
10436                        DECL_NAME (r));
10437                 RETURN (error_mark_node);
10438               }
10439             type = complete_type (type);
10440             /* Wait until cp_finish_decl to set this again, to handle
10441                circular dependency (template/instantiate6.C). */
10442             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10443             type = check_var_type (DECL_NAME (r), type);
10444
10445             if (DECL_HAS_VALUE_EXPR_P (t))
10446               {
10447                 tree ve = DECL_VALUE_EXPR (t);
10448                 ve = tsubst_expr (ve, args, complain, in_decl,
10449                                   /*constant_expression_p=*/false);
10450                 if (REFERENCE_REF_P (ve))
10451                   {
10452                     gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10453                     ve = TREE_OPERAND (ve, 0);
10454                   }
10455                 SET_DECL_VALUE_EXPR (r, ve);
10456               }
10457           }
10458         else if (DECL_SELF_REFERENCE_P (t))
10459           SET_DECL_SELF_REFERENCE_P (r);
10460         TREE_TYPE (r) = type;
10461         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10462         DECL_CONTEXT (r) = ctx;
10463         /* Clear out the mangled name and RTL for the instantiation.  */
10464         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10465         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10466           SET_DECL_RTL (r, NULL);
10467         /* The initializer must not be expanded until it is required;
10468            see [temp.inst].  */
10469         DECL_INITIAL (r) = NULL_TREE;
10470         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10471           SET_DECL_RTL (r, NULL);
10472         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10473         if (TREE_CODE (r) == VAR_DECL)
10474           {
10475             /* Possibly limit visibility based on template args.  */
10476             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10477             if (DECL_VISIBILITY_SPECIFIED (t))
10478               {
10479                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10480                 DECL_ATTRIBUTES (r)
10481                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10482               }
10483             determine_visibility (r);
10484           }
10485
10486         if (!local_p)
10487           {
10488             /* A static data member declaration is always marked
10489                external when it is declared in-class, even if an
10490                initializer is present.  We mimic the non-template
10491                processing here.  */
10492             DECL_EXTERNAL (r) = 1;
10493
10494             register_specialization (r, gen_tmpl, argvec, false, hash);
10495             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10496             SET_DECL_IMPLICIT_INSTANTIATION (r);
10497           }
10498         else if (cp_unevaluated_operand)
10499           {
10500             /* We're substituting this var in a decltype outside of its
10501                scope, such as for a lambda return type.  Don't add it to
10502                local_specializations, do perform auto deduction.  */
10503             tree auto_node = type_uses_auto (type);
10504             if (auto_node)
10505               {
10506                 tree init
10507                   = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10508                                  /*constant_expression_p=*/false);
10509                 init = resolve_nondeduced_context (init);
10510                 TREE_TYPE (r) = type
10511                   = do_auto_deduction (type, init, auto_node);
10512               }
10513           }
10514         else
10515           register_local_specialization (r, t);
10516
10517         DECL_CHAIN (r) = NULL_TREE;
10518
10519         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10520                                         /*flags=*/0,
10521                                         args, complain, in_decl);
10522
10523         /* Preserve a typedef that names a type.  */
10524         if (is_typedef_decl (r))
10525           {
10526             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10527             set_underlying_type (r);
10528           }
10529
10530         layout_decl (r, 0);
10531       }
10532       break;
10533
10534     default:
10535       gcc_unreachable ();
10536     }
10537 #undef RETURN
10538
10539  out:
10540   /* Restore the file and line information.  */
10541   input_location = saved_loc;
10542
10543   return r;
10544 }
10545
10546 /* Substitute into the ARG_TYPES of a function type.
10547    If END is a TREE_CHAIN, leave it and any following types
10548    un-substituted.  */
10549
10550 static tree
10551 tsubst_arg_types (tree arg_types,
10552                   tree args,
10553                   tree end,
10554                   tsubst_flags_t complain,
10555                   tree in_decl)
10556 {
10557   tree remaining_arg_types;
10558   tree type = NULL_TREE;
10559   int i = 1;
10560   tree expanded_args = NULL_TREE;
10561   tree default_arg;
10562
10563   if (!arg_types || arg_types == void_list_node || arg_types == end)
10564     return arg_types;
10565
10566   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10567                                           args, end, complain, in_decl);
10568   if (remaining_arg_types == error_mark_node)
10569     return error_mark_node;
10570
10571   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10572     {
10573       /* For a pack expansion, perform substitution on the
10574          entire expression. Later on, we'll handle the arguments
10575          one-by-one.  */
10576       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10577                                             args, complain, in_decl);
10578
10579       if (TREE_CODE (expanded_args) == TREE_VEC)
10580         /* So that we'll spin through the parameters, one by one.  */
10581         i = TREE_VEC_LENGTH (expanded_args);
10582       else
10583         {
10584           /* We only partially substituted into the parameter
10585              pack. Our type is TYPE_PACK_EXPANSION.  */
10586           type = expanded_args;
10587           expanded_args = NULL_TREE;
10588         }
10589     }
10590
10591   while (i > 0) {
10592     --i;
10593     
10594     if (expanded_args)
10595       type = TREE_VEC_ELT (expanded_args, i);
10596     else if (!type)
10597       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10598
10599     if (type == error_mark_node)
10600       return error_mark_node;
10601     if (VOID_TYPE_P (type))
10602       {
10603         if (complain & tf_error)
10604           {
10605             error ("invalid parameter type %qT", type);
10606             if (in_decl)
10607               error ("in declaration %q+D", in_decl);
10608           }
10609         return error_mark_node;
10610     }
10611     
10612     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10613        top-level qualifiers as required.  */
10614     type = cv_unqualified (type_decays_to (type));
10615
10616     /* We do not substitute into default arguments here.  The standard
10617        mandates that they be instantiated only when needed, which is
10618        done in build_over_call.  */
10619     default_arg = TREE_PURPOSE (arg_types);
10620
10621     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10622       {
10623         /* We've instantiated a template before its default arguments
10624            have been parsed.  This can happen for a nested template
10625            class, and is not an error unless we require the default
10626            argument in a call of this function.  */
10627         remaining_arg_types = 
10628           tree_cons (default_arg, type, remaining_arg_types);
10629         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10630                        remaining_arg_types);
10631       }
10632     else
10633       remaining_arg_types = 
10634         hash_tree_cons (default_arg, type, remaining_arg_types);
10635   }
10636         
10637   return remaining_arg_types;
10638 }
10639
10640 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10641    *not* handle the exception-specification for FNTYPE, because the
10642    initial substitution of explicitly provided template parameters
10643    during argument deduction forbids substitution into the
10644    exception-specification:
10645
10646      [temp.deduct]
10647
10648      All references in the function type of the function template to  the
10649      corresponding template parameters are replaced by the specified tem-
10650      plate argument values.  If a substitution in a template parameter or
10651      in  the function type of the function template results in an invalid
10652      type, type deduction fails.  [Note: The equivalent  substitution  in
10653      exception specifications is done only when the function is instanti-
10654      ated, at which point a program is  ill-formed  if  the  substitution
10655      results in an invalid type.]  */
10656
10657 static tree
10658 tsubst_function_type (tree t,
10659                       tree args,
10660                       tsubst_flags_t complain,
10661                       tree in_decl)
10662 {
10663   tree return_type;
10664   tree arg_types;
10665   tree fntype;
10666
10667   /* The TYPE_CONTEXT is not used for function/method types.  */
10668   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10669
10670   /* Substitute the return type.  */
10671   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10672   if (return_type == error_mark_node)
10673     return error_mark_node;
10674   /* The standard does not presently indicate that creation of a
10675      function type with an invalid return type is a deduction failure.
10676      However, that is clearly analogous to creating an array of "void"
10677      or a reference to a reference.  This is core issue #486.  */
10678   if (TREE_CODE (return_type) == ARRAY_TYPE
10679       || TREE_CODE (return_type) == FUNCTION_TYPE)
10680     {
10681       if (complain & tf_error)
10682         {
10683           if (TREE_CODE (return_type) == ARRAY_TYPE)
10684             error ("function returning an array");
10685           else
10686             error ("function returning a function");
10687         }
10688       return error_mark_node;
10689     }
10690
10691   /* Substitute the argument types.  */
10692   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
10693                                 complain, in_decl);
10694   if (arg_types == error_mark_node)
10695     return error_mark_node;
10696
10697   /* Construct a new type node and return it.  */
10698   if (TREE_CODE (t) == FUNCTION_TYPE)
10699     {
10700       fntype = build_function_type (return_type, arg_types);
10701       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10702     }
10703   else
10704     {
10705       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10706       if (! MAYBE_CLASS_TYPE_P (r))
10707         {
10708           /* [temp.deduct]
10709
10710              Type deduction may fail for any of the following
10711              reasons:
10712
10713              -- Attempting to create "pointer to member of T" when T
10714              is not a class type.  */
10715           if (complain & tf_error)
10716             error ("creating pointer to member function of non-class type %qT",
10717                       r);
10718           return error_mark_node;
10719         }
10720
10721       fntype = build_method_type_directly (r, return_type,
10722                                            TREE_CHAIN (arg_types));
10723     }
10724   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10725
10726   return fntype;
10727 }
10728
10729 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10730    ARGS into that specification, and return the substituted
10731    specification.  If there is no specification, return NULL_TREE.  */
10732
10733 static tree
10734 tsubst_exception_specification (tree fntype,
10735                                 tree args,
10736                                 tsubst_flags_t complain,
10737                                 tree in_decl,
10738                                 bool defer_ok)
10739 {
10740   tree specs;
10741   tree new_specs;
10742
10743   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10744   new_specs = NULL_TREE;
10745   if (specs && TREE_PURPOSE (specs))
10746     {
10747       /* A noexcept-specifier.  */
10748       tree expr = TREE_PURPOSE (specs);
10749       if (TREE_CODE (expr) == INTEGER_CST)
10750         new_specs = expr;
10751       else if (defer_ok)
10752         {
10753           /* Defer instantiation of noexcept-specifiers to avoid
10754              excessive instantiations (c++/49107).  */
10755           new_specs = make_node (DEFERRED_NOEXCEPT);
10756           if (DEFERRED_NOEXCEPT_SPEC_P (specs))
10757             {
10758               /* We already partially instantiated this member template,
10759                  so combine the new args with the old.  */
10760               DEFERRED_NOEXCEPT_PATTERN (new_specs)
10761                 = DEFERRED_NOEXCEPT_PATTERN (expr);
10762               DEFERRED_NOEXCEPT_ARGS (new_specs)
10763                 = add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
10764             }
10765           else
10766             {
10767               DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
10768               DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
10769             }
10770         }
10771       else
10772         new_specs = tsubst_copy_and_build
10773           (expr, args, complain, in_decl, /*function_p=*/false,
10774            /*integral_constant_expression_p=*/true);
10775       new_specs = build_noexcept_spec (new_specs, complain);
10776     }
10777   else if (specs)
10778     {
10779       if (! TREE_VALUE (specs))
10780         new_specs = specs;
10781       else
10782         while (specs)
10783           {
10784             tree spec;
10785             int i, len = 1;
10786             tree expanded_specs = NULL_TREE;
10787
10788             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10789               {
10790                 /* Expand the pack expansion type.  */
10791                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10792                                                        args, complain,
10793                                                        in_decl);
10794
10795                 if (expanded_specs == error_mark_node)
10796                   return error_mark_node;
10797                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10798                   len = TREE_VEC_LENGTH (expanded_specs);
10799                 else
10800                   {
10801                     /* We're substituting into a member template, so
10802                        we got a TYPE_PACK_EXPANSION back.  Add that
10803                        expansion and move on.  */
10804                     gcc_assert (TREE_CODE (expanded_specs) 
10805                                 == TYPE_PACK_EXPANSION);
10806                     new_specs = add_exception_specifier (new_specs,
10807                                                          expanded_specs,
10808                                                          complain);
10809                     specs = TREE_CHAIN (specs);
10810                     continue;
10811                   }
10812               }
10813
10814             for (i = 0; i < len; ++i)
10815               {
10816                 if (expanded_specs)
10817                   spec = TREE_VEC_ELT (expanded_specs, i);
10818                 else
10819                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10820                 if (spec == error_mark_node)
10821                   return spec;
10822                 new_specs = add_exception_specifier (new_specs, spec, 
10823                                                      complain);
10824               }
10825
10826             specs = TREE_CHAIN (specs);
10827           }
10828     }
10829   return new_specs;
10830 }
10831
10832 /* Take the tree structure T and replace template parameters used
10833    therein with the argument vector ARGS.  IN_DECL is an associated
10834    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10835    Issue error and warning messages under control of COMPLAIN.  Note
10836    that we must be relatively non-tolerant of extensions here, in
10837    order to preserve conformance; if we allow substitutions that
10838    should not be allowed, we may allow argument deductions that should
10839    not succeed, and therefore report ambiguous overload situations
10840    where there are none.  In theory, we could allow the substitution,
10841    but indicate that it should have failed, and allow our caller to
10842    make sure that the right thing happens, but we don't try to do this
10843    yet.
10844
10845    This function is used for dealing with types, decls and the like;
10846    for expressions, use tsubst_expr or tsubst_copy.  */
10847
10848 tree
10849 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10850 {
10851   enum tree_code code;
10852   tree type, r = NULL_TREE;
10853
10854   if (t == NULL_TREE || t == error_mark_node
10855       || t == integer_type_node
10856       || t == void_type_node
10857       || t == char_type_node
10858       || t == unknown_type_node
10859       || TREE_CODE (t) == NAMESPACE_DECL
10860       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10861     return t;
10862
10863   if (DECL_P (t))
10864     return tsubst_decl (t, args, complain);
10865
10866   if (args == NULL_TREE)
10867     return t;
10868
10869   code = TREE_CODE (t);
10870
10871   if (code == IDENTIFIER_NODE)
10872     type = IDENTIFIER_TYPE_VALUE (t);
10873   else
10874     type = TREE_TYPE (t);
10875
10876   gcc_assert (type != unknown_type_node);
10877
10878   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10879      such as attribute aligned.  */
10880   if (TYPE_P (t)
10881       && typedef_variant_p (t))
10882     {
10883       tree decl = TYPE_NAME (t);
10884
10885       if (TYPE_DECL_ALIAS_P (decl)
10886           && DECL_LANG_SPECIFIC (decl)
10887           && DECL_TEMPLATE_INFO (decl)
10888           && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
10889         {
10890           /* DECL represents an alias template and we want to
10891              instantiate it.  Let's substitute our arguments for the
10892              template parameters into the declaration and get the
10893              resulting type.  */
10894           r = tsubst (decl, args, complain, decl);
10895         }
10896       else if (DECL_CLASS_SCOPE_P (decl)
10897                && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10898                && uses_template_parms (DECL_CONTEXT (decl)))
10899         {
10900           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10901           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10902           r = retrieve_specialization (tmpl, gen_args, 0);
10903         }
10904       else if (DECL_FUNCTION_SCOPE_P (decl)
10905                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10906                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10907         r = retrieve_local_specialization (decl);
10908       else
10909         /* The typedef is from a non-template context.  */
10910         return t;
10911
10912       if (r)
10913         {
10914           r = TREE_TYPE (r);
10915           r = cp_build_qualified_type_real
10916             (r, cp_type_quals (t) | cp_type_quals (r),
10917              complain | tf_ignore_bad_quals);
10918           return r;
10919         }
10920       else
10921         {
10922           /* We don't have an instantiation yet, so drop the typedef.  */
10923           int quals = cp_type_quals (t);
10924           t = DECL_ORIGINAL_TYPE (decl);
10925           t = cp_build_qualified_type_real (t, quals,
10926                                             complain | tf_ignore_bad_quals);
10927         }
10928     }
10929
10930   if (type
10931       && code != TYPENAME_TYPE
10932       && code != TEMPLATE_TYPE_PARM
10933       && code != IDENTIFIER_NODE
10934       && code != FUNCTION_TYPE
10935       && code != METHOD_TYPE)
10936     type = tsubst (type, args, complain, in_decl);
10937   if (type == error_mark_node)
10938     return error_mark_node;
10939
10940   switch (code)
10941     {
10942     case RECORD_TYPE:
10943     case UNION_TYPE:
10944     case ENUMERAL_TYPE:
10945       return tsubst_aggr_type (t, args, complain, in_decl,
10946                                /*entering_scope=*/0);
10947
10948     case ERROR_MARK:
10949     case IDENTIFIER_NODE:
10950     case VOID_TYPE:
10951     case REAL_TYPE:
10952     case COMPLEX_TYPE:
10953     case VECTOR_TYPE:
10954     case BOOLEAN_TYPE:
10955     case NULLPTR_TYPE:
10956     case LANG_TYPE:
10957       return t;
10958
10959     case INTEGER_TYPE:
10960       if (t == integer_type_node)
10961         return t;
10962
10963       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10964           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10965         return t;
10966
10967       {
10968         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10969
10970         max = tsubst_expr (omax, args, complain, in_decl,
10971                            /*integral_constant_expression_p=*/false);
10972
10973         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10974            needed.  */
10975         if (TREE_CODE (max) == NOP_EXPR
10976             && TREE_SIDE_EFFECTS (omax)
10977             && !TREE_TYPE (max))
10978           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10979
10980         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10981            with TREE_SIDE_EFFECTS that indicates this is not an integral
10982            constant expression.  */
10983         if (processing_template_decl
10984             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10985           {
10986             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10987             TREE_SIDE_EFFECTS (max) = 1;
10988           }
10989
10990         return compute_array_index_type (NULL_TREE, max, complain);
10991       }
10992
10993     case TEMPLATE_TYPE_PARM:
10994     case TEMPLATE_TEMPLATE_PARM:
10995     case BOUND_TEMPLATE_TEMPLATE_PARM:
10996     case TEMPLATE_PARM_INDEX:
10997       {
10998         int idx;
10999         int level;
11000         int levels;
11001         tree arg = NULL_TREE;
11002
11003         r = NULL_TREE;
11004
11005         gcc_assert (TREE_VEC_LENGTH (args) > 0);
11006         template_parm_level_and_index (t, &level, &idx); 
11007
11008         levels = TMPL_ARGS_DEPTH (args);
11009         if (level <= levels)
11010           {
11011             arg = TMPL_ARG (args, level, idx);
11012
11013             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11014               /* See through ARGUMENT_PACK_SELECT arguments. */
11015               arg = ARGUMENT_PACK_SELECT_ARG (arg);
11016           }
11017
11018         if (arg == error_mark_node)
11019           return error_mark_node;
11020         else if (arg != NULL_TREE)
11021           {
11022             if (ARGUMENT_PACK_P (arg))
11023               /* If ARG is an argument pack, we don't actually want to
11024                  perform a substitution here, because substitutions
11025                  for argument packs are only done
11026                  element-by-element. We can get to this point when
11027                  substituting the type of a non-type template
11028                  parameter pack, when that type actually contains
11029                  template parameter packs from an outer template, e.g.,
11030
11031                  template<typename... Types> struct A {
11032                    template<Types... Values> struct B { };
11033                  };  */
11034               return t;
11035
11036             if (code == TEMPLATE_TYPE_PARM)
11037               {
11038                 int quals;
11039                 gcc_assert (TYPE_P (arg));
11040
11041                 quals = cp_type_quals (arg) | cp_type_quals (t);
11042                   
11043                 return cp_build_qualified_type_real
11044                   (arg, quals, complain | tf_ignore_bad_quals);
11045               }
11046             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11047               {
11048                 /* We are processing a type constructed from a
11049                    template template parameter.  */
11050                 tree argvec = tsubst (TYPE_TI_ARGS (t),
11051                                       args, complain, in_decl);
11052                 if (argvec == error_mark_node)
11053                   return error_mark_node;
11054
11055                 gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
11056                             || TREE_CODE (arg) == TEMPLATE_DECL
11057                             || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
11058
11059                 if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
11060                   /* Consider this code:
11061
11062                         template <template <class> class Template>
11063                         struct Internal {
11064                         template <class Arg> using Bind = Template<Arg>;
11065                         };
11066
11067                         template <template <class> class Template, class Arg>
11068                         using Instantiate = Template<Arg>; //#0
11069
11070                         template <template <class> class Template,
11071                                   class Argument>
11072                         using Bind =
11073                           Instantiate<Internal<Template>::template Bind,
11074                                       Argument>; //#1
11075
11076                      When #1 is parsed, the
11077                      BOUND_TEMPLATE_TEMPLATE_PARM representing the
11078                      parameter `Template' in #0 matches the
11079                      UNBOUND_CLASS_TEMPLATE representing the argument
11080                      `Internal<Template>::template Bind'; We then want
11081                      to assemble the type `Bind<Argument>' that can't
11082                      be fully created right now, because
11083                      `Internal<Template>' not being complete, the Bind
11084                      template cannot be looked up in that context.  So
11085                      we need to "store" `Bind<Argument>' for later
11086                      when the context of Bind becomes complete.  Let's
11087                      store that in a TYPENAME_TYPE.  */
11088                   return make_typename_type (TYPE_CONTEXT (arg),
11089                                              build_nt (TEMPLATE_ID_EXPR,
11090                                                        TYPE_IDENTIFIER (arg),
11091                                                        argvec),
11092                                              typename_type,
11093                                              complain);
11094
11095                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
11096                    are resolving nested-types in the signature of a
11097                    member function templates.  Otherwise ARG is a
11098                    TEMPLATE_DECL and is the real template to be
11099                    instantiated.  */
11100                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11101                   arg = TYPE_NAME (arg);
11102
11103                 r = lookup_template_class (arg,
11104                                            argvec, in_decl,
11105                                            DECL_CONTEXT (arg),
11106                                             /*entering_scope=*/0,
11107                                            complain);
11108                 return cp_build_qualified_type_real
11109                   (r, cp_type_quals (t), complain);
11110               }
11111             else
11112               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11113               return convert_from_reference (unshare_expr (arg));
11114           }
11115
11116         if (level == 1)
11117           /* This can happen during the attempted tsubst'ing in
11118              unify.  This means that we don't yet have any information
11119              about the template parameter in question.  */
11120           return t;
11121
11122         /* If we get here, we must have been looking at a parm for a
11123            more deeply nested template.  Make a new version of this
11124            template parameter, but with a lower level.  */
11125         switch (code)
11126           {
11127           case TEMPLATE_TYPE_PARM:
11128           case TEMPLATE_TEMPLATE_PARM:
11129           case BOUND_TEMPLATE_TEMPLATE_PARM:
11130             if (cp_type_quals (t))
11131               {
11132                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11133                 r = cp_build_qualified_type_real
11134                   (r, cp_type_quals (t),
11135                    complain | (code == TEMPLATE_TYPE_PARM
11136                                ? tf_ignore_bad_quals : 0));
11137               }
11138             else
11139               {
11140                 r = copy_type (t);
11141                 TEMPLATE_TYPE_PARM_INDEX (r)
11142                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11143                                                 r, levels, args, complain);
11144                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11145                 TYPE_MAIN_VARIANT (r) = r;
11146                 TYPE_POINTER_TO (r) = NULL_TREE;
11147                 TYPE_REFERENCE_TO (r) = NULL_TREE;
11148
11149                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11150                   /* We have reduced the level of the template
11151                      template parameter, but not the levels of its
11152                      template parameters, so canonical_type_parameter
11153                      will not be able to find the canonical template
11154                      template parameter for this level. Thus, we
11155                      require structural equality checking to compare
11156                      TEMPLATE_TEMPLATE_PARMs. */
11157                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11158                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11159                   SET_TYPE_STRUCTURAL_EQUALITY (r);
11160                 else
11161                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
11162
11163                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11164                   {
11165                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11166                                           complain, in_decl);
11167                     if (argvec == error_mark_node)
11168                       return error_mark_node;
11169
11170                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11171                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11172                   }
11173               }
11174             break;
11175
11176           case TEMPLATE_PARM_INDEX:
11177             r = reduce_template_parm_level (t, type, levels, args, complain);
11178             break;
11179
11180           default:
11181             gcc_unreachable ();
11182           }
11183
11184         return r;
11185       }
11186
11187     case TREE_LIST:
11188       {
11189         tree purpose, value, chain;
11190
11191         if (t == void_list_node)
11192           return t;
11193
11194         purpose = TREE_PURPOSE (t);
11195         if (purpose)
11196           {
11197             purpose = tsubst (purpose, args, complain, in_decl);
11198             if (purpose == error_mark_node)
11199               return error_mark_node;
11200           }
11201         value = TREE_VALUE (t);
11202         if (value)
11203           {
11204             value = tsubst (value, args, complain, in_decl);
11205             if (value == error_mark_node)
11206               return error_mark_node;
11207           }
11208         chain = TREE_CHAIN (t);
11209         if (chain && chain != void_type_node)
11210           {
11211             chain = tsubst (chain, args, complain, in_decl);
11212             if (chain == error_mark_node)
11213               return error_mark_node;
11214           }
11215         if (purpose == TREE_PURPOSE (t)
11216             && value == TREE_VALUE (t)
11217             && chain == TREE_CHAIN (t))
11218           return t;
11219         return hash_tree_cons (purpose, value, chain);
11220       }
11221
11222     case TREE_BINFO:
11223       /* We should never be tsubsting a binfo.  */
11224       gcc_unreachable ();
11225
11226     case TREE_VEC:
11227       /* A vector of template arguments.  */
11228       gcc_assert (!type);
11229       return tsubst_template_args (t, args, complain, in_decl);
11230
11231     case POINTER_TYPE:
11232     case REFERENCE_TYPE:
11233       {
11234         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11235           return t;
11236
11237         /* [temp.deduct]
11238
11239            Type deduction may fail for any of the following
11240            reasons:
11241
11242            -- Attempting to create a pointer to reference type.
11243            -- Attempting to create a reference to a reference type or
11244               a reference to void.
11245
11246           Core issue 106 says that creating a reference to a reference
11247           during instantiation is no longer a cause for failure. We
11248           only enforce this check in strict C++98 mode.  */
11249         if ((TREE_CODE (type) == REFERENCE_TYPE
11250              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11251             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11252           {
11253             static location_t last_loc;
11254
11255             /* We keep track of the last time we issued this error
11256                message to avoid spewing a ton of messages during a
11257                single bad template instantiation.  */
11258             if (complain & tf_error
11259                 && last_loc != input_location)
11260               {
11261                 if (TREE_CODE (type) == VOID_TYPE)
11262                   error ("forming reference to void");
11263                else if (code == POINTER_TYPE)
11264                  error ("forming pointer to reference type %qT", type);
11265                else
11266                   error ("forming reference to reference type %qT", type);
11267                 last_loc = input_location;
11268               }
11269
11270             return error_mark_node;
11271           }
11272         else if (code == POINTER_TYPE)
11273           {
11274             r = build_pointer_type (type);
11275             if (TREE_CODE (type) == METHOD_TYPE)
11276               r = build_ptrmemfunc_type (r);
11277           }
11278         else if (TREE_CODE (type) == REFERENCE_TYPE)
11279           /* In C++0x, during template argument substitution, when there is an
11280              attempt to create a reference to a reference type, reference
11281              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11282
11283              "If a template-argument for a template-parameter T names a type
11284              that is a reference to a type A, an attempt to create the type
11285              'lvalue reference to cv T' creates the type 'lvalue reference to
11286              A,' while an attempt to create the type type rvalue reference to
11287              cv T' creates the type T"
11288           */
11289           r = cp_build_reference_type
11290               (TREE_TYPE (type),
11291                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11292         else
11293           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11294         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11295
11296         if (r != error_mark_node)
11297           /* Will this ever be needed for TYPE_..._TO values?  */
11298           layout_type (r);
11299
11300         return r;
11301       }
11302     case OFFSET_TYPE:
11303       {
11304         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11305         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11306           {
11307             /* [temp.deduct]
11308
11309                Type deduction may fail for any of the following
11310                reasons:
11311
11312                -- Attempting to create "pointer to member of T" when T
11313                   is not a class type.  */
11314             if (complain & tf_error)
11315               error ("creating pointer to member of non-class type %qT", r);
11316             return error_mark_node;
11317           }
11318         if (TREE_CODE (type) == REFERENCE_TYPE)
11319           {
11320             if (complain & tf_error)
11321               error ("creating pointer to member reference type %qT", type);
11322             return error_mark_node;
11323           }
11324         if (TREE_CODE (type) == VOID_TYPE)
11325           {
11326             if (complain & tf_error)
11327               error ("creating pointer to member of type void");
11328             return error_mark_node;
11329           }
11330         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11331         if (TREE_CODE (type) == FUNCTION_TYPE)
11332           {
11333             /* The type of the implicit object parameter gets its
11334                cv-qualifiers from the FUNCTION_TYPE. */
11335             tree memptr;
11336             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
11337             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11338             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11339                                                  complain);
11340           }
11341         else
11342           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11343                                                cp_type_quals (t),
11344                                                complain);
11345       }
11346     case FUNCTION_TYPE:
11347     case METHOD_TYPE:
11348       {
11349         tree fntype;
11350         tree specs;
11351         fntype = tsubst_function_type (t, args, complain, in_decl);
11352         if (fntype == error_mark_node)
11353           return error_mark_node;
11354
11355         /* Substitute the exception specification.  */
11356         specs = tsubst_exception_specification (t, args, complain,
11357                                                 in_decl, /*defer_ok*/true);
11358         if (specs == error_mark_node)
11359           return error_mark_node;
11360         if (specs)
11361           fntype = build_exception_variant (fntype, specs);
11362         return fntype;
11363       }
11364     case ARRAY_TYPE:
11365       {
11366         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11367         if (domain == error_mark_node)
11368           return error_mark_node;
11369
11370         /* As an optimization, we avoid regenerating the array type if
11371            it will obviously be the same as T.  */
11372         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11373           return t;
11374
11375         /* These checks should match the ones in grokdeclarator.
11376
11377            [temp.deduct]
11378
11379            The deduction may fail for any of the following reasons:
11380
11381            -- Attempting to create an array with an element type that
11382               is void, a function type, or a reference type, or [DR337]
11383               an abstract class type.  */
11384         if (TREE_CODE (type) == VOID_TYPE
11385             || TREE_CODE (type) == FUNCTION_TYPE
11386             || TREE_CODE (type) == REFERENCE_TYPE)
11387           {
11388             if (complain & tf_error)
11389               error ("creating array of %qT", type);
11390             return error_mark_node;
11391           }
11392         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
11393           {
11394             if (complain & tf_error)
11395               error ("creating array of %qT, which is an abstract class type",
11396                      type);
11397             return error_mark_node;
11398           }
11399
11400         r = build_cplus_array_type (type, domain);
11401
11402         if (TYPE_USER_ALIGN (t))
11403           {
11404             TYPE_ALIGN (r) = TYPE_ALIGN (t);
11405             TYPE_USER_ALIGN (r) = 1;
11406           }
11407
11408         return r;
11409       }
11410
11411     case TYPENAME_TYPE:
11412       {
11413         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11414                                      in_decl, /*entering_scope=*/1);
11415         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11416                               complain, in_decl);
11417
11418         if (ctx == error_mark_node || f == error_mark_node)
11419           return error_mark_node;
11420
11421         if (!MAYBE_CLASS_TYPE_P (ctx))
11422           {
11423             if (complain & tf_error)
11424               error ("%qT is not a class, struct, or union type", ctx);
11425             return error_mark_node;
11426           }
11427         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11428           {
11429             /* Normally, make_typename_type does not require that the CTX
11430                have complete type in order to allow things like:
11431
11432                  template <class T> struct S { typename S<T>::X Y; };
11433
11434                But, such constructs have already been resolved by this
11435                point, so here CTX really should have complete type, unless
11436                it's a partial instantiation.  */
11437             ctx = complete_type (ctx);
11438             if (!COMPLETE_TYPE_P (ctx))
11439               {
11440                 if (complain & tf_error)
11441                   cxx_incomplete_type_error (NULL_TREE, ctx);
11442                 return error_mark_node;
11443               }
11444           }
11445
11446         f = make_typename_type (ctx, f, typename_type,
11447                                 (complain & tf_error) | tf_keep_type_decl);
11448         if (f == error_mark_node)
11449           return f;
11450         if (TREE_CODE (f) == TYPE_DECL)
11451           {
11452             complain |= tf_ignore_bad_quals;
11453             f = TREE_TYPE (f);
11454           }
11455
11456         if (TREE_CODE (f) != TYPENAME_TYPE)
11457           {
11458             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11459               {
11460                 if (complain & tf_error)
11461                   error ("%qT resolves to %qT, which is not an enumeration type",
11462                          t, f);
11463                 else
11464                   return error_mark_node;
11465               }
11466             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11467               {
11468                 if (complain & tf_error)
11469                   error ("%qT resolves to %qT, which is is not a class type",
11470                          t, f);
11471                 else
11472                   return error_mark_node;
11473               }
11474           }
11475
11476         return cp_build_qualified_type_real
11477           (f, cp_type_quals (f) | cp_type_quals (t), complain);
11478       }
11479
11480     case UNBOUND_CLASS_TEMPLATE:
11481       {
11482         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11483                                      in_decl, /*entering_scope=*/1);
11484         tree name = TYPE_IDENTIFIER (t);
11485         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11486
11487         if (ctx == error_mark_node || name == error_mark_node)
11488           return error_mark_node;
11489
11490         if (parm_list)
11491           parm_list = tsubst_template_parms (parm_list, args, complain);
11492         return make_unbound_class_template (ctx, name, parm_list, complain);
11493       }
11494
11495     case TYPEOF_TYPE:
11496       {
11497         tree type;
11498
11499         ++cp_unevaluated_operand;
11500         ++c_inhibit_evaluation_warnings;
11501
11502         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11503                             complain, in_decl,
11504                             /*integral_constant_expression_p=*/false);
11505
11506         --cp_unevaluated_operand;
11507         --c_inhibit_evaluation_warnings;
11508
11509         type = finish_typeof (type);
11510         return cp_build_qualified_type_real (type,
11511                                              cp_type_quals (t)
11512                                              | cp_type_quals (type),
11513                                              complain);
11514       }
11515
11516     case DECLTYPE_TYPE:
11517       {
11518         tree type;
11519
11520         ++cp_unevaluated_operand;
11521         ++c_inhibit_evaluation_warnings;
11522
11523         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11524                             complain, in_decl,
11525                             /*integral_constant_expression_p=*/false);
11526
11527         --cp_unevaluated_operand;
11528         --c_inhibit_evaluation_warnings;
11529
11530         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11531           type = lambda_capture_field_type (type);
11532         else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11533           type = lambda_proxy_type (type);
11534         else
11535           type = finish_decltype_type
11536             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t), complain);
11537         return cp_build_qualified_type_real (type,
11538                                              cp_type_quals (t)
11539                                              | cp_type_quals (type),
11540                                              complain);
11541       }
11542
11543     case UNDERLYING_TYPE:
11544       {
11545         tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11546                             complain, in_decl);
11547         return finish_underlying_type (type);
11548       }
11549
11550     case TYPE_ARGUMENT_PACK:
11551     case NONTYPE_ARGUMENT_PACK:
11552       {
11553         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11554         tree packed_out = 
11555           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
11556                                 args,
11557                                 complain,
11558                                 in_decl);
11559         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11560
11561         /* For template nontype argument packs, also substitute into
11562            the type.  */
11563         if (code == NONTYPE_ARGUMENT_PACK)
11564           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11565
11566         return r;
11567       }
11568       break;
11569
11570     case INTEGER_CST:
11571     case REAL_CST:
11572     case STRING_CST:
11573     case PLUS_EXPR:
11574     case MINUS_EXPR:
11575     case NEGATE_EXPR:
11576     case NOP_EXPR:
11577     case INDIRECT_REF:
11578     case ADDR_EXPR:
11579     case CALL_EXPR:
11580     case ARRAY_REF:
11581     case SCOPE_REF:
11582       /* We should use one of the expression tsubsts for these codes.  */
11583       gcc_unreachable ();
11584
11585     default:
11586       sorry ("use of %qs in template", tree_code_name [(int) code]);
11587       return error_mark_node;
11588     }
11589 }
11590
11591 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11592    type of the expression on the left-hand side of the "." or "->"
11593    operator.  */
11594
11595 static tree
11596 tsubst_baselink (tree baselink, tree object_type,
11597                  tree args, tsubst_flags_t complain, tree in_decl)
11598 {
11599     tree name;
11600     tree qualifying_scope;
11601     tree fns;
11602     tree optype;
11603     tree template_args = 0;
11604     bool template_id_p = false;
11605     bool qualified = BASELINK_QUALIFIED_P (baselink);
11606
11607     /* A baselink indicates a function from a base class.  Both the
11608        BASELINK_ACCESS_BINFO and the base class referenced may
11609        indicate bases of the template class, rather than the
11610        instantiated class.  In addition, lookups that were not
11611        ambiguous before may be ambiguous now.  Therefore, we perform
11612        the lookup again.  */
11613     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11614     qualifying_scope = tsubst (qualifying_scope, args,
11615                                complain, in_decl);
11616     fns = BASELINK_FUNCTIONS (baselink);
11617     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11618     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11619       {
11620         template_id_p = true;
11621         template_args = TREE_OPERAND (fns, 1);
11622         fns = TREE_OPERAND (fns, 0);
11623         if (template_args)
11624           template_args = tsubst_template_args (template_args, args,
11625                                                 complain, in_decl);
11626       }
11627     name = DECL_NAME (get_first_fn (fns));
11628     if (IDENTIFIER_TYPENAME_P (name))
11629       name = mangle_conv_op_name_for_type (optype);
11630     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11631     if (!baselink)
11632       return error_mark_node;
11633
11634     /* If lookup found a single function, mark it as used at this
11635        point.  (If it lookup found multiple functions the one selected
11636        later by overload resolution will be marked as used at that
11637        point.)  */
11638     if (BASELINK_P (baselink))
11639       fns = BASELINK_FUNCTIONS (baselink);
11640     if (!template_id_p && !really_overloaded_fn (fns))
11641       mark_used (OVL_CURRENT (fns));
11642
11643     /* Add back the template arguments, if present.  */
11644     if (BASELINK_P (baselink) && template_id_p)
11645       BASELINK_FUNCTIONS (baselink)
11646         = build_nt (TEMPLATE_ID_EXPR,
11647                     BASELINK_FUNCTIONS (baselink),
11648                     template_args);
11649     /* Update the conversion operator type.  */
11650     BASELINK_OPTYPE (baselink) = optype;
11651
11652     if (!object_type)
11653       object_type = current_class_type;
11654
11655     if (qualified)
11656       baselink = adjust_result_of_qualified_name_lookup (baselink,
11657                                                          qualifying_scope,
11658                                                          object_type);
11659     return baselink;
11660 }
11661
11662 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11663    true if the qualified-id will be a postfix-expression in-and-of
11664    itself; false if more of the postfix-expression follows the
11665    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11666    of "&".  */
11667
11668 static tree
11669 tsubst_qualified_id (tree qualified_id, tree args,
11670                      tsubst_flags_t complain, tree in_decl,
11671                      bool done, bool address_p)
11672 {
11673   tree expr;
11674   tree scope;
11675   tree name;
11676   bool is_template;
11677   tree template_args;
11678
11679   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11680
11681   /* Figure out what name to look up.  */
11682   name = TREE_OPERAND (qualified_id, 1);
11683   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11684     {
11685       is_template = true;
11686       template_args = TREE_OPERAND (name, 1);
11687       if (template_args)
11688         template_args = tsubst_template_args (template_args, args,
11689                                               complain, in_decl);
11690       name = TREE_OPERAND (name, 0);
11691     }
11692   else
11693     {
11694       is_template = false;
11695       template_args = NULL_TREE;
11696     }
11697
11698   /* Substitute into the qualifying scope.  When there are no ARGS, we
11699      are just trying to simplify a non-dependent expression.  In that
11700      case the qualifying scope may be dependent, and, in any case,
11701      substituting will not help.  */
11702   scope = TREE_OPERAND (qualified_id, 0);
11703   if (args)
11704     {
11705       scope = tsubst (scope, args, complain, in_decl);
11706       expr = tsubst_copy (name, args, complain, in_decl);
11707     }
11708   else
11709     expr = name;
11710
11711   if (dependent_scope_p (scope))
11712     {
11713       if (is_template)
11714         expr = build_min_nt (TEMPLATE_ID_EXPR, expr, template_args);
11715       return build_qualified_name (NULL_TREE, scope, expr,
11716                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11717     }
11718
11719   if (!BASELINK_P (name) && !DECL_P (expr))
11720     {
11721       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11722         {
11723           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11724           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11725             {
11726               error ("qualifying type %qT does not match destructor name ~%qT",
11727                      scope, TREE_OPERAND (expr, 0));
11728               expr = error_mark_node;
11729             }
11730           else
11731             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11732                                           /*is_type_p=*/0, false);
11733         }
11734       else
11735         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11736       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11737                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11738         {
11739           if (complain & tf_error)
11740             {
11741               error ("dependent-name %qE is parsed as a non-type, but "
11742                      "instantiation yields a type", qualified_id);
11743               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11744             }
11745           return error_mark_node;
11746         }
11747     }
11748
11749   if (DECL_P (expr))
11750     {
11751       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11752                                            scope);
11753       /* Remember that there was a reference to this entity.  */
11754       mark_used (expr);
11755     }
11756
11757   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11758     {
11759       if (complain & tf_error)
11760         qualified_name_lookup_error (scope,
11761                                      TREE_OPERAND (qualified_id, 1),
11762                                      expr, input_location);
11763       return error_mark_node;
11764     }
11765
11766   if (is_template)
11767     expr = lookup_template_function (expr, template_args);
11768
11769   if (expr == error_mark_node && complain & tf_error)
11770     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11771                                  expr, input_location);
11772   else if (TYPE_P (scope))
11773     {
11774       expr = (adjust_result_of_qualified_name_lookup
11775               (expr, scope, current_class_type));
11776       expr = (finish_qualified_id_expr
11777               (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
11778                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11779                /*template_arg_p=*/false));
11780     }
11781
11782   /* Expressions do not generally have reference type.  */
11783   if (TREE_CODE (expr) != SCOPE_REF
11784       /* However, if we're about to form a pointer-to-member, we just
11785          want the referenced member referenced.  */
11786       && TREE_CODE (expr) != OFFSET_REF)
11787     expr = convert_from_reference (expr);
11788
11789   return expr;
11790 }
11791
11792 /* Like tsubst, but deals with expressions.  This function just replaces
11793    template parms; to finish processing the resultant expression, use
11794    tsubst_copy_and_build or tsubst_expr.  */
11795
11796 static tree
11797 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11798 {
11799   enum tree_code code;
11800   tree r;
11801
11802   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11803     return t;
11804
11805   code = TREE_CODE (t);
11806
11807   switch (code)
11808     {
11809     case PARM_DECL:
11810       r = retrieve_local_specialization (t);
11811
11812       if (r == NULL)
11813         {
11814           tree c;
11815
11816           /* We get here for a use of 'this' in an NSDMI.  */
11817           if (DECL_NAME (t) == this_identifier
11818               && at_function_scope_p ()
11819               && DECL_CONSTRUCTOR_P (current_function_decl))
11820             return current_class_ptr;
11821
11822           /* This can happen for a parameter name used later in a function
11823              declaration (such as in a late-specified return type).  Just
11824              make a dummy decl, since it's only used for its type.  */
11825           gcc_assert (cp_unevaluated_operand != 0);
11826           /* We copy T because want to tsubst the PARM_DECL only,
11827              not the following PARM_DECLs that are chained to T.  */
11828           c = copy_node (t);
11829           r = tsubst_decl (c, args, complain);
11830           /* Give it the template pattern as its context; its true context
11831              hasn't been instantiated yet and this is good enough for
11832              mangling.  */
11833           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11834         }
11835       
11836       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11837         r = ARGUMENT_PACK_SELECT_ARG (r);
11838       mark_used (r);
11839       return r;
11840
11841     case CONST_DECL:
11842       {
11843         tree enum_type;
11844         tree v;
11845
11846         if (DECL_TEMPLATE_PARM_P (t))
11847           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11848         /* There is no need to substitute into namespace-scope
11849            enumerators.  */
11850         if (DECL_NAMESPACE_SCOPE_P (t))
11851           return t;
11852         /* If ARGS is NULL, then T is known to be non-dependent.  */
11853         if (args == NULL_TREE)
11854           return integral_constant_value (t);
11855
11856         /* Unfortunately, we cannot just call lookup_name here.
11857            Consider:
11858
11859              template <int I> int f() {
11860              enum E { a = I };
11861              struct S { void g() { E e = a; } };
11862              };
11863
11864            When we instantiate f<7>::S::g(), say, lookup_name is not
11865            clever enough to find f<7>::a.  */
11866         enum_type
11867           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11868                               /*entering_scope=*/0);
11869
11870         for (v = TYPE_VALUES (enum_type);
11871              v != NULL_TREE;
11872              v = TREE_CHAIN (v))
11873           if (TREE_PURPOSE (v) == DECL_NAME (t))
11874             return TREE_VALUE (v);
11875
11876           /* We didn't find the name.  That should never happen; if
11877              name-lookup found it during preliminary parsing, we
11878              should find it again here during instantiation.  */
11879         gcc_unreachable ();
11880       }
11881       return t;
11882
11883     case FIELD_DECL:
11884       if (DECL_CONTEXT (t))
11885         {
11886           tree ctx;
11887
11888           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11889                                   /*entering_scope=*/1);
11890           if (ctx != DECL_CONTEXT (t))
11891             {
11892               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11893               if (!r)
11894                 {
11895                   if (complain & tf_error)
11896                     error ("using invalid field %qD", t);
11897                   return error_mark_node;
11898                 }
11899               return r;
11900             }
11901         }
11902
11903       return t;
11904
11905     case VAR_DECL:
11906     case FUNCTION_DECL:
11907       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11908           || local_variable_p (t))
11909         t = tsubst (t, args, complain, in_decl);
11910       mark_used (t);
11911       return t;
11912
11913     case NAMESPACE_DECL:
11914       return t;
11915
11916     case OVERLOAD:
11917       /* An OVERLOAD will always be a non-dependent overload set; an
11918          overload set from function scope will just be represented with an
11919          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11920       gcc_assert (!uses_template_parms (t));
11921       return t;
11922
11923     case BASELINK:
11924       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11925
11926     case TEMPLATE_DECL:
11927       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11928         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11929                        args, complain, in_decl);
11930       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11931         return tsubst (t, args, complain, in_decl);
11932       else if (DECL_CLASS_SCOPE_P (t)
11933                && uses_template_parms (DECL_CONTEXT (t)))
11934         {
11935           /* Template template argument like the following example need
11936              special treatment:
11937
11938                template <template <class> class TT> struct C {};
11939                template <class T> struct D {
11940                  template <class U> struct E {};
11941                  C<E> c;                                // #1
11942                };
11943                D<int> d;                                // #2
11944
11945              We are processing the template argument `E' in #1 for
11946              the template instantiation #2.  Originally, `E' is a
11947              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11948              have to substitute this with one having context `D<int>'.  */
11949
11950           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11951           return lookup_field (context, DECL_NAME(t), 0, false);
11952         }
11953       else
11954         /* Ordinary template template argument.  */
11955         return t;
11956
11957     case CAST_EXPR:
11958     case REINTERPRET_CAST_EXPR:
11959     case CONST_CAST_EXPR:
11960     case STATIC_CAST_EXPR:
11961     case DYNAMIC_CAST_EXPR:
11962     case IMPLICIT_CONV_EXPR:
11963     case CONVERT_EXPR:
11964     case NOP_EXPR:
11965       return build1
11966         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11967          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11968
11969     case SIZEOF_EXPR:
11970       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11971         {
11972
11973           tree expanded;
11974           int len = 0;
11975
11976           ++cp_unevaluated_operand;
11977           ++c_inhibit_evaluation_warnings;
11978           /* We only want to compute the number of arguments.  */
11979           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11980                                             complain, in_decl);
11981           --cp_unevaluated_operand;
11982           --c_inhibit_evaluation_warnings;
11983
11984           if (TREE_CODE (expanded) == TREE_VEC)
11985             len = TREE_VEC_LENGTH (expanded);
11986
11987           if (expanded == error_mark_node)
11988             return error_mark_node;
11989           else if (PACK_EXPANSION_P (expanded)
11990                    || (TREE_CODE (expanded) == TREE_VEC
11991                        && len > 0
11992                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11993             {
11994               if (TREE_CODE (expanded) == TREE_VEC)
11995                 expanded = TREE_VEC_ELT (expanded, len - 1);
11996
11997               if (TYPE_P (expanded))
11998                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11999                                                    complain & tf_error);
12000               else
12001                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
12002                                                    complain & tf_error);
12003             }
12004           else
12005             return build_int_cst (size_type_node, len);
12006         }
12007       /* Fall through */
12008
12009     case INDIRECT_REF:
12010     case NEGATE_EXPR:
12011     case TRUTH_NOT_EXPR:
12012     case BIT_NOT_EXPR:
12013     case ADDR_EXPR:
12014     case UNARY_PLUS_EXPR:      /* Unary + */
12015     case ALIGNOF_EXPR:
12016     case AT_ENCODE_EXPR:
12017     case ARROW_EXPR:
12018     case THROW_EXPR:
12019     case TYPEID_EXPR:
12020     case REALPART_EXPR:
12021     case IMAGPART_EXPR:
12022       return build1
12023         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12024          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
12025
12026     case COMPONENT_REF:
12027       {
12028         tree object;
12029         tree name;
12030
12031         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
12032         name = TREE_OPERAND (t, 1);
12033         if (TREE_CODE (name) == BIT_NOT_EXPR)
12034           {
12035             name = tsubst_copy (TREE_OPERAND (name, 0), args,
12036                                 complain, in_decl);
12037             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12038           }
12039         else if (TREE_CODE (name) == SCOPE_REF
12040                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
12041           {
12042             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
12043                                      complain, in_decl);
12044             name = TREE_OPERAND (name, 1);
12045             name = tsubst_copy (TREE_OPERAND (name, 0), args,
12046                                 complain, in_decl);
12047             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12048             name = build_qualified_name (/*type=*/NULL_TREE,
12049                                          base, name,
12050                                          /*template_p=*/false);
12051           }
12052         else if (BASELINK_P (name))
12053           name = tsubst_baselink (name,
12054                                   non_reference (TREE_TYPE (object)),
12055                                   args, complain,
12056                                   in_decl);
12057         else
12058           name = tsubst_copy (name, args, complain, in_decl);
12059         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
12060       }
12061
12062     case PLUS_EXPR:
12063     case MINUS_EXPR:
12064     case MULT_EXPR:
12065     case TRUNC_DIV_EXPR:
12066     case CEIL_DIV_EXPR:
12067     case FLOOR_DIV_EXPR:
12068     case ROUND_DIV_EXPR:
12069     case EXACT_DIV_EXPR:
12070     case BIT_AND_EXPR:
12071     case BIT_IOR_EXPR:
12072     case BIT_XOR_EXPR:
12073     case TRUNC_MOD_EXPR:
12074     case FLOOR_MOD_EXPR:
12075     case TRUTH_ANDIF_EXPR:
12076     case TRUTH_ORIF_EXPR:
12077     case TRUTH_AND_EXPR:
12078     case TRUTH_OR_EXPR:
12079     case RSHIFT_EXPR:
12080     case LSHIFT_EXPR:
12081     case RROTATE_EXPR:
12082     case LROTATE_EXPR:
12083     case EQ_EXPR:
12084     case NE_EXPR:
12085     case MAX_EXPR:
12086     case MIN_EXPR:
12087     case LE_EXPR:
12088     case GE_EXPR:
12089     case LT_EXPR:
12090     case GT_EXPR:
12091     case COMPOUND_EXPR:
12092     case DOTSTAR_EXPR:
12093     case MEMBER_REF:
12094     case PREDECREMENT_EXPR:
12095     case PREINCREMENT_EXPR:
12096     case POSTDECREMENT_EXPR:
12097     case POSTINCREMENT_EXPR:
12098       return build_nt
12099         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12100          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12101
12102     case SCOPE_REF:
12103       return build_qualified_name (/*type=*/NULL_TREE,
12104                                    tsubst_copy (TREE_OPERAND (t, 0),
12105                                                 args, complain, in_decl),
12106                                    tsubst_copy (TREE_OPERAND (t, 1),
12107                                                 args, complain, in_decl),
12108                                    QUALIFIED_NAME_IS_TEMPLATE (t));
12109
12110     case ARRAY_REF:
12111       return build_nt
12112         (ARRAY_REF,
12113          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12114          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12115          NULL_TREE, NULL_TREE);
12116
12117     case CALL_EXPR:
12118       {
12119         int n = VL_EXP_OPERAND_LENGTH (t);
12120         tree result = build_vl_exp (CALL_EXPR, n);
12121         int i;
12122         for (i = 0; i < n; i++)
12123           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12124                                              complain, in_decl);
12125         return result;
12126       }
12127
12128     case COND_EXPR:
12129     case MODOP_EXPR:
12130     case PSEUDO_DTOR_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         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12137         return r;
12138       }
12139
12140     case NEW_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          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12146         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12147         return r;
12148       }
12149
12150     case DELETE_EXPR:
12151       {
12152         r = build_nt
12153         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12154          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12155         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12156         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12157         return r;
12158       }
12159
12160     case TEMPLATE_ID_EXPR:
12161       {
12162         /* Substituted template arguments */
12163         tree fn = TREE_OPERAND (t, 0);
12164         tree targs = TREE_OPERAND (t, 1);
12165
12166         fn = tsubst_copy (fn, args, complain, in_decl);
12167         if (targs)
12168           targs = tsubst_template_args (targs, args, complain, in_decl);
12169
12170         return lookup_template_function (fn, targs);
12171       }
12172
12173     case TREE_LIST:
12174       {
12175         tree purpose, value, chain;
12176
12177         if (t == void_list_node)
12178           return t;
12179
12180         purpose = TREE_PURPOSE (t);
12181         if (purpose)
12182           purpose = tsubst_copy (purpose, args, complain, in_decl);
12183         value = TREE_VALUE (t);
12184         if (value)
12185           value = tsubst_copy (value, args, complain, in_decl);
12186         chain = TREE_CHAIN (t);
12187         if (chain && chain != void_type_node)
12188           chain = tsubst_copy (chain, args, complain, in_decl);
12189         if (purpose == TREE_PURPOSE (t)
12190             && value == TREE_VALUE (t)
12191             && chain == TREE_CHAIN (t))
12192           return t;
12193         return tree_cons (purpose, value, chain);
12194       }
12195
12196     case RECORD_TYPE:
12197     case UNION_TYPE:
12198     case ENUMERAL_TYPE:
12199     case INTEGER_TYPE:
12200     case TEMPLATE_TYPE_PARM:
12201     case TEMPLATE_TEMPLATE_PARM:
12202     case BOUND_TEMPLATE_TEMPLATE_PARM:
12203     case TEMPLATE_PARM_INDEX:
12204     case POINTER_TYPE:
12205     case REFERENCE_TYPE:
12206     case OFFSET_TYPE:
12207     case FUNCTION_TYPE:
12208     case METHOD_TYPE:
12209     case ARRAY_TYPE:
12210     case TYPENAME_TYPE:
12211     case UNBOUND_CLASS_TEMPLATE:
12212     case TYPEOF_TYPE:
12213     case DECLTYPE_TYPE:
12214     case TYPE_DECL:
12215       return tsubst (t, args, complain, in_decl);
12216
12217     case IDENTIFIER_NODE:
12218       if (IDENTIFIER_TYPENAME_P (t))
12219         {
12220           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12221           return mangle_conv_op_name_for_type (new_type);
12222         }
12223       else
12224         return t;
12225
12226     case CONSTRUCTOR:
12227       /* This is handled by tsubst_copy_and_build.  */
12228       gcc_unreachable ();
12229
12230     case VA_ARG_EXPR:
12231       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12232                                           in_decl),
12233                              tsubst (TREE_TYPE (t), args, complain, in_decl));
12234
12235     case CLEANUP_POINT_EXPR:
12236       /* We shouldn't have built any of these during initial template
12237          generation.  Instead, they should be built during instantiation
12238          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12239       gcc_unreachable ();
12240
12241     case OFFSET_REF:
12242       r = build2
12243         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12244          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12245          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12246       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12247       mark_used (TREE_OPERAND (r, 1));
12248       return r;
12249
12250     case EXPR_PACK_EXPANSION:
12251       error ("invalid use of pack expansion expression");
12252       return error_mark_node;
12253
12254     case NONTYPE_ARGUMENT_PACK:
12255       error ("use %<...%> to expand argument pack");
12256       return error_mark_node;
12257
12258     case INTEGER_CST:
12259     case REAL_CST:
12260     case STRING_CST:
12261     case COMPLEX_CST:
12262       {
12263         /* Instantiate any typedefs in the type.  */
12264         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12265         r = fold_convert (type, t);
12266         gcc_assert (TREE_CODE (r) == code);
12267         return r;
12268       }
12269
12270     case PTRMEM_CST:
12271       /* These can sometimes show up in a partial instantiation, but never
12272          involve template parms.  */
12273       gcc_assert (!uses_template_parms (t));
12274       return t;
12275
12276     default:
12277       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12278       gcc_checking_assert (false);
12279       return t;
12280     }
12281 }
12282
12283 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12284
12285 static tree
12286 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12287                     tree in_decl)
12288 {
12289   tree new_clauses = NULL, nc, oc;
12290
12291   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12292     {
12293       nc = copy_node (oc);
12294       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12295       new_clauses = nc;
12296
12297       switch (OMP_CLAUSE_CODE (nc))
12298         {
12299         case OMP_CLAUSE_LASTPRIVATE:
12300           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12301             {
12302               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12303               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12304                            in_decl, /*integral_constant_expression_p=*/false);
12305               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12306                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12307             }
12308           /* FALLTHRU */
12309         case OMP_CLAUSE_PRIVATE:
12310         case OMP_CLAUSE_SHARED:
12311         case OMP_CLAUSE_FIRSTPRIVATE:
12312         case OMP_CLAUSE_REDUCTION:
12313         case OMP_CLAUSE_COPYIN:
12314         case OMP_CLAUSE_COPYPRIVATE:
12315         case OMP_CLAUSE_IF:
12316         case OMP_CLAUSE_NUM_THREADS:
12317         case OMP_CLAUSE_SCHEDULE:
12318         case OMP_CLAUSE_COLLAPSE:
12319         case OMP_CLAUSE_FINAL:
12320           OMP_CLAUSE_OPERAND (nc, 0)
12321             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
12322                            in_decl, /*integral_constant_expression_p=*/false);
12323           break;
12324         case OMP_CLAUSE_NOWAIT:
12325         case OMP_CLAUSE_ORDERED:
12326         case OMP_CLAUSE_DEFAULT:
12327         case OMP_CLAUSE_UNTIED:
12328         case OMP_CLAUSE_MERGEABLE:
12329           break;
12330         default:
12331           gcc_unreachable ();
12332         }
12333     }
12334
12335   return finish_omp_clauses (nreverse (new_clauses));
12336 }
12337
12338 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12339
12340 static tree
12341 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12342                           tree in_decl)
12343 {
12344 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12345
12346   tree purpose, value, chain;
12347
12348   if (t == NULL)
12349     return t;
12350
12351   if (TREE_CODE (t) != TREE_LIST)
12352     return tsubst_copy_and_build (t, args, complain, in_decl,
12353                                   /*function_p=*/false,
12354                                   /*integral_constant_expression_p=*/false);
12355
12356   if (t == void_list_node)
12357     return t;
12358
12359   purpose = TREE_PURPOSE (t);
12360   if (purpose)
12361     purpose = RECUR (purpose);
12362   value = TREE_VALUE (t);
12363   if (value)
12364     {
12365       if (TREE_CODE (value) != LABEL_DECL)
12366         value = RECUR (value);
12367       else
12368         {
12369           value = lookup_label (DECL_NAME (value));
12370           gcc_assert (TREE_CODE (value) == LABEL_DECL);
12371           TREE_USED (value) = 1;
12372         }
12373     }
12374   chain = TREE_CHAIN (t);
12375   if (chain && chain != void_type_node)
12376     chain = RECUR (chain);
12377   return tree_cons (purpose, value, chain);
12378 #undef RECUR
12379 }
12380
12381 /* Substitute one OMP_FOR iterator.  */
12382
12383 static void
12384 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12385                          tree condv, tree incrv, tree *clauses,
12386                          tree args, tsubst_flags_t complain, tree in_decl,
12387                          bool integral_constant_expression_p)
12388 {
12389 #define RECUR(NODE)                             \
12390   tsubst_expr ((NODE), args, complain, in_decl, \
12391                integral_constant_expression_p)
12392   tree decl, init, cond, incr, auto_node;
12393
12394   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12395   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12396   decl = RECUR (TREE_OPERAND (init, 0));
12397   init = TREE_OPERAND (init, 1);
12398   auto_node = type_uses_auto (TREE_TYPE (decl));
12399   if (auto_node && init)
12400     {
12401       tree init_expr = init;
12402       if (TREE_CODE (init_expr) == DECL_EXPR)
12403         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
12404       init_expr = RECUR (init_expr);
12405       TREE_TYPE (decl)
12406         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
12407     }
12408   gcc_assert (!type_dependent_expression_p (decl));
12409
12410   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12411     {
12412       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12413       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12414       if (TREE_CODE (incr) == MODIFY_EXPR)
12415         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12416                                     RECUR (TREE_OPERAND (incr, 1)),
12417                                     complain);
12418       else
12419         incr = RECUR (incr);
12420       TREE_VEC_ELT (declv, i) = decl;
12421       TREE_VEC_ELT (initv, i) = init;
12422       TREE_VEC_ELT (condv, i) = cond;
12423       TREE_VEC_ELT (incrv, i) = incr;
12424       return;
12425     }
12426
12427   if (init && TREE_CODE (init) != DECL_EXPR)
12428     {
12429       tree c;
12430       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12431         {
12432           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12433                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12434               && OMP_CLAUSE_DECL (c) == decl)
12435             break;
12436           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12437                    && OMP_CLAUSE_DECL (c) == decl)
12438             error ("iteration variable %qD should not be firstprivate", decl);
12439           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12440                    && OMP_CLAUSE_DECL (c) == decl)
12441             error ("iteration variable %qD should not be reduction", decl);
12442         }
12443       if (c == NULL)
12444         {
12445           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12446           OMP_CLAUSE_DECL (c) = decl;
12447           c = finish_omp_clauses (c);
12448           if (c)
12449             {
12450               OMP_CLAUSE_CHAIN (c) = *clauses;
12451               *clauses = c;
12452             }
12453         }
12454     }
12455   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12456   if (COMPARISON_CLASS_P (cond))
12457     cond = build2 (TREE_CODE (cond), boolean_type_node,
12458                    RECUR (TREE_OPERAND (cond, 0)),
12459                    RECUR (TREE_OPERAND (cond, 1)));
12460   else
12461     cond = RECUR (cond);
12462   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12463   switch (TREE_CODE (incr))
12464     {
12465     case PREINCREMENT_EXPR:
12466     case PREDECREMENT_EXPR:
12467     case POSTINCREMENT_EXPR:
12468     case POSTDECREMENT_EXPR:
12469       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12470                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12471       break;
12472     case MODIFY_EXPR:
12473       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12474           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12475         {
12476           tree rhs = TREE_OPERAND (incr, 1);
12477           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12478                          RECUR (TREE_OPERAND (incr, 0)),
12479                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12480                                  RECUR (TREE_OPERAND (rhs, 0)),
12481                                  RECUR (TREE_OPERAND (rhs, 1))));
12482         }
12483       else
12484         incr = RECUR (incr);
12485       break;
12486     case MODOP_EXPR:
12487       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12488           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12489         {
12490           tree lhs = RECUR (TREE_OPERAND (incr, 0));
12491           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12492                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12493                                  TREE_TYPE (decl), lhs,
12494                                  RECUR (TREE_OPERAND (incr, 2))));
12495         }
12496       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12497                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12498                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12499         {
12500           tree rhs = TREE_OPERAND (incr, 2);
12501           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12502                          RECUR (TREE_OPERAND (incr, 0)),
12503                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12504                                  RECUR (TREE_OPERAND (rhs, 0)),
12505                                  RECUR (TREE_OPERAND (rhs, 1))));
12506         }
12507       else
12508         incr = RECUR (incr);
12509       break;
12510     default:
12511       incr = RECUR (incr);
12512       break;
12513     }
12514
12515   TREE_VEC_ELT (declv, i) = decl;
12516   TREE_VEC_ELT (initv, i) = init;
12517   TREE_VEC_ELT (condv, i) = cond;
12518   TREE_VEC_ELT (incrv, i) = incr;
12519 #undef RECUR
12520 }
12521
12522 /* Like tsubst_copy for expressions, etc. but also does semantic
12523    processing.  */
12524
12525 static tree
12526 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12527              bool integral_constant_expression_p)
12528 {
12529 #define RECUR(NODE)                             \
12530   tsubst_expr ((NODE), args, complain, in_decl, \
12531                integral_constant_expression_p)
12532
12533   tree stmt, tmp;
12534
12535   if (t == NULL_TREE || t == error_mark_node)
12536     return t;
12537
12538   if (EXPR_HAS_LOCATION (t))
12539     input_location = EXPR_LOCATION (t);
12540   if (STATEMENT_CODE_P (TREE_CODE (t)))
12541     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12542
12543   switch (TREE_CODE (t))
12544     {
12545     case STATEMENT_LIST:
12546       {
12547         tree_stmt_iterator i;
12548         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12549           RECUR (tsi_stmt (i));
12550         break;
12551       }
12552
12553     case CTOR_INITIALIZER:
12554       finish_mem_initializers (tsubst_initializer_list
12555                                (TREE_OPERAND (t, 0), args));
12556       break;
12557
12558     case RETURN_EXPR:
12559       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12560       break;
12561
12562     case EXPR_STMT:
12563       tmp = RECUR (EXPR_STMT_EXPR (t));
12564       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12565         finish_stmt_expr_expr (tmp, cur_stmt_expr);
12566       else
12567         finish_expr_stmt (tmp);
12568       break;
12569
12570     case USING_STMT:
12571       do_using_directive (USING_STMT_NAMESPACE (t));
12572       break;
12573
12574     case DECL_EXPR:
12575       {
12576         tree decl, pattern_decl;
12577         tree init;
12578
12579         pattern_decl = decl = DECL_EXPR_DECL (t);
12580         if (TREE_CODE (decl) == LABEL_DECL)
12581           finish_label_decl (DECL_NAME (decl));
12582         else if (TREE_CODE (decl) == USING_DECL)
12583           {
12584             tree scope = USING_DECL_SCOPE (decl);
12585             tree name = DECL_NAME (decl);
12586             tree decl;
12587
12588             scope = tsubst (scope, args, complain, in_decl);
12589             decl = lookup_qualified_name (scope, name,
12590                                           /*is_type_p=*/false,
12591                                           /*complain=*/false);
12592             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12593               qualified_name_lookup_error (scope, name, decl, input_location);
12594             else
12595               do_local_using_decl (decl, scope, name);
12596           }
12597         else
12598           {
12599             init = DECL_INITIAL (decl);
12600             decl = tsubst (decl, args, complain, in_decl);
12601             if (decl != error_mark_node)
12602               {
12603                 /* By marking the declaration as instantiated, we avoid
12604                    trying to instantiate it.  Since instantiate_decl can't
12605                    handle local variables, and since we've already done
12606                    all that needs to be done, that's the right thing to
12607                    do.  */
12608                 if (TREE_CODE (decl) == VAR_DECL)
12609                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12610                 if (TREE_CODE (decl) == VAR_DECL
12611                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12612                   /* Anonymous aggregates are a special case.  */
12613                   finish_anon_union (decl);
12614                 else if (is_capture_proxy (DECL_EXPR_DECL (t)))
12615                   {
12616                     DECL_CONTEXT (decl) = current_function_decl;
12617                     if (DECL_NAME (decl) == this_identifier)
12618                       {
12619                         tree lam = DECL_CONTEXT (current_function_decl);
12620                         lam = CLASSTYPE_LAMBDA_EXPR (lam);
12621                         LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
12622                       }
12623                     insert_capture_proxy (decl);
12624                   }
12625                 else
12626                   {
12627                     int const_init = false;
12628                     maybe_push_decl (decl);
12629                     if (TREE_CODE (decl) == VAR_DECL
12630                         && DECL_PRETTY_FUNCTION_P (decl))
12631                       {
12632                         /* For __PRETTY_FUNCTION__ we have to adjust the
12633                            initializer.  */
12634                         const char *const name
12635                           = cxx_printable_name (current_function_decl, 2);
12636                         init = cp_fname_init (name, &TREE_TYPE (decl));
12637                       }
12638                     else
12639                       {
12640                         tree t = RECUR (init);
12641
12642                         if (init && !t)
12643                           {
12644                             /* If we had an initializer but it
12645                                instantiated to nothing,
12646                                value-initialize the object.  This will
12647                                only occur when the initializer was a
12648                                pack expansion where the parameter packs
12649                                used in that expansion were of length
12650                                zero.  */
12651                             init = build_value_init (TREE_TYPE (decl),
12652                                                      complain);
12653                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12654                               init = get_target_expr_sfinae (init, complain);
12655                           }
12656                         else
12657                           init = t;
12658                       }
12659
12660                     if (TREE_CODE (decl) == VAR_DECL)
12661                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12662                                     (pattern_decl));
12663                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12664                   }
12665               }
12666           }
12667
12668         /* A DECL_EXPR can also be used as an expression, in the condition
12669            clause of an if/for/while construct.  */
12670         return decl;
12671       }
12672
12673     case FOR_STMT:
12674       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12675       RECUR (FOR_INIT_STMT (t));
12676       finish_for_init_stmt (stmt);
12677       tmp = RECUR (FOR_COND (t));
12678       finish_for_cond (tmp, stmt);
12679       tmp = RECUR (FOR_EXPR (t));
12680       finish_for_expr (tmp, stmt);
12681       RECUR (FOR_BODY (t));
12682       finish_for_stmt (stmt);
12683       break;
12684
12685     case RANGE_FOR_STMT:
12686       {
12687         tree decl, expr;
12688         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12689         decl = RANGE_FOR_DECL (t);
12690         decl = tsubst (decl, args, complain, in_decl);
12691         maybe_push_decl (decl);
12692         expr = RECUR (RANGE_FOR_EXPR (t));
12693         stmt = cp_convert_range_for (stmt, decl, expr);
12694         RECUR (RANGE_FOR_BODY (t));
12695         finish_for_stmt (stmt);
12696       }
12697       break;
12698
12699     case WHILE_STMT:
12700       stmt = begin_while_stmt ();
12701       tmp = RECUR (WHILE_COND (t));
12702       finish_while_stmt_cond (tmp, stmt);
12703       RECUR (WHILE_BODY (t));
12704       finish_while_stmt (stmt);
12705       break;
12706
12707     case DO_STMT:
12708       stmt = begin_do_stmt ();
12709       RECUR (DO_BODY (t));
12710       finish_do_body (stmt);
12711       tmp = RECUR (DO_COND (t));
12712       finish_do_stmt (tmp, stmt);
12713       break;
12714
12715     case IF_STMT:
12716       stmt = begin_if_stmt ();
12717       tmp = RECUR (IF_COND (t));
12718       finish_if_stmt_cond (tmp, stmt);
12719       RECUR (THEN_CLAUSE (t));
12720       finish_then_clause (stmt);
12721
12722       if (ELSE_CLAUSE (t))
12723         {
12724           begin_else_clause (stmt);
12725           RECUR (ELSE_CLAUSE (t));
12726           finish_else_clause (stmt);
12727         }
12728
12729       finish_if_stmt (stmt);
12730       break;
12731
12732     case BIND_EXPR:
12733       if (BIND_EXPR_BODY_BLOCK (t))
12734         stmt = begin_function_body ();
12735       else
12736         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12737                                     ? BCS_TRY_BLOCK : 0);
12738
12739       RECUR (BIND_EXPR_BODY (t));
12740
12741       if (BIND_EXPR_BODY_BLOCK (t))
12742         finish_function_body (stmt);
12743       else
12744         finish_compound_stmt (stmt);
12745       break;
12746
12747     case BREAK_STMT:
12748       finish_break_stmt ();
12749       break;
12750
12751     case CONTINUE_STMT:
12752       finish_continue_stmt ();
12753       break;
12754
12755     case SWITCH_STMT:
12756       stmt = begin_switch_stmt ();
12757       tmp = RECUR (SWITCH_STMT_COND (t));
12758       finish_switch_cond (tmp, stmt);
12759       RECUR (SWITCH_STMT_BODY (t));
12760       finish_switch_stmt (stmt);
12761       break;
12762
12763     case CASE_LABEL_EXPR:
12764       finish_case_label (EXPR_LOCATION (t),
12765                          RECUR (CASE_LOW (t)),
12766                          RECUR (CASE_HIGH (t)));
12767       break;
12768
12769     case LABEL_EXPR:
12770       {
12771         tree decl = LABEL_EXPR_LABEL (t);
12772         tree label;
12773
12774         label = finish_label_stmt (DECL_NAME (decl));
12775         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12776           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12777       }
12778       break;
12779
12780     case GOTO_EXPR:
12781       tmp = GOTO_DESTINATION (t);
12782       if (TREE_CODE (tmp) != LABEL_DECL)
12783         /* Computed goto's must be tsubst'd into.  On the other hand,
12784            non-computed gotos must not be; the identifier in question
12785            will have no binding.  */
12786         tmp = RECUR (tmp);
12787       else
12788         tmp = DECL_NAME (tmp);
12789       finish_goto_stmt (tmp);
12790       break;
12791
12792     case ASM_EXPR:
12793       tmp = finish_asm_stmt
12794         (ASM_VOLATILE_P (t),
12795          RECUR (ASM_STRING (t)),
12796          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12797          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12798          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12799          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12800       {
12801         tree asm_expr = tmp;
12802         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12803           asm_expr = TREE_OPERAND (asm_expr, 0);
12804         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12805       }
12806       break;
12807
12808     case TRY_BLOCK:
12809       if (CLEANUP_P (t))
12810         {
12811           stmt = begin_try_block ();
12812           RECUR (TRY_STMTS (t));
12813           finish_cleanup_try_block (stmt);
12814           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12815         }
12816       else
12817         {
12818           tree compound_stmt = NULL_TREE;
12819
12820           if (FN_TRY_BLOCK_P (t))
12821             stmt = begin_function_try_block (&compound_stmt);
12822           else
12823             stmt = begin_try_block ();
12824
12825           RECUR (TRY_STMTS (t));
12826
12827           if (FN_TRY_BLOCK_P (t))
12828             finish_function_try_block (stmt);
12829           else
12830             finish_try_block (stmt);
12831
12832           RECUR (TRY_HANDLERS (t));
12833           if (FN_TRY_BLOCK_P (t))
12834             finish_function_handler_sequence (stmt, compound_stmt);
12835           else
12836             finish_handler_sequence (stmt);
12837         }
12838       break;
12839
12840     case HANDLER:
12841       {
12842         tree decl = HANDLER_PARMS (t);
12843
12844         if (decl)
12845           {
12846             decl = tsubst (decl, args, complain, in_decl);
12847             /* Prevent instantiate_decl from trying to instantiate
12848                this variable.  We've already done all that needs to be
12849                done.  */
12850             if (decl != error_mark_node)
12851               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12852           }
12853         stmt = begin_handler ();
12854         finish_handler_parms (decl, stmt);
12855         RECUR (HANDLER_BODY (t));
12856         finish_handler (stmt);
12857       }
12858       break;
12859
12860     case TAG_DEFN:
12861       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12862       break;
12863
12864     case STATIC_ASSERT:
12865       {
12866         tree condition = 
12867           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12868                        args,
12869                        complain, in_decl,
12870                        /*integral_constant_expression_p=*/true);
12871         finish_static_assert (condition,
12872                               STATIC_ASSERT_MESSAGE (t),
12873                               STATIC_ASSERT_SOURCE_LOCATION (t),
12874                               /*member_p=*/false);
12875       }
12876       break;
12877
12878     case OMP_PARALLEL:
12879       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12880                                 args, complain, in_decl);
12881       stmt = begin_omp_parallel ();
12882       RECUR (OMP_PARALLEL_BODY (t));
12883       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12884         = OMP_PARALLEL_COMBINED (t);
12885       break;
12886
12887     case OMP_TASK:
12888       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12889                                 args, complain, in_decl);
12890       stmt = begin_omp_task ();
12891       RECUR (OMP_TASK_BODY (t));
12892       finish_omp_task (tmp, stmt);
12893       break;
12894
12895     case OMP_FOR:
12896       {
12897         tree clauses, body, pre_body;
12898         tree declv, initv, condv, incrv;
12899         int i;
12900
12901         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12902                                       args, complain, in_decl);
12903         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12904         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12905         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12906         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12907
12908         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12909           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12910                                    &clauses, args, complain, in_decl,
12911                                    integral_constant_expression_p);
12912
12913         stmt = begin_omp_structured_block ();
12914
12915         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12916           if (TREE_VEC_ELT (initv, i) == NULL
12917               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12918             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12919           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12920             {
12921               tree init = RECUR (TREE_VEC_ELT (initv, i));
12922               gcc_assert (init == TREE_VEC_ELT (declv, i));
12923               TREE_VEC_ELT (initv, i) = NULL_TREE;
12924             }
12925           else
12926             {
12927               tree decl_expr = TREE_VEC_ELT (initv, i);
12928               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12929               gcc_assert (init != NULL);
12930               TREE_VEC_ELT (initv, i) = RECUR (init);
12931               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12932               RECUR (decl_expr);
12933               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12934             }
12935
12936         pre_body = push_stmt_list ();
12937         RECUR (OMP_FOR_PRE_BODY (t));
12938         pre_body = pop_stmt_list (pre_body);
12939
12940         body = push_stmt_list ();
12941         RECUR (OMP_FOR_BODY (t));
12942         body = pop_stmt_list (body);
12943
12944         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12945                             body, pre_body, clauses);
12946
12947         add_stmt (finish_omp_structured_block (stmt));
12948       }
12949       break;
12950
12951     case OMP_SECTIONS:
12952     case OMP_SINGLE:
12953       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12954       stmt = push_stmt_list ();
12955       RECUR (OMP_BODY (t));
12956       stmt = pop_stmt_list (stmt);
12957
12958       t = copy_node (t);
12959       OMP_BODY (t) = stmt;
12960       OMP_CLAUSES (t) = tmp;
12961       add_stmt (t);
12962       break;
12963
12964     case OMP_SECTION:
12965     case OMP_CRITICAL:
12966     case OMP_MASTER:
12967     case OMP_ORDERED:
12968       stmt = push_stmt_list ();
12969       RECUR (OMP_BODY (t));
12970       stmt = pop_stmt_list (stmt);
12971
12972       t = copy_node (t);
12973       OMP_BODY (t) = stmt;
12974       add_stmt (t);
12975       break;
12976
12977     case OMP_ATOMIC:
12978       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12979       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
12980         {
12981           tree op1 = TREE_OPERAND (t, 1);
12982           tree rhs1 = NULL_TREE;
12983           tree lhs, rhs;
12984           if (TREE_CODE (op1) == COMPOUND_EXPR)
12985             {
12986               rhs1 = RECUR (TREE_OPERAND (op1, 0));
12987               op1 = TREE_OPERAND (op1, 1);
12988             }
12989           lhs = RECUR (TREE_OPERAND (op1, 0));
12990           rhs = RECUR (TREE_OPERAND (op1, 1));
12991           finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
12992                              NULL_TREE, NULL_TREE, rhs1);
12993         }
12994       else
12995         {
12996           tree op1 = TREE_OPERAND (t, 1);
12997           tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
12998           tree rhs1 = NULL_TREE;
12999           enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
13000           enum tree_code opcode = NOP_EXPR;
13001           if (code == OMP_ATOMIC_READ)
13002             {
13003               v = RECUR (TREE_OPERAND (op1, 0));
13004               lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
13005             }
13006           else if (code == OMP_ATOMIC_CAPTURE_OLD
13007                    || code == OMP_ATOMIC_CAPTURE_NEW)
13008             {
13009               tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
13010               v = RECUR (TREE_OPERAND (op1, 0));
13011               lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
13012               if (TREE_CODE (op11) == COMPOUND_EXPR)
13013                 {
13014                   rhs1 = RECUR (TREE_OPERAND (op11, 0));
13015                   op11 = TREE_OPERAND (op11, 1);
13016                 }
13017               lhs = RECUR (TREE_OPERAND (op11, 0));
13018               rhs = RECUR (TREE_OPERAND (op11, 1));
13019               opcode = TREE_CODE (op11);
13020             }
13021           else
13022             {
13023               code = OMP_ATOMIC;
13024               lhs = RECUR (TREE_OPERAND (op1, 0));
13025               rhs = RECUR (TREE_OPERAND (op1, 1));
13026             }
13027           finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
13028         }
13029       break;
13030
13031     case TRANSACTION_EXPR:
13032       {
13033         int flags = 0;
13034         flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
13035         flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
13036
13037         if (TRANSACTION_EXPR_IS_STMT (t))
13038           {
13039             tree body = TRANSACTION_EXPR_BODY (t);
13040             tree noex = NULL_TREE;
13041             if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
13042               {
13043                 noex = MUST_NOT_THROW_COND (body);
13044                 if (noex == NULL_TREE)
13045                   noex = boolean_true_node;
13046                 body = TREE_OPERAND (body, 0);
13047               }
13048             stmt = begin_transaction_stmt (input_location, NULL, flags);
13049             RECUR (body);
13050             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
13051           }
13052         else
13053           {
13054             stmt = build_transaction_expr (EXPR_LOCATION (t),
13055                                            RECUR (TRANSACTION_EXPR_BODY (t)),
13056                                            flags, NULL_TREE);
13057             return stmt;
13058           }
13059       }
13060       break;
13061
13062     case MUST_NOT_THROW_EXPR:
13063       return build_must_not_throw_expr (RECUR (TREE_OPERAND (t, 0)),
13064                                         RECUR (MUST_NOT_THROW_COND (t)));
13065
13066     case EXPR_PACK_EXPANSION:
13067       error ("invalid use of pack expansion expression");
13068       return error_mark_node;
13069
13070     case NONTYPE_ARGUMENT_PACK:
13071       error ("use %<...%> to expand argument pack");
13072       return error_mark_node;
13073
13074     default:
13075       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
13076
13077       return tsubst_copy_and_build (t, args, complain, in_decl,
13078                                     /*function_p=*/false,
13079                                     integral_constant_expression_p);
13080     }
13081
13082   return NULL_TREE;
13083 #undef RECUR
13084 }
13085
13086 /* T is a postfix-expression that is not being used in a function
13087    call.  Return the substituted version of T.  */
13088
13089 static tree
13090 tsubst_non_call_postfix_expression (tree t, tree args,
13091                                     tsubst_flags_t complain,
13092                                     tree in_decl)
13093 {
13094   if (TREE_CODE (t) == SCOPE_REF)
13095     t = tsubst_qualified_id (t, args, complain, in_decl,
13096                              /*done=*/false, /*address_p=*/false);
13097   else
13098     t = tsubst_copy_and_build (t, args, complain, in_decl,
13099                                /*function_p=*/false,
13100                                /*integral_constant_expression_p=*/false);
13101
13102   return t;
13103 }
13104
13105 /* Like tsubst but deals with expressions and performs semantic
13106    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
13107
13108 tree
13109 tsubst_copy_and_build (tree t,
13110                        tree args,
13111                        tsubst_flags_t complain,
13112                        tree in_decl,
13113                        bool function_p,
13114                        bool integral_constant_expression_p)
13115 {
13116 #define RECUR(NODE)                                             \
13117   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
13118                          /*function_p=*/false,                  \
13119                          integral_constant_expression_p)
13120
13121   tree op1;
13122
13123   if (t == NULL_TREE || t == error_mark_node)
13124     return t;
13125
13126   switch (TREE_CODE (t))
13127     {
13128     case USING_DECL:
13129       t = DECL_NAME (t);
13130       /* Fall through.  */
13131     case IDENTIFIER_NODE:
13132       {
13133         tree decl;
13134         cp_id_kind idk;
13135         bool non_integral_constant_expression_p;
13136         const char *error_msg;
13137
13138         if (IDENTIFIER_TYPENAME_P (t))
13139           {
13140             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13141             t = mangle_conv_op_name_for_type (new_type);
13142           }
13143
13144         /* Look up the name.  */
13145         decl = lookup_name (t);
13146
13147         /* By convention, expressions use ERROR_MARK_NODE to indicate
13148            failure, not NULL_TREE.  */
13149         if (decl == NULL_TREE)
13150           decl = error_mark_node;
13151
13152         decl = finish_id_expression (t, decl, NULL_TREE,
13153                                      &idk,
13154                                      integral_constant_expression_p,
13155           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx0x),
13156                                      &non_integral_constant_expression_p,
13157                                      /*template_p=*/false,
13158                                      /*done=*/true,
13159                                      /*address_p=*/false,
13160                                      /*template_arg_p=*/false,
13161                                      &error_msg,
13162                                      input_location);
13163         if (error_msg)
13164           error (error_msg);
13165         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13166           {
13167             if (complain & tf_error)
13168               unqualified_name_lookup_error (decl);
13169             decl = error_mark_node;
13170           }
13171         return decl;
13172       }
13173
13174     case TEMPLATE_ID_EXPR:
13175       {
13176         tree object;
13177         tree templ = RECUR (TREE_OPERAND (t, 0));
13178         tree targs = TREE_OPERAND (t, 1);
13179
13180         if (targs)
13181           targs = tsubst_template_args (targs, args, complain, in_decl);
13182
13183         if (TREE_CODE (templ) == COMPONENT_REF)
13184           {
13185             object = TREE_OPERAND (templ, 0);
13186             templ = TREE_OPERAND (templ, 1);
13187           }
13188         else
13189           object = NULL_TREE;
13190         templ = lookup_template_function (templ, targs);
13191
13192         if (object)
13193           return build3 (COMPONENT_REF, TREE_TYPE (templ),
13194                          object, templ, NULL_TREE);
13195         else
13196           return baselink_for_fns (templ);
13197       }
13198
13199     case INDIRECT_REF:
13200       {
13201         tree r = RECUR (TREE_OPERAND (t, 0));
13202
13203         if (REFERENCE_REF_P (t))
13204           {
13205             /* A type conversion to reference type will be enclosed in
13206                such an indirect ref, but the substitution of the cast
13207                will have also added such an indirect ref.  */
13208             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13209               r = convert_from_reference (r);
13210           }
13211         else
13212           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
13213         return r;
13214       }
13215
13216     case NOP_EXPR:
13217       return build_nop
13218         (tsubst (TREE_TYPE (t), args, complain, in_decl),
13219          RECUR (TREE_OPERAND (t, 0)));
13220
13221     case IMPLICIT_CONV_EXPR:
13222       {
13223         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13224         tree expr = RECUR (TREE_OPERAND (t, 0));
13225         int flags = LOOKUP_IMPLICIT;
13226         if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13227           flags = LOOKUP_NORMAL;
13228         return perform_implicit_conversion_flags (type, expr, complain,
13229                                                   flags);
13230       }
13231
13232     case CONVERT_EXPR:
13233       return build1
13234         (CONVERT_EXPR,
13235          tsubst (TREE_TYPE (t), args, complain, in_decl),
13236          RECUR (TREE_OPERAND (t, 0)));
13237
13238     case CAST_EXPR:
13239     case REINTERPRET_CAST_EXPR:
13240     case CONST_CAST_EXPR:
13241     case DYNAMIC_CAST_EXPR:
13242     case STATIC_CAST_EXPR:
13243       {
13244         tree type;
13245         tree op;
13246
13247         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13248         if (integral_constant_expression_p
13249             && !cast_valid_in_integral_constant_expression_p (type))
13250           {
13251             if (complain & tf_error)
13252               error ("a cast to a type other than an integral or "
13253                      "enumeration type cannot appear in a constant-expression");
13254             return error_mark_node; 
13255           }
13256
13257         op = RECUR (TREE_OPERAND (t, 0));
13258
13259         switch (TREE_CODE (t))
13260           {
13261           case CAST_EXPR:
13262             return build_functional_cast (type, op, complain);
13263           case REINTERPRET_CAST_EXPR:
13264             return build_reinterpret_cast (type, op, complain);
13265           case CONST_CAST_EXPR:
13266             return build_const_cast (type, op, complain);
13267           case DYNAMIC_CAST_EXPR:
13268             return build_dynamic_cast (type, op, complain);
13269           case STATIC_CAST_EXPR:
13270             return build_static_cast (type, op, complain);
13271           default:
13272             gcc_unreachable ();
13273           }
13274       }
13275
13276     case POSTDECREMENT_EXPR:
13277     case POSTINCREMENT_EXPR:
13278       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13279                                                 args, complain, in_decl);
13280       return build_x_unary_op (TREE_CODE (t), op1, complain);
13281
13282     case PREDECREMENT_EXPR:
13283     case PREINCREMENT_EXPR:
13284     case NEGATE_EXPR:
13285     case BIT_NOT_EXPR:
13286     case ABS_EXPR:
13287     case TRUTH_NOT_EXPR:
13288     case UNARY_PLUS_EXPR:  /* Unary + */
13289     case REALPART_EXPR:
13290     case IMAGPART_EXPR:
13291       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
13292                                complain);
13293
13294     case FIX_TRUNC_EXPR:
13295       return cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
13296                                 0, complain);
13297
13298     case ADDR_EXPR:
13299       op1 = TREE_OPERAND (t, 0);
13300       if (TREE_CODE (op1) == LABEL_DECL)
13301         return finish_label_address_expr (DECL_NAME (op1),
13302                                           EXPR_LOCATION (op1));
13303       if (TREE_CODE (op1) == SCOPE_REF)
13304         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13305                                    /*done=*/true, /*address_p=*/true);
13306       else
13307         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13308                                                   in_decl);
13309       return build_x_unary_op (ADDR_EXPR, op1, complain);
13310
13311     case PLUS_EXPR:
13312     case MINUS_EXPR:
13313     case MULT_EXPR:
13314     case TRUNC_DIV_EXPR:
13315     case CEIL_DIV_EXPR:
13316     case FLOOR_DIV_EXPR:
13317     case ROUND_DIV_EXPR:
13318     case EXACT_DIV_EXPR:
13319     case BIT_AND_EXPR:
13320     case BIT_IOR_EXPR:
13321     case BIT_XOR_EXPR:
13322     case TRUNC_MOD_EXPR:
13323     case FLOOR_MOD_EXPR:
13324     case TRUTH_ANDIF_EXPR:
13325     case TRUTH_ORIF_EXPR:
13326     case TRUTH_AND_EXPR:
13327     case TRUTH_OR_EXPR:
13328     case RSHIFT_EXPR:
13329     case LSHIFT_EXPR:
13330     case RROTATE_EXPR:
13331     case LROTATE_EXPR:
13332     case EQ_EXPR:
13333     case NE_EXPR:
13334     case MAX_EXPR:
13335     case MIN_EXPR:
13336     case LE_EXPR:
13337     case GE_EXPR:
13338     case LT_EXPR:
13339     case GT_EXPR:
13340     case MEMBER_REF:
13341     case DOTSTAR_EXPR:
13342       {
13343         tree r = build_x_binary_op
13344           (TREE_CODE (t),
13345            RECUR (TREE_OPERAND (t, 0)),
13346            (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13347             ? ERROR_MARK
13348             : TREE_CODE (TREE_OPERAND (t, 0))),
13349            RECUR (TREE_OPERAND (t, 1)),
13350            (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13351             ? ERROR_MARK
13352             : TREE_CODE (TREE_OPERAND (t, 1))),
13353            /*overload=*/NULL,
13354            complain);
13355         if (EXPR_P (r) && TREE_NO_WARNING (t))
13356           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13357         return r;
13358       }
13359
13360     case SCOPE_REF:
13361       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13362                                   /*address_p=*/false);
13363     case ARRAY_REF:
13364       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13365                                                 args, complain, in_decl);
13366       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
13367
13368     case SIZEOF_EXPR:
13369       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13370         return tsubst_copy (t, args, complain, in_decl);
13371       /* Fall through */
13372       
13373     case ALIGNOF_EXPR:
13374       op1 = TREE_OPERAND (t, 0);
13375       if (!args)
13376         {
13377           /* When there are no ARGS, we are trying to evaluate a
13378              non-dependent expression from the parser.  Trying to do
13379              the substitutions may not work.  */
13380           if (!TYPE_P (op1))
13381             op1 = TREE_TYPE (op1);
13382         }
13383       else
13384         {
13385           ++cp_unevaluated_operand;
13386           ++c_inhibit_evaluation_warnings;
13387           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13388                                        /*function_p=*/false,
13389                                        /*integral_constant_expression_p=*/false);
13390           --cp_unevaluated_operand;
13391           --c_inhibit_evaluation_warnings;
13392         }
13393       if (TYPE_P (op1))
13394         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
13395                                            complain & tf_error);
13396       else
13397         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
13398                                            complain & tf_error);
13399
13400     case AT_ENCODE_EXPR:
13401       {
13402         op1 = TREE_OPERAND (t, 0);
13403         ++cp_unevaluated_operand;
13404         ++c_inhibit_evaluation_warnings;
13405         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13406                                      /*function_p=*/false,
13407                                      /*integral_constant_expression_p=*/false);
13408         --cp_unevaluated_operand;
13409         --c_inhibit_evaluation_warnings;
13410         return objc_build_encode_expr (op1);
13411       }
13412
13413     case NOEXCEPT_EXPR:
13414       op1 = TREE_OPERAND (t, 0);
13415       ++cp_unevaluated_operand;
13416       ++c_inhibit_evaluation_warnings;
13417       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13418                                    /*function_p=*/false,
13419                                    /*integral_constant_expression_p=*/false);
13420       --cp_unevaluated_operand;
13421       --c_inhibit_evaluation_warnings;
13422       return finish_noexcept_expr (op1, complain);
13423
13424     case MODOP_EXPR:
13425       {
13426         tree r = build_x_modify_expr
13427           (RECUR (TREE_OPERAND (t, 0)),
13428            TREE_CODE (TREE_OPERAND (t, 1)),
13429            RECUR (TREE_OPERAND (t, 2)),
13430            complain);
13431         /* TREE_NO_WARNING must be set if either the expression was
13432            parenthesized or it uses an operator such as >>= rather
13433            than plain assignment.  In the former case, it was already
13434            set and must be copied.  In the latter case,
13435            build_x_modify_expr sets it and it must not be reset
13436            here.  */
13437         if (TREE_NO_WARNING (t))
13438           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13439         return r;
13440       }
13441
13442     case ARROW_EXPR:
13443       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13444                                                 args, complain, in_decl);
13445       /* Remember that there was a reference to this entity.  */
13446       if (DECL_P (op1))
13447         mark_used (op1);
13448       return build_x_arrow (op1);
13449
13450     case NEW_EXPR:
13451       {
13452         tree placement = RECUR (TREE_OPERAND (t, 0));
13453         tree init = RECUR (TREE_OPERAND (t, 3));
13454         VEC(tree,gc) *placement_vec;
13455         VEC(tree,gc) *init_vec;
13456         tree ret;
13457
13458         if (placement == NULL_TREE)
13459           placement_vec = NULL;
13460         else
13461           {
13462             placement_vec = make_tree_vector ();
13463             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13464               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
13465           }
13466
13467         /* If there was an initializer in the original tree, but it
13468            instantiated to an empty list, then we should pass a
13469            non-NULL empty vector to tell build_new that it was an
13470            empty initializer() rather than no initializer.  This can
13471            only happen when the initializer is a pack expansion whose
13472            parameter packs are of length zero.  */
13473         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13474           init_vec = NULL;
13475         else
13476           {
13477             init_vec = make_tree_vector ();
13478             if (init == void_zero_node)
13479               gcc_assert (init_vec != NULL);
13480             else
13481               {
13482                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
13483                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
13484               }
13485           }
13486
13487         ret = build_new (&placement_vec,
13488                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13489                          RECUR (TREE_OPERAND (t, 2)),
13490                          &init_vec,
13491                          NEW_EXPR_USE_GLOBAL (t),
13492                          complain);
13493
13494         if (placement_vec != NULL)
13495           release_tree_vector (placement_vec);
13496         if (init_vec != NULL)
13497           release_tree_vector (init_vec);
13498
13499         return ret;
13500       }
13501
13502     case DELETE_EXPR:
13503      return delete_sanity
13504        (RECUR (TREE_OPERAND (t, 0)),
13505         RECUR (TREE_OPERAND (t, 1)),
13506         DELETE_EXPR_USE_VEC (t),
13507         DELETE_EXPR_USE_GLOBAL (t),
13508         complain);
13509
13510     case COMPOUND_EXPR:
13511       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
13512                                     RECUR (TREE_OPERAND (t, 1)),
13513                                     complain);
13514
13515     case CALL_EXPR:
13516       {
13517         tree function;
13518         VEC(tree,gc) *call_args;
13519         unsigned int nargs, i;
13520         bool qualified_p;
13521         bool koenig_p;
13522         tree ret;
13523
13524         function = CALL_EXPR_FN (t);
13525         /* When we parsed the expression,  we determined whether or
13526            not Koenig lookup should be performed.  */
13527         koenig_p = KOENIG_LOOKUP_P (t);
13528         if (TREE_CODE (function) == SCOPE_REF)
13529           {
13530             qualified_p = true;
13531             function = tsubst_qualified_id (function, args, complain, in_decl,
13532                                             /*done=*/false,
13533                                             /*address_p=*/false);
13534           }
13535         else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13536           {
13537             /* Do nothing; calling tsubst_copy_and_build on an identifier
13538                would incorrectly perform unqualified lookup again.
13539
13540                Note that we can also have an IDENTIFIER_NODE if the earlier
13541                unqualified lookup found a member function; in that case
13542                koenig_p will be false and we do want to do the lookup
13543                again to find the instantiated member function.
13544
13545                FIXME but doing that causes c++/15272, so we need to stop
13546                using IDENTIFIER_NODE in that situation.  */
13547             qualified_p = false;
13548           }
13549         else
13550           {
13551             if (TREE_CODE (function) == COMPONENT_REF)
13552               {
13553                 tree op = TREE_OPERAND (function, 1);
13554
13555                 qualified_p = (TREE_CODE (op) == SCOPE_REF
13556                                || (BASELINK_P (op)
13557                                    && BASELINK_QUALIFIED_P (op)));
13558               }
13559             else
13560               qualified_p = false;
13561
13562             function = tsubst_copy_and_build (function, args, complain,
13563                                               in_decl,
13564                                               !qualified_p,
13565                                               integral_constant_expression_p);
13566
13567             if (BASELINK_P (function))
13568               qualified_p = true;
13569           }
13570
13571         nargs = call_expr_nargs (t);
13572         call_args = make_tree_vector ();
13573         for (i = 0; i < nargs; ++i)
13574           {
13575             tree arg = CALL_EXPR_ARG (t, i);
13576
13577             if (!PACK_EXPANSION_P (arg))
13578               VEC_safe_push (tree, gc, call_args,
13579                              RECUR (CALL_EXPR_ARG (t, i)));
13580             else
13581               {
13582                 /* Expand the pack expansion and push each entry onto
13583                    CALL_ARGS.  */
13584                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13585                 if (TREE_CODE (arg) == TREE_VEC)
13586                   {
13587                     unsigned int len, j;
13588
13589                     len = TREE_VEC_LENGTH (arg);
13590                     for (j = 0; j < len; ++j)
13591                       {
13592                         tree value = TREE_VEC_ELT (arg, j);
13593                         if (value != NULL_TREE)
13594                           value = convert_from_reference (value);
13595                         VEC_safe_push (tree, gc, call_args, value);
13596                       }
13597                   }
13598                 else
13599                   {
13600                     /* A partial substitution.  Add one entry.  */
13601                     VEC_safe_push (tree, gc, call_args, arg);
13602                   }
13603               }
13604           }
13605
13606         /* We do not perform argument-dependent lookup if normal
13607            lookup finds a non-function, in accordance with the
13608            expected resolution of DR 218.  */
13609         if (koenig_p
13610             && ((is_overloaded_fn (function)
13611                  /* If lookup found a member function, the Koenig lookup is
13612                     not appropriate, even if an unqualified-name was used
13613                     to denote the function.  */
13614                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
13615                 || TREE_CODE (function) == IDENTIFIER_NODE)
13616             /* Only do this when substitution turns a dependent call
13617                into a non-dependent call.  */
13618             && type_dependent_expression_p_push (t)
13619             && !any_type_dependent_arguments_p (call_args))
13620           function = perform_koenig_lookup (function, call_args, false,
13621                                             tf_none);
13622
13623         if (TREE_CODE (function) == IDENTIFIER_NODE
13624             && !any_type_dependent_arguments_p (call_args))
13625           {
13626             if (koenig_p && (complain & tf_warning_or_error))
13627               {
13628                 /* For backwards compatibility and good diagnostics, try
13629                    the unqualified lookup again if we aren't in SFINAE
13630                    context.  */
13631                 tree unq = (tsubst_copy_and_build
13632                             (function, args, complain, in_decl, true,
13633                              integral_constant_expression_p));
13634                 if (unq == error_mark_node)
13635                   return error_mark_node;
13636
13637                 if (unq != function)
13638                   {
13639                     tree fn = unq;
13640                     if (TREE_CODE (fn) == INDIRECT_REF)
13641                       fn = TREE_OPERAND (fn, 0);
13642                     if (TREE_CODE (fn) == COMPONENT_REF)
13643                       fn = TREE_OPERAND (fn, 1);
13644                     if (is_overloaded_fn (fn))
13645                       fn = get_first_fn (fn);
13646                     permerror (EXPR_LOC_OR_HERE (t),
13647                                "%qD was not declared in this scope, "
13648                                "and no declarations were found by "
13649                                "argument-dependent lookup at the point "
13650                                "of instantiation", function);
13651                     if (!DECL_P (fn))
13652                       /* Can't say anything more.  */;
13653                     else if (DECL_CLASS_SCOPE_P (fn))
13654                       {
13655                         inform (EXPR_LOC_OR_HERE (t),
13656                                 "declarations in dependent base %qT are "
13657                                 "not found by unqualified lookup",
13658                                 DECL_CLASS_CONTEXT (fn));
13659                         if (current_class_ptr)
13660                           inform (EXPR_LOC_OR_HERE (t),
13661                                   "use %<this->%D%> instead", function);
13662                         else
13663                           inform (EXPR_LOC_OR_HERE (t),
13664                                   "use %<%T::%D%> instead",
13665                                   current_class_name, function);
13666                       }
13667                     else
13668                       inform (0, "%q+D declared here, later in the "
13669                                 "translation unit", fn);
13670                     function = unq;
13671                   }
13672               }
13673             if (TREE_CODE (function) == IDENTIFIER_NODE)
13674               {
13675                 unqualified_name_lookup_error (function);
13676                 release_tree_vector (call_args);
13677                 return error_mark_node;
13678               }
13679           }
13680
13681         /* Remember that there was a reference to this entity.  */
13682         if (DECL_P (function))
13683           mark_used (function);
13684
13685         if (TREE_CODE (function) == OFFSET_REF)
13686           ret = build_offset_ref_call_from_tree (function, &call_args);
13687         else if (TREE_CODE (function) == COMPONENT_REF)
13688           {
13689             tree instance = TREE_OPERAND (function, 0);
13690             tree fn = TREE_OPERAND (function, 1);
13691
13692             if (processing_template_decl
13693                 && (type_dependent_expression_p (instance)
13694                     || (!BASELINK_P (fn)
13695                         && TREE_CODE (fn) != FIELD_DECL)
13696                     || type_dependent_expression_p (fn)
13697                     || any_type_dependent_arguments_p (call_args)))
13698               ret = build_nt_call_vec (function, call_args);
13699             else if (!BASELINK_P (fn))
13700               ret = finish_call_expr (function, &call_args,
13701                                        /*disallow_virtual=*/false,
13702                                        /*koenig_p=*/false,
13703                                        complain);
13704             else
13705               ret = (build_new_method_call
13706                       (instance, fn,
13707                        &call_args, NULL_TREE,
13708                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
13709                        /*fn_p=*/NULL,
13710                        complain));
13711           }
13712         else
13713           ret = finish_call_expr (function, &call_args,
13714                                   /*disallow_virtual=*/qualified_p,
13715                                   koenig_p,
13716                                   complain);
13717
13718         release_tree_vector (call_args);
13719
13720         return ret;
13721       }
13722
13723     case COND_EXPR:
13724       return build_x_conditional_expr
13725         (RECUR (TREE_OPERAND (t, 0)),
13726          RECUR (TREE_OPERAND (t, 1)),
13727          RECUR (TREE_OPERAND (t, 2)),
13728          complain);
13729
13730     case PSEUDO_DTOR_EXPR:
13731       return finish_pseudo_destructor_expr
13732         (RECUR (TREE_OPERAND (t, 0)),
13733          RECUR (TREE_OPERAND (t, 1)),
13734          tsubst (TREE_OPERAND (t, 2), args, complain, in_decl));
13735
13736     case TREE_LIST:
13737       {
13738         tree purpose, value, chain;
13739
13740         if (t == void_list_node)
13741           return t;
13742
13743         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
13744             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
13745           {
13746             /* We have pack expansions, so expand those and
13747                create a new list out of it.  */
13748             tree purposevec = NULL_TREE;
13749             tree valuevec = NULL_TREE;
13750             tree chain;
13751             int i, len = -1;
13752
13753             /* Expand the argument expressions.  */
13754             if (TREE_PURPOSE (t))
13755               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
13756                                                  complain, in_decl);
13757             if (TREE_VALUE (t))
13758               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
13759                                                complain, in_decl);
13760
13761             /* Build the rest of the list.  */
13762             chain = TREE_CHAIN (t);
13763             if (chain && chain != void_type_node)
13764               chain = RECUR (chain);
13765
13766             /* Determine the number of arguments.  */
13767             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
13768               {
13769                 len = TREE_VEC_LENGTH (purposevec);
13770                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
13771               }
13772             else if (TREE_CODE (valuevec) == TREE_VEC)
13773               len = TREE_VEC_LENGTH (valuevec);
13774             else
13775               {
13776                 /* Since we only performed a partial substitution into
13777                    the argument pack, we only return a single list
13778                    node.  */
13779                 if (purposevec == TREE_PURPOSE (t)
13780                     && valuevec == TREE_VALUE (t)
13781                     && chain == TREE_CHAIN (t))
13782                   return t;
13783
13784                 return tree_cons (purposevec, valuevec, chain);
13785               }
13786             
13787             /* Convert the argument vectors into a TREE_LIST */
13788             i = len;
13789             while (i > 0)
13790               {
13791                 /* Grab the Ith values.  */
13792                 i--;
13793                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13794                                      : NULL_TREE;
13795                 value 
13796                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13797                              : NULL_TREE;
13798
13799                 /* Build the list (backwards).  */
13800                 chain = tree_cons (purpose, value, chain);
13801               }
13802
13803             return chain;
13804           }
13805
13806         purpose = TREE_PURPOSE (t);
13807         if (purpose)
13808           purpose = RECUR (purpose);
13809         value = TREE_VALUE (t);
13810         if (value)
13811           value = RECUR (value);
13812         chain = TREE_CHAIN (t);
13813         if (chain && chain != void_type_node)
13814           chain = RECUR (chain);
13815         if (purpose == TREE_PURPOSE (t)
13816             && value == TREE_VALUE (t)
13817             && chain == TREE_CHAIN (t))
13818           return t;
13819         return tree_cons (purpose, value, chain);
13820       }
13821
13822     case COMPONENT_REF:
13823       {
13824         tree object;
13825         tree object_type;
13826         tree member;
13827
13828         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13829                                                      args, complain, in_decl);
13830         /* Remember that there was a reference to this entity.  */
13831         if (DECL_P (object))
13832           mark_used (object);
13833         object_type = TREE_TYPE (object);
13834
13835         member = TREE_OPERAND (t, 1);
13836         if (BASELINK_P (member))
13837           member = tsubst_baselink (member,
13838                                     non_reference (TREE_TYPE (object)),
13839                                     args, complain, in_decl);
13840         else
13841           member = tsubst_copy (member, args, complain, in_decl);
13842         if (member == error_mark_node)
13843           return error_mark_node;
13844
13845         if (type_dependent_expression_p (object))
13846           /* We can't do much here.  */;
13847         else if (!CLASS_TYPE_P (object_type))
13848           {
13849             if (SCALAR_TYPE_P (object_type))
13850               {
13851                 tree s = NULL_TREE;
13852                 tree dtor = member;
13853
13854                 if (TREE_CODE (dtor) == SCOPE_REF)
13855                   {
13856                     s = TREE_OPERAND (dtor, 0);
13857                     dtor = TREE_OPERAND (dtor, 1);
13858                   }
13859                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13860                   {
13861                     dtor = TREE_OPERAND (dtor, 0);
13862                     if (TYPE_P (dtor))
13863                       return finish_pseudo_destructor_expr (object, s, dtor);
13864                   }
13865               }
13866           }
13867         else if (TREE_CODE (member) == SCOPE_REF
13868                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13869           {
13870             /* Lookup the template functions now that we know what the
13871                scope is.  */
13872             tree scope = TREE_OPERAND (member, 0);
13873             tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13874             tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13875             member = lookup_qualified_name (scope, tmpl,
13876                                             /*is_type_p=*/false,
13877                                             /*complain=*/false);
13878             if (BASELINK_P (member))
13879               {
13880                 BASELINK_FUNCTIONS (member)
13881                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13882                               args);
13883                 member = (adjust_result_of_qualified_name_lookup
13884                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13885                            object_type));
13886               }
13887             else
13888               {
13889                 qualified_name_lookup_error (scope, tmpl, member,
13890                                              input_location);
13891                 return error_mark_node;
13892               }
13893           }
13894         else if (TREE_CODE (member) == SCOPE_REF
13895                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13896                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13897           {
13898             if (complain & tf_error)
13899               {
13900                 if (TYPE_P (TREE_OPERAND (member, 0)))
13901                   error ("%qT is not a class or namespace",
13902                          TREE_OPERAND (member, 0));
13903                 else
13904                   error ("%qD is not a class or namespace",
13905                          TREE_OPERAND (member, 0));
13906               }
13907             return error_mark_node;
13908           }
13909         else if (TREE_CODE (member) == FIELD_DECL)
13910           return finish_non_static_data_member (member, object, NULL_TREE);
13911
13912         return finish_class_member_access_expr (object, member,
13913                                                 /*template_p=*/false,
13914                                                 complain);
13915       }
13916
13917     case THROW_EXPR:
13918       return build_throw
13919         (RECUR (TREE_OPERAND (t, 0)));
13920
13921     case CONSTRUCTOR:
13922       {
13923         VEC(constructor_elt,gc) *n;
13924         constructor_elt *ce;
13925         unsigned HOST_WIDE_INT idx;
13926         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13927         bool process_index_p;
13928         int newlen;
13929         bool need_copy_p = false;
13930         tree r;
13931
13932         if (type == error_mark_node)
13933           return error_mark_node;
13934
13935         /* digest_init will do the wrong thing if we let it.  */
13936         if (type && TYPE_PTRMEMFUNC_P (type))
13937           return t;
13938
13939         /* We do not want to process the index of aggregate
13940            initializers as they are identifier nodes which will be
13941            looked up by digest_init.  */
13942         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13943
13944         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13945         newlen = VEC_length (constructor_elt, n);
13946         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13947           {
13948             if (ce->index && process_index_p)
13949               ce->index = RECUR (ce->index);
13950
13951             if (PACK_EXPANSION_P (ce->value))
13952               {
13953                 /* Substitute into the pack expansion.  */
13954                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13955                                                   in_decl);
13956
13957                 if (ce->value == error_mark_node
13958                     || PACK_EXPANSION_P (ce->value))
13959                   ;
13960                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13961                   /* Just move the argument into place.  */
13962                   ce->value = TREE_VEC_ELT (ce->value, 0);
13963                 else
13964                   {
13965                     /* Update the length of the final CONSTRUCTOR
13966                        arguments vector, and note that we will need to
13967                        copy.*/
13968                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13969                     need_copy_p = true;
13970                   }
13971               }
13972             else
13973               ce->value = RECUR (ce->value);
13974           }
13975
13976         if (need_copy_p)
13977           {
13978             VEC(constructor_elt,gc) *old_n = n;
13979
13980             n = VEC_alloc (constructor_elt, gc, newlen);
13981             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13982               {
13983                 if (TREE_CODE (ce->value) == TREE_VEC)
13984                   {
13985                     int i, len = TREE_VEC_LENGTH (ce->value);
13986                     for (i = 0; i < len; ++i)
13987                       CONSTRUCTOR_APPEND_ELT (n, 0,
13988                                               TREE_VEC_ELT (ce->value, i));
13989                   }
13990                 else
13991                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13992               }
13993           }
13994
13995         r = build_constructor (init_list_type_node, n);
13996         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13997
13998         if (TREE_HAS_CONSTRUCTOR (t))
13999           return finish_compound_literal (type, r, complain);
14000
14001         TREE_TYPE (r) = type;
14002         return r;
14003       }
14004
14005     case TYPEID_EXPR:
14006       {
14007         tree operand_0 = TREE_OPERAND (t, 0);
14008         if (TYPE_P (operand_0))
14009           {
14010             operand_0 = tsubst (operand_0, args, complain, in_decl);
14011             return get_typeid (operand_0);
14012           }
14013         else
14014           {
14015             operand_0 = RECUR (operand_0);
14016             return build_typeid (operand_0);
14017           }
14018       }
14019
14020     case VAR_DECL:
14021       if (!args)
14022         return t;
14023       /* Fall through */
14024
14025     case PARM_DECL:
14026       {
14027         tree r = tsubst_copy (t, args, complain, in_decl);
14028
14029         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
14030           /* If the original type was a reference, we'll be wrapped in
14031              the appropriate INDIRECT_REF.  */
14032           r = convert_from_reference (r);
14033         return r;
14034       }
14035
14036     case VA_ARG_EXPR:
14037       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
14038                              tsubst (TREE_TYPE (t), args, complain, in_decl));
14039
14040     case OFFSETOF_EXPR:
14041       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
14042
14043     case TRAIT_EXPR:
14044       {
14045         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
14046                                   complain, in_decl);
14047
14048         tree type2 = TRAIT_EXPR_TYPE2 (t);
14049         if (type2)
14050           type2 = tsubst_copy (type2, args, complain, in_decl);
14051         
14052         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
14053       }
14054
14055     case STMT_EXPR:
14056       {
14057         tree old_stmt_expr = cur_stmt_expr;
14058         tree stmt_expr = begin_stmt_expr ();
14059
14060         cur_stmt_expr = stmt_expr;
14061         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
14062                      integral_constant_expression_p);
14063         stmt_expr = finish_stmt_expr (stmt_expr, false);
14064         cur_stmt_expr = old_stmt_expr;
14065
14066         /* If the resulting list of expression statement is empty,
14067            fold it further into void_zero_node.  */
14068         if (empty_expr_stmt_p (stmt_expr))
14069           stmt_expr = void_zero_node;
14070
14071         return stmt_expr;
14072       }
14073
14074     case CONST_DECL:
14075       t = tsubst_copy (t, args, complain, in_decl);
14076       /* As in finish_id_expression, we resolve enumeration constants
14077          to their underlying values.  */
14078       if (TREE_CODE (t) == CONST_DECL && !processing_template_decl)
14079         {
14080           used_types_insert (TREE_TYPE (t));
14081           return DECL_INITIAL (t);
14082         }
14083       return t;
14084
14085     case LAMBDA_EXPR:
14086       {
14087         tree r = build_lambda_expr ();
14088
14089         tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
14090         LAMBDA_EXPR_CLOSURE (r) = type;
14091         CLASSTYPE_LAMBDA_EXPR (type) = r;
14092
14093         LAMBDA_EXPR_LOCATION (r)
14094           = LAMBDA_EXPR_LOCATION (t);
14095         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
14096           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
14097         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
14098         LAMBDA_EXPR_DISCRIMINATOR (r)
14099           = (LAMBDA_EXPR_DISCRIMINATOR (t));
14100         LAMBDA_EXPR_EXTRA_SCOPE (r)
14101           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
14102         if (LAMBDA_EXPR_RETURN_TYPE (t) == dependent_lambda_return_type_node)
14103           {
14104             LAMBDA_EXPR_RETURN_TYPE (r) = dependent_lambda_return_type_node;
14105             LAMBDA_EXPR_DEDUCE_RETURN_TYPE_P (r) = true;
14106           }
14107         else
14108           LAMBDA_EXPR_RETURN_TYPE (r)
14109             = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
14110
14111         gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
14112                     && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
14113
14114         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
14115         determine_visibility (TYPE_NAME (type));
14116         /* Now that we know visibility, instantiate the type so we have a
14117            declaration of the op() for later calls to lambda_function.  */
14118         complete_type (type);
14119
14120         /* The capture list refers to closure members, so this needs to
14121            wait until after we finish instantiating the type.  Also keep
14122            any captures that may have been added during instantiation.  */
14123         LAMBDA_EXPR_CAPTURE_LIST (r)
14124           = chainon (RECUR (LAMBDA_EXPR_CAPTURE_LIST (t)),
14125                      LAMBDA_EXPR_CAPTURE_LIST (r));
14126         LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
14127
14128         return build_lambda_object (r);
14129       }
14130
14131     case TARGET_EXPR:
14132       /* We can get here for a constant initializer of non-dependent type.
14133          FIXME stop folding in cp_parser_initializer_clause.  */
14134       {
14135         tree r = get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
14136         return r;
14137       }
14138
14139     case TRANSACTION_EXPR:
14140       return tsubst_expr(t, args, complain, in_decl,
14141              integral_constant_expression_p);
14142
14143     default:
14144       /* Handle Objective-C++ constructs, if appropriate.  */
14145       {
14146         tree subst
14147           = objcp_tsubst_copy_and_build (t, args, complain,
14148                                          in_decl, /*function_p=*/false);
14149         if (subst)
14150           return subst;
14151       }
14152       return tsubst_copy (t, args, complain, in_decl);
14153     }
14154
14155 #undef RECUR
14156 }
14157
14158 /* Verify that the instantiated ARGS are valid. For type arguments,
14159    make sure that the type's linkage is ok. For non-type arguments,
14160    make sure they are constants if they are integral or enumerations.
14161    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14162
14163 static bool
14164 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14165 {
14166   if (ARGUMENT_PACK_P (t))
14167     {
14168       tree vec = ARGUMENT_PACK_ARGS (t);
14169       int len = TREE_VEC_LENGTH (vec);
14170       bool result = false;
14171       int i;
14172
14173       for (i = 0; i < len; ++i)
14174         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14175           result = true;
14176       return result;
14177     }
14178   else if (TYPE_P (t))
14179     {
14180       /* [basic.link]: A name with no linkage (notably, the name
14181          of a class or enumeration declared in a local scope)
14182          shall not be used to declare an entity with linkage.
14183          This implies that names with no linkage cannot be used as
14184          template arguments
14185
14186          DR 757 relaxes this restriction for C++0x.  */
14187       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14188                  : no_linkage_check (t, /*relaxed_p=*/false));
14189
14190       if (nt)
14191         {
14192           /* DR 488 makes use of a type with no linkage cause
14193              type deduction to fail.  */
14194           if (complain & tf_error)
14195             {
14196               if (TYPE_ANONYMOUS_P (nt))
14197                 error ("%qT is/uses anonymous type", t);
14198               else
14199                 error ("template argument for %qD uses local type %qT",
14200                        tmpl, t);
14201             }
14202           return true;
14203         }
14204       /* In order to avoid all sorts of complications, we do not
14205          allow variably-modified types as template arguments.  */
14206       else if (variably_modified_type_p (t, NULL_TREE))
14207         {
14208           if (complain & tf_error)
14209             error ("%qT is a variably modified type", t);
14210           return true;
14211         }
14212     }
14213   /* A non-type argument of integral or enumerated type must be a
14214      constant.  */
14215   else if (TREE_TYPE (t)
14216            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14217            && !TREE_CONSTANT (t))
14218     {
14219       if (complain & tf_error)
14220         error ("integral expression %qE is not constant", t);
14221       return true;
14222     }
14223   return false;
14224 }
14225
14226 static bool
14227 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14228 {
14229   int ix, len = DECL_NTPARMS (tmpl);
14230   bool result = false;
14231
14232   for (ix = 0; ix != len; ix++)
14233     {
14234       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14235         result = true;
14236     }
14237   if (result && (complain & tf_error))
14238     error ("  trying to instantiate %qD", tmpl);
14239   return result;
14240 }
14241
14242 /* In C++0x, it's possible to have a function template whose type depends
14243    on itself recursively.  This is most obvious with decltype, but can also
14244    occur with enumeration scope (c++/48969).  So we need to catch infinite
14245    recursion and reject the substitution at deduction time; this function
14246    will return error_mark_node for any repeated substitution.
14247
14248    This also catches excessive recursion such as when f<N> depends on
14249    f<N-1> across all integers, and returns error_mark_node for all the
14250    substitutions back up to the initial one.
14251
14252    This is, of course, not reentrant.  */
14253
14254 static tree
14255 deduction_tsubst_fntype (tree fn, tree targs, tsubst_flags_t complain)
14256 {
14257   static bool excessive_deduction_depth;
14258   static int deduction_depth;
14259   struct pending_template *old_last_pend = last_pending_template;
14260   struct tinst_level *old_error_tinst = last_error_tinst_level;
14261
14262   tree fntype = TREE_TYPE (fn);
14263   tree tinst;
14264   tree r;
14265
14266   if (excessive_deduction_depth)
14267     return error_mark_node;
14268
14269   tinst = build_tree_list (fn, targs);
14270   if (!push_tinst_level (tinst))
14271     {
14272       excessive_deduction_depth = true;
14273       ggc_free (tinst);
14274       return error_mark_node;
14275     }
14276
14277   input_location = DECL_SOURCE_LOCATION (fn);
14278   ++deduction_depth;
14279   push_deduction_access_scope (fn);
14280   r = tsubst (fntype, targs, complain, NULL_TREE);
14281   pop_deduction_access_scope (fn);
14282   --deduction_depth;
14283
14284   if (excessive_deduction_depth)
14285     {
14286       r = error_mark_node;
14287       if (deduction_depth == 0)
14288         /* Reset once we're all the way out.  */
14289         excessive_deduction_depth = false;
14290     }
14291
14292   pop_tinst_level ();
14293   /* We can't free this if a pending_template entry or last_error_tinst_level
14294      is pointing at it.  */
14295   if (last_pending_template == old_last_pend
14296       && last_error_tinst_level == old_error_tinst)
14297     ggc_free (tinst);
14298   return r;
14299 }
14300
14301 /* Instantiate the indicated variable or function template TMPL with
14302    the template arguments in TARG_PTR.  */
14303
14304 static tree
14305 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14306 {
14307   tree targ_ptr = orig_args;
14308   tree fndecl;
14309   tree gen_tmpl;
14310   tree spec;
14311
14312   if (tmpl == error_mark_node)
14313     return error_mark_node;
14314
14315   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14316
14317   /* If this function is a clone, handle it specially.  */
14318   if (DECL_CLONED_FUNCTION_P (tmpl))
14319     {
14320       tree spec;
14321       tree clone;
14322
14323       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14324          DECL_CLONED_FUNCTION.  */
14325       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14326                                    targ_ptr, complain);
14327       if (spec == error_mark_node)
14328         return error_mark_node;
14329
14330       /* Look for the clone.  */
14331       FOR_EACH_CLONE (clone, spec)
14332         if (DECL_NAME (clone) == DECL_NAME (tmpl))
14333           return clone;
14334       /* We should always have found the clone by now.  */
14335       gcc_unreachable ();
14336       return NULL_TREE;
14337     }
14338
14339   /* Check to see if we already have this specialization.  */
14340   gen_tmpl = most_general_template (tmpl);
14341   if (tmpl != gen_tmpl)
14342     /* The TMPL is a partial instantiation.  To get a full set of
14343        arguments we must add the arguments used to perform the
14344        partial instantiation.  */
14345     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14346                                             targ_ptr);
14347
14348   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14349      but it doesn't seem to be on the hot path.  */
14350   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14351
14352   gcc_assert (tmpl == gen_tmpl
14353               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14354                   == spec)
14355               || fndecl == NULL_TREE);
14356
14357   if (spec != NULL_TREE)
14358     return spec;
14359
14360   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14361                                complain))
14362     return error_mark_node;
14363
14364   /* We are building a FUNCTION_DECL, during which the access of its
14365      parameters and return types have to be checked.  However this
14366      FUNCTION_DECL which is the desired context for access checking
14367      is not built yet.  We solve this chicken-and-egg problem by
14368      deferring all checks until we have the FUNCTION_DECL.  */
14369   push_deferring_access_checks (dk_deferred);
14370
14371   /* Instantiation of the function happens in the context of the function
14372      template, not the context of the overload resolution we're doing.  */
14373   push_to_top_level ();
14374   if (DECL_CLASS_SCOPE_P (gen_tmpl))
14375     {
14376       tree ctx = tsubst (DECL_CONTEXT (gen_tmpl), targ_ptr,
14377                          complain, gen_tmpl);
14378       push_nested_class (ctx);
14379     }
14380   /* Substitute template parameters to obtain the specialization.  */
14381   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14382                    targ_ptr, complain, gen_tmpl);
14383   if (DECL_CLASS_SCOPE_P (gen_tmpl))
14384     pop_nested_class ();
14385   pop_from_top_level ();
14386
14387   if (fndecl == error_mark_node)
14388     return error_mark_node;
14389
14390   /* Now we know the specialization, compute access previously
14391      deferred.  */
14392   push_access_scope (fndecl);
14393
14394   /* Some typedefs referenced from within the template code need to be access
14395      checked at template instantiation time, i.e now. These types were
14396      added to the template at parsing time. Let's get those and perfom
14397      the acces checks then.  */
14398   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
14399   perform_deferred_access_checks ();
14400   pop_access_scope (fndecl);
14401   pop_deferring_access_checks ();
14402
14403   /* The DECL_TI_TEMPLATE should always be the immediate parent
14404      template, not the most general template.  */
14405   DECL_TI_TEMPLATE (fndecl) = tmpl;
14406
14407   /* If we've just instantiated the main entry point for a function,
14408      instantiate all the alternate entry points as well.  We do this
14409      by cloning the instantiation of the main entry point, not by
14410      instantiating the template clones.  */
14411   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14412     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14413
14414   return fndecl;
14415 }
14416
14417 /* Wrapper for instantiate_template_1.  */
14418
14419 tree
14420 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14421 {
14422   tree ret;
14423   timevar_push (TV_TEMPLATE_INST);
14424   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14425   timevar_pop (TV_TEMPLATE_INST);
14426   return ret;
14427 }
14428
14429 /* We're going to do deduction substitution on the type of TMPL, a function
14430    template.  In C++11 mode, push into that access scope.  In C++03 mode,
14431    disable access checking.  */
14432
14433 static void
14434 push_deduction_access_scope (tree tmpl)
14435 {
14436   if (cxx_dialect >= cxx0x)
14437     {
14438       int ptd = processing_template_decl;
14439       push_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14440       /* Preserve processing_template_decl across push_to_top_level.  */
14441       if (ptd && !processing_template_decl)
14442         ++processing_template_decl;
14443     }
14444   else
14445     push_deferring_access_checks (dk_no_check);
14446 }
14447
14448 /* And pop back out.  */
14449
14450 static void
14451 pop_deduction_access_scope (tree tmpl)
14452 {
14453   if (cxx_dialect >= cxx0x)
14454     pop_access_scope (DECL_TEMPLATE_RESULT (tmpl));
14455   else
14456     pop_deferring_access_checks ();
14457 }
14458
14459 /* PARM is a template parameter pack for FN.  Returns true iff
14460    PARM is used in a deducible way in the argument list of FN.  */
14461
14462 static bool
14463 pack_deducible_p (tree parm, tree fn)
14464 {
14465   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14466   for (; t; t = TREE_CHAIN (t))
14467     {
14468       tree type = TREE_VALUE (t);
14469       tree packs;
14470       if (!PACK_EXPANSION_P (type))
14471         continue;
14472       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14473            packs; packs = TREE_CHAIN (packs))
14474         if (TREE_VALUE (packs) == parm)
14475           {
14476             /* The template parameter pack is used in a function parameter
14477                pack.  If this is the end of the parameter list, the
14478                template parameter pack is deducible.  */
14479             if (TREE_CHAIN (t) == void_list_node)
14480               return true;
14481             else
14482               /* Otherwise, not.  Well, it could be deduced from
14483                  a non-pack parameter, but doing so would end up with
14484                  a deduction mismatch, so don't bother.  */
14485               return false;
14486           }
14487     }
14488   /* The template parameter pack isn't used in any function parameter
14489      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14490   return true;
14491 }
14492
14493 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14494    NARGS elements of the arguments that are being used when calling
14495    it.  TARGS is a vector into which the deduced template arguments
14496    are placed.
14497
14498    Return zero for success, 2 for an incomplete match that doesn't resolve
14499    all the types, and 1 for complete failure.  An error message will be
14500    printed only for an incomplete match.
14501
14502    If FN is a conversion operator, or we are trying to produce a specific
14503    specialization, RETURN_TYPE is the return type desired.
14504
14505    The EXPLICIT_TARGS are explicit template arguments provided via a
14506    template-id.
14507
14508    The parameter STRICT is one of:
14509
14510    DEDUCE_CALL:
14511      We are deducing arguments for a function call, as in
14512      [temp.deduct.call].
14513
14514    DEDUCE_CONV:
14515      We are deducing arguments for a conversion function, as in
14516      [temp.deduct.conv].
14517
14518    DEDUCE_EXACT:
14519      We are deducing arguments when doing an explicit instantiation
14520      as in [temp.explicit], when determining an explicit specialization
14521      as in [temp.expl.spec], or when taking the address of a function
14522      template, as in [temp.deduct.funcaddr].  */
14523
14524 int
14525 fn_type_unification (tree fn,
14526                      tree explicit_targs,
14527                      tree targs,
14528                      const tree *args,
14529                      unsigned int nargs,
14530                      tree return_type,
14531                      unification_kind_t strict,
14532                      int flags,
14533                      bool explain_p)
14534 {
14535   tree parms;
14536   tree fntype;
14537   int result;
14538
14539   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14540
14541   fntype = TREE_TYPE (fn);
14542   if (explicit_targs)
14543     {
14544       /* [temp.deduct]
14545
14546          The specified template arguments must match the template
14547          parameters in kind (i.e., type, nontype, template), and there
14548          must not be more arguments than there are parameters;
14549          otherwise type deduction fails.
14550
14551          Nontype arguments must match the types of the corresponding
14552          nontype template parameters, or must be convertible to the
14553          types of the corresponding nontype parameters as specified in
14554          _temp.arg.nontype_, otherwise type deduction fails.
14555
14556          All references in the function type of the function template
14557          to the corresponding template parameters are replaced by the
14558          specified template argument values.  If a substitution in a
14559          template parameter or in the function type of the function
14560          template results in an invalid type, type deduction fails.  */
14561       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14562       int i, len = TREE_VEC_LENGTH (tparms);
14563       tree converted_args;
14564       bool incomplete = false;
14565
14566       if (explicit_targs == error_mark_node)
14567         return unify_invalid (explain_p);
14568
14569       converted_args
14570         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
14571                                   (explain_p
14572                                    ? tf_warning_or_error
14573                                    : tf_none),
14574                                    /*require_all_args=*/false,
14575                                    /*use_default_args=*/false));
14576       if (converted_args == error_mark_node)
14577         return 1;
14578
14579       /* Substitute the explicit args into the function type.  This is
14580          necessary so that, for instance, explicitly declared function
14581          arguments can match null pointed constants.  If we were given
14582          an incomplete set of explicit args, we must not do semantic
14583          processing during substitution as we could create partial
14584          instantiations.  */
14585       for (i = 0; i < len; i++)
14586         {
14587           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14588           bool parameter_pack = false;
14589           tree targ = TREE_VEC_ELT (converted_args, i);
14590
14591           /* Dig out the actual parm.  */
14592           if (TREE_CODE (parm) == TYPE_DECL
14593               || TREE_CODE (parm) == TEMPLATE_DECL)
14594             {
14595               parm = TREE_TYPE (parm);
14596               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
14597             }
14598           else if (TREE_CODE (parm) == PARM_DECL)
14599             {
14600               parm = DECL_INITIAL (parm);
14601               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
14602             }
14603
14604           if (!parameter_pack && targ == NULL_TREE)
14605             /* No explicit argument for this template parameter.  */
14606             incomplete = true;
14607
14608           if (parameter_pack && pack_deducible_p (parm, fn))
14609             {
14610               /* Mark the argument pack as "incomplete". We could
14611                  still deduce more arguments during unification.
14612                  We remove this mark in type_unification_real.  */
14613               if (targ)
14614                 {
14615                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
14616                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
14617                     = ARGUMENT_PACK_ARGS (targ);
14618                 }
14619
14620               /* We have some incomplete argument packs.  */
14621               incomplete = true;
14622             }
14623         }
14624
14625       processing_template_decl += incomplete;
14626       fntype = deduction_tsubst_fntype (fn, converted_args,
14627                                         (explain_p
14628                                          ? tf_warning_or_error
14629                                          : tf_none));
14630       processing_template_decl -= incomplete;
14631
14632       if (fntype == error_mark_node)
14633         return 1;
14634
14635       /* Place the explicitly specified arguments in TARGS.  */
14636       for (i = NUM_TMPL_ARGS (converted_args); i--;)
14637         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
14638     }
14639
14640   /* Never do unification on the 'this' parameter.  */
14641   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
14642
14643   if (return_type)
14644     {
14645       tree *new_args;
14646
14647       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
14648       new_args = XALLOCAVEC (tree, nargs + 1);
14649       new_args[0] = return_type;
14650       memcpy (new_args + 1, args, nargs * sizeof (tree));
14651       args = new_args;
14652       ++nargs;
14653     }
14654
14655   /* We allow incomplete unification without an error message here
14656      because the standard doesn't seem to explicitly prohibit it.  Our
14657      callers must be ready to deal with unification failures in any
14658      event.  */
14659   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
14660                                   targs, parms, args, nargs, /*subr=*/0,
14661                                   strict, flags, explain_p);
14662
14663   /* Now that we have bindings for all of the template arguments,
14664      ensure that the arguments deduced for the template template
14665      parameters have compatible template parameter lists.  We cannot
14666      check this property before we have deduced all template
14667      arguments, because the template parameter types of a template
14668      template parameter might depend on prior template parameters
14669      deduced after the template template parameter.  The following
14670      ill-formed example illustrates this issue:
14671
14672        template<typename T, template<T> class C> void f(C<5>, T);
14673
14674        template<int N> struct X {};
14675
14676        void g() {
14677          f(X<5>(), 5l); // error: template argument deduction fails
14678        }
14679
14680      The template parameter list of 'C' depends on the template type
14681      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
14682      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
14683      time that we deduce 'C'.  */
14684   if (result == 0
14685       && !template_template_parm_bindings_ok_p 
14686            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
14687     return unify_inconsistent_template_template_parameters (explain_p);
14688
14689   if (result == 0)
14690     /* All is well so far.  Now, check:
14691
14692        [temp.deduct]
14693
14694        When all template arguments have been deduced, all uses of
14695        template parameters in nondeduced contexts are replaced with
14696        the corresponding deduced argument values.  If the
14697        substitution results in an invalid type, as described above,
14698        type deduction fails.  */
14699     {
14700       tree substed = deduction_tsubst_fntype (fn, targs,
14701                                               (explain_p
14702                                                ? tf_warning_or_error
14703                                                : tf_none));
14704       if (substed == error_mark_node)
14705         return 1;
14706
14707       /* If we're looking for an exact match, check that what we got
14708          is indeed an exact match.  It might not be if some template
14709          parameters are used in non-deduced contexts.  */
14710       if (strict == DEDUCE_EXACT)
14711         {
14712           unsigned int i;
14713
14714           tree sarg
14715             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
14716           if (return_type)
14717             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
14718           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
14719             if (!same_type_p (args[i], TREE_VALUE (sarg)))
14720               return unify_type_mismatch (explain_p, args[i],
14721                                           TREE_VALUE (sarg));
14722         }
14723     }
14724
14725   return result;
14726 }
14727
14728 /* Adjust types before performing type deduction, as described in
14729    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
14730    sections are symmetric.  PARM is the type of a function parameter
14731    or the return type of the conversion function.  ARG is the type of
14732    the argument passed to the call, or the type of the value
14733    initialized with the result of the conversion function.
14734    ARG_EXPR is the original argument expression, which may be null.  */
14735
14736 static int
14737 maybe_adjust_types_for_deduction (unification_kind_t strict,
14738                                   tree* parm,
14739                                   tree* arg,
14740                                   tree arg_expr)
14741 {
14742   int result = 0;
14743
14744   switch (strict)
14745     {
14746     case DEDUCE_CALL:
14747       break;
14748
14749     case DEDUCE_CONV:
14750       {
14751         /* Swap PARM and ARG throughout the remainder of this
14752            function; the handling is precisely symmetric since PARM
14753            will initialize ARG rather than vice versa.  */
14754         tree* temp = parm;
14755         parm = arg;
14756         arg = temp;
14757         break;
14758       }
14759
14760     case DEDUCE_EXACT:
14761       /* Core issue #873: Do the DR606 thing (see below) for these cases,
14762          too, but here handle it by stripping the reference from PARM
14763          rather than by adding it to ARG.  */
14764       if (TREE_CODE (*parm) == REFERENCE_TYPE
14765           && TYPE_REF_IS_RVALUE (*parm)
14766           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14767           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14768           && TREE_CODE (*arg) == REFERENCE_TYPE
14769           && !TYPE_REF_IS_RVALUE (*arg))
14770         *parm = TREE_TYPE (*parm);
14771       /* Nothing else to do in this case.  */
14772       return 0;
14773
14774     default:
14775       gcc_unreachable ();
14776     }
14777
14778   if (TREE_CODE (*parm) != REFERENCE_TYPE)
14779     {
14780       /* [temp.deduct.call]
14781
14782          If P is not a reference type:
14783
14784          --If A is an array type, the pointer type produced by the
14785          array-to-pointer standard conversion (_conv.array_) is
14786          used in place of A for type deduction; otherwise,
14787
14788          --If A is a function type, the pointer type produced by
14789          the function-to-pointer standard conversion
14790          (_conv.func_) is used in place of A for type deduction;
14791          otherwise,
14792
14793          --If A is a cv-qualified type, the top level
14794          cv-qualifiers of A's type are ignored for type
14795          deduction.  */
14796       if (TREE_CODE (*arg) == ARRAY_TYPE)
14797         *arg = build_pointer_type (TREE_TYPE (*arg));
14798       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
14799         *arg = build_pointer_type (*arg);
14800       else
14801         *arg = TYPE_MAIN_VARIANT (*arg);
14802     }
14803
14804   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
14805      of the form T&&, where T is a template parameter, and the argument
14806      is an lvalue, T is deduced as A& */
14807   if (TREE_CODE (*parm) == REFERENCE_TYPE
14808       && TYPE_REF_IS_RVALUE (*parm)
14809       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
14810       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
14811       && (arg_expr ? real_lvalue_p (arg_expr)
14812           /* try_one_overload doesn't provide an arg_expr, but
14813              functions are always lvalues.  */
14814           : TREE_CODE (*arg) == FUNCTION_TYPE))
14815     *arg = build_reference_type (*arg);
14816
14817   /* [temp.deduct.call]
14818
14819      If P is a cv-qualified type, the top level cv-qualifiers
14820      of P's type are ignored for type deduction.  If P is a
14821      reference type, the type referred to by P is used for
14822      type deduction.  */
14823   *parm = TYPE_MAIN_VARIANT (*parm);
14824   if (TREE_CODE (*parm) == REFERENCE_TYPE)
14825     {
14826       *parm = TREE_TYPE (*parm);
14827       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14828     }
14829
14830   /* DR 322. For conversion deduction, remove a reference type on parm
14831      too (which has been swapped into ARG).  */
14832   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
14833     *arg = TREE_TYPE (*arg);
14834
14835   return result;
14836 }
14837
14838 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
14839    template which does contain any deducible template parameters; check if
14840    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
14841    unify_one_argument.  */
14842
14843 static int
14844 check_non_deducible_conversion (tree parm, tree arg, int strict,
14845                                 int flags, bool explain_p)
14846 {
14847   tree type;
14848
14849   if (!TYPE_P (arg))
14850     type = TREE_TYPE (arg);
14851   else
14852     type = arg;
14853
14854   if (same_type_p (parm, type))
14855     return unify_success (explain_p);
14856
14857   if (strict == DEDUCE_CONV)
14858     {
14859       if (can_convert_arg (type, parm, NULL_TREE, flags))
14860         return unify_success (explain_p);
14861     }
14862   else if (strict != DEDUCE_EXACT)
14863     {
14864       if (can_convert_arg (parm, type,
14865                            TYPE_P (arg) ? NULL_TREE : arg,
14866                            flags))
14867         return unify_success (explain_p);
14868     }
14869
14870   if (strict == DEDUCE_EXACT)
14871     return unify_type_mismatch (explain_p, parm, arg);
14872   else
14873     return unify_arg_conversion (explain_p, parm, type, arg);
14874 }
14875
14876 /* Subroutine of type_unification_real and unify_pack_expansion to
14877    handle unification of a single P/A pair.  Parameters are as
14878    for those functions.  */
14879
14880 static int
14881 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
14882                     int subr, unification_kind_t strict, int flags,
14883                     bool explain_p)
14884 {
14885   tree arg_expr = NULL_TREE;
14886   int arg_strict;
14887
14888   if (arg == error_mark_node || parm == error_mark_node)
14889     return unify_invalid (explain_p);
14890   if (arg == unknown_type_node)
14891     /* We can't deduce anything from this, but we might get all the
14892        template args from other function args.  */
14893     return unify_success (explain_p);
14894
14895   /* FIXME uses_deducible_template_parms */
14896   if (TYPE_P (parm) && !uses_template_parms (parm))
14897     return check_non_deducible_conversion (parm, arg, strict, flags,
14898                                            explain_p);
14899
14900   switch (strict)
14901     {
14902     case DEDUCE_CALL:
14903       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
14904                     | UNIFY_ALLOW_MORE_CV_QUAL
14905                     | UNIFY_ALLOW_DERIVED);
14906       break;
14907
14908     case DEDUCE_CONV:
14909       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14910       break;
14911
14912     case DEDUCE_EXACT:
14913       arg_strict = UNIFY_ALLOW_NONE;
14914       break;
14915
14916     default:
14917       gcc_unreachable ();
14918     }
14919
14920   /* We only do these transformations if this is the top-level
14921      parameter_type_list in a call or declaration matching; in other
14922      situations (nested function declarators, template argument lists) we
14923      won't be comparing a type to an expression, and we don't do any type
14924      adjustments.  */
14925   if (!subr)
14926     {
14927       if (!TYPE_P (arg))
14928         {
14929           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14930           if (type_unknown_p (arg))
14931             {
14932               /* [temp.deduct.type] A template-argument can be
14933                  deduced from a pointer to function or pointer
14934                  to member function argument if the set of
14935                  overloaded functions does not contain function
14936                  templates and at most one of a set of
14937                  overloaded functions provides a unique
14938                  match.  */
14939
14940               if (resolve_overloaded_unification
14941                   (tparms, targs, parm, arg, strict,
14942                    arg_strict, explain_p))
14943                 return unify_success (explain_p);
14944               return unify_overload_resolution_failure (explain_p, arg);
14945             }
14946
14947           arg_expr = arg;
14948           arg = unlowered_expr_type (arg);
14949           if (arg == error_mark_node)
14950             return unify_invalid (explain_p);
14951         }
14952
14953       arg_strict |=
14954         maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
14955     }
14956   else
14957     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
14958                 == (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
14959
14960   /* For deduction from an init-list we need the actual list.  */
14961   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14962     arg = arg_expr;
14963   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
14964 }
14965
14966 /* Most parms like fn_type_unification.
14967
14968    If SUBR is 1, we're being called recursively (to unify the
14969    arguments of a function or method parameter of a function
14970    template). */
14971
14972 static int
14973 type_unification_real (tree tparms,
14974                        tree targs,
14975                        tree xparms,
14976                        const tree *xargs,
14977                        unsigned int xnargs,
14978                        int subr,
14979                        unification_kind_t strict,
14980                        int flags,
14981                        bool explain_p)
14982 {
14983   tree parm, arg;
14984   int i;
14985   int ntparms = TREE_VEC_LENGTH (tparms);
14986   int saw_undeduced = 0;
14987   tree parms;
14988   const tree *args;
14989   unsigned int nargs;
14990   unsigned int ia;
14991
14992   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
14993   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
14994   gcc_assert (ntparms > 0);
14995
14996   /* Reset the number of non-defaulted template arguments contained
14997      in TARGS.  */
14998   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
14999
15000  again:
15001   parms = xparms;
15002   args = xargs;
15003   nargs = xnargs;
15004
15005   ia = 0;
15006   while (parms && parms != void_list_node
15007          && ia < nargs)
15008     {
15009       parm = TREE_VALUE (parms);
15010
15011       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
15012           && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
15013         /* For a function parameter pack that occurs at the end of the
15014            parameter-declaration-list, the type A of each remaining
15015            argument of the call is compared with the type P of the
15016            declarator-id of the function parameter pack.  */
15017         break;
15018
15019       parms = TREE_CHAIN (parms);
15020
15021       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
15022         /* For a function parameter pack that does not occur at the
15023            end of the parameter-declaration-list, the type of the
15024            parameter pack is a non-deduced context.  */
15025         continue;
15026
15027       arg = args[ia];
15028       ++ia;
15029
15030       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15031                               flags, explain_p))
15032         return 1;
15033     }
15034
15035   if (parms 
15036       && parms != void_list_node
15037       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
15038     {
15039       /* Unify the remaining arguments with the pack expansion type.  */
15040       tree argvec;
15041       tree parmvec = make_tree_vec (1);
15042
15043       /* Allocate a TREE_VEC and copy in all of the arguments */ 
15044       argvec = make_tree_vec (nargs - ia);
15045       for (i = 0; ia < nargs; ++ia, ++i)
15046         TREE_VEC_ELT (argvec, i) = args[ia];
15047
15048       /* Copy the parameter into parmvec.  */
15049       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
15050       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
15051                                 /*subr=*/subr, explain_p))
15052         return 1;
15053
15054       /* Advance to the end of the list of parameters.  */
15055       parms = TREE_CHAIN (parms);
15056     }
15057
15058   /* Fail if we've reached the end of the parm list, and more args
15059      are present, and the parm list isn't variadic.  */
15060   if (ia < nargs && parms == void_list_node)
15061     return unify_too_many_arguments (explain_p, nargs, ia);
15062   /* Fail if parms are left and they don't have default values.  */
15063   if (parms && parms != void_list_node
15064       && TREE_PURPOSE (parms) == NULL_TREE)
15065     {
15066       unsigned int count = nargs;
15067       tree p = parms;
15068       while (p && p != void_list_node)
15069         {
15070           count++;
15071           p = TREE_CHAIN (p);
15072         }
15073       return unify_too_few_arguments (explain_p, ia, count);
15074     }
15075
15076   if (!subr)
15077     {
15078       tsubst_flags_t complain = (explain_p
15079                                  ? tf_warning_or_error
15080                                  : tf_none);
15081
15082       for (i = 0; i < ntparms; i++)
15083         {
15084           tree targ = TREE_VEC_ELT (targs, i);
15085           tree tparm = TREE_VEC_ELT (tparms, i);
15086
15087           /* Clear the "incomplete" flags on all argument packs now so that
15088              substituting them into later default arguments works.  */
15089           if (targ && ARGUMENT_PACK_P (targ))
15090             {
15091               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
15092               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
15093             }
15094
15095           if (targ || tparm == error_mark_node)
15096             continue;
15097           tparm = TREE_VALUE (tparm);
15098
15099           /* If this is an undeduced nontype parameter that depends on
15100              a type parameter, try another pass; its type may have been
15101              deduced from a later argument than the one from which
15102              this parameter can be deduced.  */
15103           if (TREE_CODE (tparm) == PARM_DECL
15104               && uses_template_parms (TREE_TYPE (tparm))
15105               && !saw_undeduced++)
15106             goto again;
15107
15108           /* Core issue #226 (C++0x) [temp.deduct]:
15109
15110              If a template argument has not been deduced, its
15111              default template argument, if any, is used. 
15112
15113              When we are in C++98 mode, TREE_PURPOSE will either
15114              be NULL_TREE or ERROR_MARK_NODE, so we do not need
15115              to explicitly check cxx_dialect here.  */
15116           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
15117             {
15118               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
15119               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
15120               location_t save_loc = input_location;
15121               if (DECL_P (parm))
15122                 input_location = DECL_SOURCE_LOCATION (parm);
15123               arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
15124               arg = convert_template_argument (parm, arg, targs, complain,
15125                                                i, NULL_TREE);
15126               input_location = save_loc;
15127               if (arg == error_mark_node)
15128                 return 1;
15129               else
15130                 {
15131                   TREE_VEC_ELT (targs, i) = arg;
15132                   /* The position of the first default template argument,
15133                      is also the number of non-defaulted arguments in TARGS.
15134                      Record that.  */
15135                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15136                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
15137                   continue;
15138                 }
15139             }
15140
15141           /* If the type parameter is a parameter pack, then it will
15142              be deduced to an empty parameter pack.  */
15143           if (template_parameter_pack_p (tparm))
15144             {
15145               tree arg;
15146
15147               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15148                 {
15149                   arg = make_node (NONTYPE_ARGUMENT_PACK);
15150                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15151                   TREE_CONSTANT (arg) = 1;
15152                 }
15153               else
15154                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15155
15156               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15157
15158               TREE_VEC_ELT (targs, i) = arg;
15159               continue;
15160             }
15161
15162           return unify_parameter_deduction_failure (explain_p, tparm);
15163         }
15164     }
15165 #ifdef ENABLE_CHECKING
15166   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15167     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15168 #endif
15169
15170   return unify_success (explain_p);
15171 }
15172
15173 /* Subroutine of type_unification_real.  Args are like the variables
15174    at the call site.  ARG is an overloaded function (or template-id);
15175    we try deducing template args from each of the overloads, and if
15176    only one succeeds, we go with that.  Modifies TARGS and returns
15177    true on success.  */
15178
15179 static bool
15180 resolve_overloaded_unification (tree tparms,
15181                                 tree targs,
15182                                 tree parm,
15183                                 tree arg,
15184                                 unification_kind_t strict,
15185                                 int sub_strict,
15186                                 bool explain_p)
15187 {
15188   tree tempargs = copy_node (targs);
15189   int good = 0;
15190   tree goodfn = NULL_TREE;
15191   bool addr_p;
15192
15193   if (TREE_CODE (arg) == ADDR_EXPR)
15194     {
15195       arg = TREE_OPERAND (arg, 0);
15196       addr_p = true;
15197     }
15198   else
15199     addr_p = false;
15200
15201   if (TREE_CODE (arg) == COMPONENT_REF)
15202     /* Handle `&x' where `x' is some static or non-static member
15203        function name.  */
15204     arg = TREE_OPERAND (arg, 1);
15205
15206   if (TREE_CODE (arg) == OFFSET_REF)
15207     arg = TREE_OPERAND (arg, 1);
15208
15209   /* Strip baselink information.  */
15210   if (BASELINK_P (arg))
15211     arg = BASELINK_FUNCTIONS (arg);
15212
15213   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15214     {
15215       /* If we got some explicit template args, we need to plug them into
15216          the affected templates before we try to unify, in case the
15217          explicit args will completely resolve the templates in question.  */
15218
15219       int ok = 0;
15220       tree expl_subargs = TREE_OPERAND (arg, 1);
15221       arg = TREE_OPERAND (arg, 0);
15222
15223       for (; arg; arg = OVL_NEXT (arg))
15224         {
15225           tree fn = OVL_CURRENT (arg);
15226           tree subargs, elem;
15227
15228           if (TREE_CODE (fn) != TEMPLATE_DECL)
15229             continue;
15230
15231           ++processing_template_decl;
15232           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15233                                   expl_subargs, /*check_ret=*/false);
15234           if (subargs && !any_dependent_template_arguments_p (subargs))
15235             {
15236               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15237               if (try_one_overload (tparms, targs, tempargs, parm,
15238                                     elem, strict, sub_strict, addr_p, explain_p)
15239                   && (!goodfn || !same_type_p (goodfn, elem)))
15240                 {
15241                   goodfn = elem;
15242                   ++good;
15243                 }
15244             }
15245           else if (subargs)
15246             ++ok;
15247           --processing_template_decl;
15248         }
15249       /* If no templates (or more than one) are fully resolved by the
15250          explicit arguments, this template-id is a non-deduced context; it
15251          could still be OK if we deduce all template arguments for the
15252          enclosing call through other arguments.  */
15253       if (good != 1)
15254         good = ok;
15255     }
15256   else if (TREE_CODE (arg) != OVERLOAD
15257            && TREE_CODE (arg) != FUNCTION_DECL)
15258     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15259        -- but the deduction does not succeed because the expression is
15260        not just the function on its own.  */
15261     return false;
15262   else
15263     for (; arg; arg = OVL_NEXT (arg))
15264       if (try_one_overload (tparms, targs, tempargs, parm,
15265                             TREE_TYPE (OVL_CURRENT (arg)),
15266                             strict, sub_strict, addr_p, explain_p)
15267           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15268         {
15269           goodfn = OVL_CURRENT (arg);
15270           ++good;
15271         }
15272
15273   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15274      to function or pointer to member function argument if the set of
15275      overloaded functions does not contain function templates and at most
15276      one of a set of overloaded functions provides a unique match.
15277
15278      So if we found multiple possibilities, we return success but don't
15279      deduce anything.  */
15280
15281   if (good == 1)
15282     {
15283       int i = TREE_VEC_LENGTH (targs);
15284       for (; i--; )
15285         if (TREE_VEC_ELT (tempargs, i))
15286           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15287     }
15288   if (good)
15289     return true;
15290
15291   return false;
15292 }
15293
15294 /* Core DR 115: In contexts where deduction is done and fails, or in
15295    contexts where deduction is not done, if a template argument list is
15296    specified and it, along with any default template arguments, identifies
15297    a single function template specialization, then the template-id is an
15298    lvalue for the function template specialization.  */
15299
15300 tree
15301 resolve_nondeduced_context (tree orig_expr)
15302 {
15303   tree expr, offset, baselink;
15304   bool addr;
15305
15306   if (!type_unknown_p (orig_expr))
15307     return orig_expr;
15308
15309   expr = orig_expr;
15310   addr = false;
15311   offset = NULL_TREE;
15312   baselink = NULL_TREE;
15313
15314   if (TREE_CODE (expr) == ADDR_EXPR)
15315     {
15316       expr = TREE_OPERAND (expr, 0);
15317       addr = true;
15318     }
15319   if (TREE_CODE (expr) == OFFSET_REF)
15320     {
15321       offset = expr;
15322       expr = TREE_OPERAND (expr, 1);
15323     }
15324   if (BASELINK_P (expr))
15325     {
15326       baselink = expr;
15327       expr = BASELINK_FUNCTIONS (expr);
15328     }
15329
15330   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15331     {
15332       int good = 0;
15333       tree goodfn = NULL_TREE;
15334
15335       /* If we got some explicit template args, we need to plug them into
15336          the affected templates before we try to unify, in case the
15337          explicit args will completely resolve the templates in question.  */
15338
15339       tree expl_subargs = TREE_OPERAND (expr, 1);
15340       tree arg = TREE_OPERAND (expr, 0);
15341       tree badfn = NULL_TREE;
15342       tree badargs = NULL_TREE;
15343
15344       for (; arg; arg = OVL_NEXT (arg))
15345         {
15346           tree fn = OVL_CURRENT (arg);
15347           tree subargs, elem;
15348
15349           if (TREE_CODE (fn) != TEMPLATE_DECL)
15350             continue;
15351
15352           ++processing_template_decl;
15353           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
15354                                   expl_subargs, /*check_ret=*/false);
15355           if (subargs && !any_dependent_template_arguments_p (subargs))
15356             {
15357               elem = instantiate_template (fn, subargs, tf_none);
15358               if (elem == error_mark_node)
15359                 {
15360                   badfn = fn;
15361                   badargs = subargs;
15362                 }
15363               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15364                 {
15365                   goodfn = elem;
15366                   ++good;
15367                 }
15368             }
15369           --processing_template_decl;
15370         }
15371       if (good == 1)
15372         {
15373           mark_used (goodfn);
15374           expr = goodfn;
15375           if (baselink)
15376             expr = build_baselink (BASELINK_BINFO (baselink),
15377                                    BASELINK_ACCESS_BINFO (baselink),
15378                                    expr, BASELINK_OPTYPE (baselink));
15379           if (offset)
15380             {
15381               tree base
15382                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15383               expr = build_offset_ref (base, expr, addr);
15384             }
15385           if (addr)
15386             expr = cp_build_addr_expr (expr, tf_warning_or_error);
15387           return expr;
15388         }
15389       else if (good == 0 && badargs)
15390         /* There were no good options and at least one bad one, so let the
15391            user know what the problem is.  */
15392         instantiate_template (badfn, badargs, tf_warning_or_error);
15393     }
15394   return orig_expr;
15395 }
15396
15397 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15398    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15399    different overloads deduce different arguments for a given parm.
15400    ADDR_P is true if the expression for which deduction is being
15401    performed was of the form "& fn" rather than simply "fn".
15402
15403    Returns 1 on success.  */
15404
15405 static int
15406 try_one_overload (tree tparms,
15407                   tree orig_targs,
15408                   tree targs,
15409                   tree parm,
15410                   tree arg,
15411                   unification_kind_t strict,
15412                   int sub_strict,
15413                   bool addr_p,
15414                   bool explain_p)
15415 {
15416   int nargs;
15417   tree tempargs;
15418   int i;
15419
15420   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15421      to function or pointer to member function argument if the set of
15422      overloaded functions does not contain function templates and at most
15423      one of a set of overloaded functions provides a unique match.
15424
15425      So if this is a template, just return success.  */
15426
15427   if (uses_template_parms (arg))
15428     return 1;
15429
15430   if (TREE_CODE (arg) == METHOD_TYPE)
15431     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15432   else if (addr_p)
15433     arg = build_pointer_type (arg);
15434
15435   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15436
15437   /* We don't copy orig_targs for this because if we have already deduced
15438      some template args from previous args, unify would complain when we
15439      try to deduce a template parameter for the same argument, even though
15440      there isn't really a conflict.  */
15441   nargs = TREE_VEC_LENGTH (targs);
15442   tempargs = make_tree_vec (nargs);
15443
15444   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15445     return 0;
15446
15447   /* First make sure we didn't deduce anything that conflicts with
15448      explicitly specified args.  */
15449   for (i = nargs; i--; )
15450     {
15451       tree elt = TREE_VEC_ELT (tempargs, i);
15452       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15453
15454       if (!elt)
15455         /*NOP*/;
15456       else if (uses_template_parms (elt))
15457         /* Since we're unifying against ourselves, we will fill in
15458            template args used in the function parm list with our own
15459            template parms.  Discard them.  */
15460         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15461       else if (oldelt && !template_args_equal (oldelt, elt))
15462         return 0;
15463     }
15464
15465   for (i = nargs; i--; )
15466     {
15467       tree elt = TREE_VEC_ELT (tempargs, i);
15468
15469       if (elt)
15470         TREE_VEC_ELT (targs, i) = elt;
15471     }
15472
15473   return 1;
15474 }
15475
15476 /* PARM is a template class (perhaps with unbound template
15477    parameters).  ARG is a fully instantiated type.  If ARG can be
15478    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15479    TARGS are as for unify.  */
15480
15481 static tree
15482 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15483                        bool explain_p)
15484 {
15485   tree copy_of_targs;
15486
15487   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15488       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15489           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15490     return NULL_TREE;
15491
15492   /* We need to make a new template argument vector for the call to
15493      unify.  If we used TARGS, we'd clutter it up with the result of
15494      the attempted unification, even if this class didn't work out.
15495      We also don't want to commit ourselves to all the unifications
15496      we've already done, since unification is supposed to be done on
15497      an argument-by-argument basis.  In other words, consider the
15498      following pathological case:
15499
15500        template <int I, int J, int K>
15501        struct S {};
15502
15503        template <int I, int J>
15504        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15505
15506        template <int I, int J, int K>
15507        void f(S<I, J, K>, S<I, I, I>);
15508
15509        void g() {
15510          S<0, 0, 0> s0;
15511          S<0, 1, 2> s2;
15512
15513          f(s0, s2);
15514        }
15515
15516      Now, by the time we consider the unification involving `s2', we
15517      already know that we must have `f<0, 0, 0>'.  But, even though
15518      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
15519      because there are two ways to unify base classes of S<0, 1, 2>
15520      with S<I, I, I>.  If we kept the already deduced knowledge, we
15521      would reject the possibility I=1.  */
15522   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
15523
15524   /* If unification failed, we're done.  */
15525   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
15526              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
15527     return NULL_TREE;
15528
15529   return arg;
15530 }
15531
15532 /* Given a template type PARM and a class type ARG, find the unique
15533    base type in ARG that is an instance of PARM.  We do not examine
15534    ARG itself; only its base-classes.  If there is not exactly one
15535    appropriate base class, return NULL_TREE.  PARM may be the type of
15536    a partial specialization, as well as a plain template type.  Used
15537    by unify.  */
15538
15539 static enum template_base_result
15540 get_template_base (tree tparms, tree targs, tree parm, tree arg,
15541                    bool explain_p, tree *result)
15542 {
15543   tree rval = NULL_TREE;
15544   tree binfo;
15545
15546   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
15547
15548   binfo = TYPE_BINFO (complete_type (arg));
15549   if (!binfo)
15550     {
15551       /* The type could not be completed.  */
15552       *result = NULL_TREE;
15553       return tbr_incomplete_type;
15554     }
15555
15556   /* Walk in inheritance graph order.  The search order is not
15557      important, and this avoids multiple walks of virtual bases.  */
15558   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
15559     {
15560       tree r = try_class_unification (tparms, targs, parm,
15561                                       BINFO_TYPE (binfo), explain_p);
15562
15563       if (r)
15564         {
15565           /* If there is more than one satisfactory baseclass, then:
15566
15567                [temp.deduct.call]
15568
15569               If they yield more than one possible deduced A, the type
15570               deduction fails.
15571
15572              applies.  */
15573           if (rval && !same_type_p (r, rval))
15574             {
15575               *result = NULL_TREE;
15576               return tbr_ambiguous_baseclass;
15577             }
15578
15579           rval = r;
15580         }
15581     }
15582
15583   *result = rval;
15584   return tbr_success;
15585 }
15586
15587 /* Returns the level of DECL, which declares a template parameter.  */
15588
15589 static int
15590 template_decl_level (tree decl)
15591 {
15592   switch (TREE_CODE (decl))
15593     {
15594     case TYPE_DECL:
15595     case TEMPLATE_DECL:
15596       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
15597
15598     case PARM_DECL:
15599       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
15600
15601     default:
15602       gcc_unreachable ();
15603     }
15604   return 0;
15605 }
15606
15607 /* Decide whether ARG can be unified with PARM, considering only the
15608    cv-qualifiers of each type, given STRICT as documented for unify.
15609    Returns nonzero iff the unification is OK on that basis.  */
15610
15611 static int
15612 check_cv_quals_for_unify (int strict, tree arg, tree parm)
15613 {
15614   int arg_quals = cp_type_quals (arg);
15615   int parm_quals = cp_type_quals (parm);
15616
15617   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15618       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15619     {
15620       /*  Although a CVR qualifier is ignored when being applied to a
15621           substituted template parameter ([8.3.2]/1 for example), that
15622           does not allow us to unify "const T" with "int&" because both
15623           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
15624           It is ok when we're allowing additional CV qualifiers
15625           at the outer level [14.8.2.1]/3,1st bullet.  */
15626       if ((TREE_CODE (arg) == REFERENCE_TYPE
15627            || TREE_CODE (arg) == FUNCTION_TYPE
15628            || TREE_CODE (arg) == METHOD_TYPE)
15629           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
15630         return 0;
15631
15632       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
15633           && (parm_quals & TYPE_QUAL_RESTRICT))
15634         return 0;
15635     }
15636
15637   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
15638       && (arg_quals & parm_quals) != parm_quals)
15639     return 0;
15640
15641   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
15642       && (parm_quals & arg_quals) != arg_quals)
15643     return 0;
15644
15645   return 1;
15646 }
15647
15648 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
15649 void 
15650 template_parm_level_and_index (tree parm, int* level, int* index)
15651 {
15652   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15653       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15654       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15655     {
15656       *index = TEMPLATE_TYPE_IDX (parm);
15657       *level = TEMPLATE_TYPE_LEVEL (parm);
15658     }
15659   else
15660     {
15661       *index = TEMPLATE_PARM_IDX (parm);
15662       *level = TEMPLATE_PARM_LEVEL (parm);
15663     }
15664 }
15665
15666 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)                    \
15667   do {                                                                  \
15668     if (unify (TP, TA, P, A, S, EP))                                    \
15669       return 1;                                                         \
15670   } while (0);
15671
15672 /* Unifies the remaining arguments in PACKED_ARGS with the pack
15673    expansion at the end of PACKED_PARMS. Returns 0 if the type
15674    deduction succeeds, 1 otherwise. STRICT is the same as in
15675    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
15676    call argument list. We'll need to adjust the arguments to make them
15677    types. SUBR tells us if this is from a recursive call to
15678    type_unification_real, or for comparing two template argument
15679    lists. */
15680
15681 static int
15682 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
15683                       tree packed_args, unification_kind_t strict,
15684                       bool subr, bool explain_p)
15685 {
15686   tree parm 
15687     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
15688   tree pattern = PACK_EXPANSION_PATTERN (parm);
15689   tree pack, packs = NULL_TREE;
15690   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
15691   int len = TREE_VEC_LENGTH (packed_args);
15692
15693   /* Determine the parameter packs we will be deducing from the
15694      pattern, and record their current deductions.  */
15695   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
15696        pack; pack = TREE_CHAIN (pack))
15697     {
15698       tree parm_pack = TREE_VALUE (pack);
15699       int idx, level;
15700
15701       /* Determine the index and level of this parameter pack.  */
15702       template_parm_level_and_index (parm_pack, &level, &idx);
15703
15704       /* Keep track of the parameter packs and their corresponding
15705          argument packs.  */
15706       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
15707       TREE_TYPE (packs) = make_tree_vec (len - start);
15708     }
15709   
15710   /* Loop through all of the arguments that have not yet been
15711      unified and unify each with the pattern.  */
15712   for (i = start; i < len; i++)
15713     {
15714       tree parm;
15715       bool any_explicit = false;
15716       tree arg = TREE_VEC_ELT (packed_args, i);
15717
15718       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
15719          or the element of its argument pack at the current index if
15720          this argument was explicitly specified.  */
15721       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15722         {
15723           int idx, level;
15724           tree arg, pargs;
15725           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15726
15727           arg = NULL_TREE;
15728           if (TREE_VALUE (pack)
15729               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
15730               && (i - start < TREE_VEC_LENGTH (pargs)))
15731             {
15732               any_explicit = true;
15733               arg = TREE_VEC_ELT (pargs, i - start);
15734             }
15735           TMPL_ARG (targs, level, idx) = arg;
15736         }
15737
15738       /* If we had explicit template arguments, substitute them into the
15739          pattern before deduction.  */
15740       if (any_explicit)
15741         {
15742           /* Some arguments might still be unspecified or dependent.  */
15743           bool dependent;
15744           ++processing_template_decl;
15745           dependent = any_dependent_template_arguments_p (targs);
15746           if (!dependent)
15747             --processing_template_decl;
15748           parm = tsubst (pattern, targs,
15749                          explain_p ? tf_warning_or_error : tf_none,
15750                          NULL_TREE);
15751           if (dependent)
15752             --processing_template_decl;
15753           if (parm == error_mark_node)
15754             return 1;
15755         }
15756       else
15757         parm = pattern;
15758
15759       /* Unify the pattern with the current argument.  */
15760       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15761                               LOOKUP_IMPLICIT, explain_p))
15762         return 1;
15763
15764       /* For each parameter pack, collect the deduced value.  */
15765       for (pack = packs; pack; pack = TREE_CHAIN (pack))
15766         {
15767           int idx, level;
15768           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15769
15770           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
15771             TMPL_ARG (targs, level, idx);
15772         }
15773     }
15774
15775   /* Verify that the results of unification with the parameter packs
15776      produce results consistent with what we've seen before, and make
15777      the deduced argument packs available.  */
15778   for (pack = packs; pack; pack = TREE_CHAIN (pack))
15779     {
15780       tree old_pack = TREE_VALUE (pack);
15781       tree new_args = TREE_TYPE (pack);
15782       int i, len = TREE_VEC_LENGTH (new_args);
15783       int idx, level;
15784       bool nondeduced_p = false;
15785
15786       /* By default keep the original deduced argument pack.
15787          If necessary, more specific code is going to update the
15788          resulting deduced argument later down in this function.  */
15789       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
15790       TMPL_ARG (targs, level, idx) = old_pack;
15791
15792       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
15793          actually deduce anything.  */
15794       for (i = 0; i < len && !nondeduced_p; ++i)
15795         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
15796           nondeduced_p = true;
15797       if (nondeduced_p)
15798         continue;
15799
15800       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
15801         {
15802           /* If we had fewer function args than explicit template args,
15803              just use the explicits.  */
15804           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15805           int explicit_len = TREE_VEC_LENGTH (explicit_args);
15806           if (len < explicit_len)
15807             new_args = explicit_args;
15808         }
15809
15810       if (!old_pack)
15811         {
15812           tree result;
15813           /* Build the deduced *_ARGUMENT_PACK.  */
15814           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
15815             {
15816               result = make_node (NONTYPE_ARGUMENT_PACK);
15817               TREE_TYPE (result) = 
15818                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
15819               TREE_CONSTANT (result) = 1;
15820             }
15821           else
15822             result = cxx_make_type (TYPE_ARGUMENT_PACK);
15823
15824           SET_ARGUMENT_PACK_ARGS (result, new_args);
15825
15826           /* Note the deduced argument packs for this parameter
15827              pack.  */
15828           TMPL_ARG (targs, level, idx) = result;
15829         }
15830       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
15831                && (ARGUMENT_PACK_ARGS (old_pack) 
15832                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
15833         {
15834           /* We only had the explicitly-provided arguments before, but
15835              now we have a complete set of arguments.  */
15836           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
15837
15838           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
15839           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
15840           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
15841         }
15842       else
15843         {
15844           tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
15845           tree old_args = ARGUMENT_PACK_ARGS (old_pack);
15846
15847           if (!comp_template_args_with_info (old_args, new_args,
15848                                              &bad_old_arg, &bad_new_arg))
15849             /* Inconsistent unification of this parameter pack.  */
15850             return unify_parameter_pack_inconsistent (explain_p,
15851                                                       bad_old_arg,
15852                                                       bad_new_arg);
15853         }
15854     }
15855
15856   return unify_success (explain_p);
15857 }
15858
15859 /* Deduce the value of template parameters.  TPARMS is the (innermost)
15860    set of template parameters to a template.  TARGS is the bindings
15861    for those template parameters, as determined thus far; TARGS may
15862    include template arguments for outer levels of template parameters
15863    as well.  PARM is a parameter to a template function, or a
15864    subcomponent of that parameter; ARG is the corresponding argument.
15865    This function attempts to match PARM with ARG in a manner
15866    consistent with the existing assignments in TARGS.  If more values
15867    are deduced, then TARGS is updated.
15868
15869    Returns 0 if the type deduction succeeds, 1 otherwise.  The
15870    parameter STRICT is a bitwise or of the following flags:
15871
15872      UNIFY_ALLOW_NONE:
15873        Require an exact match between PARM and ARG.
15874      UNIFY_ALLOW_MORE_CV_QUAL:
15875        Allow the deduced ARG to be more cv-qualified (by qualification
15876        conversion) than ARG.
15877      UNIFY_ALLOW_LESS_CV_QUAL:
15878        Allow the deduced ARG to be less cv-qualified than ARG.
15879      UNIFY_ALLOW_DERIVED:
15880        Allow the deduced ARG to be a template base class of ARG,
15881        or a pointer to a template base class of the type pointed to by
15882        ARG.
15883      UNIFY_ALLOW_INTEGER:
15884        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
15885        case for more information.
15886      UNIFY_ALLOW_OUTER_LEVEL:
15887        This is the outermost level of a deduction. Used to determine validity
15888        of qualification conversions. A valid qualification conversion must
15889        have const qualified pointers leading up to the inner type which
15890        requires additional CV quals, except at the outer level, where const
15891        is not required [conv.qual]. It would be normal to set this flag in
15892        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
15893      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
15894        This is the outermost level of a deduction, and PARM can be more CV
15895        qualified at this point.
15896      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
15897        This is the outermost level of a deduction, and PARM can be less CV
15898        qualified at this point.  */
15899
15900 static int
15901 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
15902        bool explain_p)
15903 {
15904   int idx;
15905   tree targ;
15906   tree tparm;
15907   int strict_in = strict;
15908
15909   /* I don't think this will do the right thing with respect to types.
15910      But the only case I've seen it in so far has been array bounds, where
15911      signedness is the only information lost, and I think that will be
15912      okay.  */
15913   while (TREE_CODE (parm) == NOP_EXPR)
15914     parm = TREE_OPERAND (parm, 0);
15915
15916   if (arg == error_mark_node)
15917     return unify_invalid (explain_p);
15918   if (arg == unknown_type_node
15919       || arg == init_list_type_node)
15920     /* We can't deduce anything from this, but we might get all the
15921        template args from other function args.  */
15922     return unify_success (explain_p);
15923
15924   /* If PARM uses template parameters, then we can't bail out here,
15925      even if ARG == PARM, since we won't record unifications for the
15926      template parameters.  We might need them if we're trying to
15927      figure out which of two things is more specialized.  */
15928   if (arg == parm && !uses_template_parms (parm))
15929     return unify_success (explain_p);
15930
15931   /* Handle init lists early, so the rest of the function can assume
15932      we're dealing with a type. */
15933   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
15934     {
15935       tree elt, elttype;
15936       unsigned i;
15937       tree orig_parm = parm;
15938
15939       /* Replace T with std::initializer_list<T> for deduction.  */
15940       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15941           && flag_deduce_init_list)
15942         parm = listify (parm);
15943
15944       if (!is_std_init_list (parm))
15945         /* We can only deduce from an initializer list argument if the
15946            parameter is std::initializer_list; otherwise this is a
15947            non-deduced context. */
15948         return unify_success (explain_p);
15949
15950       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
15951
15952       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
15953         {
15954           int elt_strict = strict;
15955
15956           if (elt == error_mark_node)
15957             return unify_invalid (explain_p);
15958
15959           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
15960             {
15961               tree type = TREE_TYPE (elt);
15962               /* It should only be possible to get here for a call.  */
15963               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
15964               elt_strict |= maybe_adjust_types_for_deduction
15965                 (DEDUCE_CALL, &elttype, &type, elt);
15966               elt = type;
15967             }
15968
15969           RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
15970                                    explain_p);
15971         }
15972
15973       /* If the std::initializer_list<T> deduction worked, replace the
15974          deduced A with std::initializer_list<A>.  */
15975       if (orig_parm != parm)
15976         {
15977           idx = TEMPLATE_TYPE_IDX (orig_parm);
15978           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15979           targ = listify (targ);
15980           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
15981         }
15982       return unify_success (explain_p);
15983     }
15984
15985   /* Immediately reject some pairs that won't unify because of
15986      cv-qualification mismatches.  */
15987   if (TREE_CODE (arg) == TREE_CODE (parm)
15988       && TYPE_P (arg)
15989       /* It is the elements of the array which hold the cv quals of an array
15990          type, and the elements might be template type parms. We'll check
15991          when we recurse.  */
15992       && TREE_CODE (arg) != ARRAY_TYPE
15993       /* We check the cv-qualifiers when unifying with template type
15994          parameters below.  We want to allow ARG `const T' to unify with
15995          PARM `T' for example, when computing which of two templates
15996          is more specialized, for example.  */
15997       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
15998       && !check_cv_quals_for_unify (strict_in, arg, parm))
15999     return unify_cv_qual_mismatch (explain_p, parm, arg);
16000
16001   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
16002       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
16003     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
16004   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
16005   strict &= ~UNIFY_ALLOW_DERIVED;
16006   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
16007   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
16008
16009   switch (TREE_CODE (parm))
16010     {
16011     case TYPENAME_TYPE:
16012     case SCOPE_REF:
16013     case UNBOUND_CLASS_TEMPLATE:
16014       /* In a type which contains a nested-name-specifier, template
16015          argument values cannot be deduced for template parameters used
16016          within the nested-name-specifier.  */
16017       return unify_success (explain_p);
16018
16019     case TEMPLATE_TYPE_PARM:
16020     case TEMPLATE_TEMPLATE_PARM:
16021     case BOUND_TEMPLATE_TEMPLATE_PARM:
16022       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16023       if (tparm == error_mark_node)
16024         return unify_invalid (explain_p);
16025
16026       if (TEMPLATE_TYPE_LEVEL (parm)
16027           != template_decl_level (tparm))
16028         /* The PARM is not one we're trying to unify.  Just check
16029            to see if it matches ARG.  */
16030         {
16031           if (TREE_CODE (arg) == TREE_CODE (parm)
16032               && same_type_p (parm, arg))
16033             return unify_success (explain_p);
16034           else
16035             return unify_type_mismatch (explain_p, parm, arg);
16036         }
16037       idx = TEMPLATE_TYPE_IDX (parm);
16038       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16039       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
16040       if (tparm == error_mark_node)
16041         return unify_invalid (explain_p);
16042
16043       /* Check for mixed types and values.  */
16044       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16045            && TREE_CODE (tparm) != TYPE_DECL)
16046           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16047               && TREE_CODE (tparm) != TEMPLATE_DECL))
16048         gcc_unreachable ();
16049
16050       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16051         {
16052           /* ARG must be constructed from a template class or a template
16053              template parameter.  */
16054           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
16055               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
16056             return unify_template_deduction_failure (explain_p, parm, arg);
16057
16058           {
16059             tree parmvec = TYPE_TI_ARGS (parm);
16060             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
16061             tree full_argvec = add_to_template_args (targs, argvec);
16062             tree parm_parms 
16063               = DECL_INNERMOST_TEMPLATE_PARMS
16064                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
16065             int i, len;
16066             int parm_variadic_p = 0;
16067
16068             /* The resolution to DR150 makes clear that default
16069                arguments for an N-argument may not be used to bind T
16070                to a template template parameter with fewer than N
16071                parameters.  It is not safe to permit the binding of
16072                default arguments as an extension, as that may change
16073                the meaning of a conforming program.  Consider:
16074
16075                   struct Dense { static const unsigned int dim = 1; };
16076
16077                   template <template <typename> class View,
16078                             typename Block>
16079                   void operator+(float, View<Block> const&);
16080
16081                   template <typename Block,
16082                             unsigned int Dim = Block::dim>
16083                   struct Lvalue_proxy { operator float() const; };
16084
16085                   void
16086                   test_1d (void) {
16087                     Lvalue_proxy<Dense> p;
16088                     float b;
16089                     b + p;
16090                   }
16091
16092               Here, if Lvalue_proxy is permitted to bind to View, then
16093               the global operator+ will be used; if they are not, the
16094               Lvalue_proxy will be converted to float.  */
16095             if (coerce_template_parms (parm_parms,
16096                                        full_argvec,
16097                                        TYPE_TI_TEMPLATE (parm),
16098                                        (explain_p
16099                                         ? tf_warning_or_error
16100                                         : tf_none),
16101                                        /*require_all_args=*/true,
16102                                        /*use_default_args=*/false)
16103                 == error_mark_node)
16104               return 1;
16105
16106             /* Deduce arguments T, i from TT<T> or TT<i>.
16107                We check each element of PARMVEC and ARGVEC individually
16108                rather than the whole TREE_VEC since they can have
16109                different number of elements.  */
16110
16111             parmvec = expand_template_argument_pack (parmvec);
16112             argvec = expand_template_argument_pack (argvec);
16113
16114             len = TREE_VEC_LENGTH (parmvec);
16115
16116             /* Check if the parameters end in a pack, making them
16117                variadic.  */
16118             if (len > 0
16119                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
16120               parm_variadic_p = 1;
16121             
16122             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
16123               return unify_too_few_arguments (explain_p,
16124                                               TREE_VEC_LENGTH (argvec), len);
16125
16126              for (i = 0; i < len - parm_variadic_p; ++i)
16127               {
16128                 RECUR_AND_CHECK_FAILURE (tparms, targs,
16129                                          TREE_VEC_ELT (parmvec, i),
16130                                          TREE_VEC_ELT (argvec, i),
16131                                          UNIFY_ALLOW_NONE, explain_p);
16132               }
16133
16134             if (parm_variadic_p
16135                 && unify_pack_expansion (tparms, targs,
16136                                          parmvec, argvec,
16137                                          DEDUCE_EXACT,
16138                                          /*subr=*/true, explain_p))
16139               return 1;
16140           }
16141           arg = TYPE_TI_TEMPLATE (arg);
16142
16143           /* Fall through to deduce template name.  */
16144         }
16145
16146       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16147           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16148         {
16149           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16150
16151           /* Simple cases: Value already set, does match or doesn't.  */
16152           if (targ != NULL_TREE && template_args_equal (targ, arg))
16153             return unify_success (explain_p);
16154           else if (targ)
16155             return unify_inconsistency (explain_p, parm, targ, arg);
16156         }
16157       else
16158         {
16159           /* If PARM is `const T' and ARG is only `int', we don't have
16160              a match unless we are allowing additional qualification.
16161              If ARG is `const int' and PARM is just `T' that's OK;
16162              that binds `const int' to `T'.  */
16163           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16164                                          arg, parm))
16165             return unify_cv_qual_mismatch (explain_p, parm, arg);
16166
16167           /* Consider the case where ARG is `const volatile int' and
16168              PARM is `const T'.  Then, T should be `volatile int'.  */
16169           arg = cp_build_qualified_type_real
16170             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16171           if (arg == error_mark_node)
16172             return unify_invalid (explain_p);
16173
16174           /* Simple cases: Value already set, does match or doesn't.  */
16175           if (targ != NULL_TREE && same_type_p (targ, arg))
16176             return unify_success (explain_p);
16177           else if (targ)
16178             return unify_inconsistency (explain_p, parm, targ, arg);
16179
16180           /* Make sure that ARG is not a variable-sized array.  (Note
16181              that were talking about variable-sized arrays (like
16182              `int[n]'), rather than arrays of unknown size (like
16183              `int[]').)  We'll get very confused by such a type since
16184              the bound of the array is not constant, and therefore
16185              not mangleable.  Besides, such types are not allowed in
16186              ISO C++, so we can do as we please here.  We do allow
16187              them for 'auto' deduction, since that isn't ABI-exposed.  */
16188           if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16189             return unify_vla_arg (explain_p, arg);
16190
16191           /* Strip typedefs as in convert_template_argument.  */
16192           arg = canonicalize_type_argument (arg, tf_none);
16193         }
16194
16195       /* If ARG is a parameter pack or an expansion, we cannot unify
16196          against it unless PARM is also a parameter pack.  */
16197       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16198           && !template_parameter_pack_p (parm))
16199         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16200
16201       /* If the argument deduction results is a METHOD_TYPE,
16202          then there is a problem.
16203          METHOD_TYPE doesn't map to any real C++ type the result of
16204          the deduction can not be of that type.  */
16205       if (TREE_CODE (arg) == METHOD_TYPE)
16206         return unify_method_type_error (explain_p, arg);
16207
16208       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16209       return unify_success (explain_p);
16210
16211     case TEMPLATE_PARM_INDEX:
16212       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16213       if (tparm == error_mark_node)
16214         return unify_invalid (explain_p);
16215
16216       if (TEMPLATE_PARM_LEVEL (parm)
16217           != template_decl_level (tparm))
16218         {
16219           /* The PARM is not one we're trying to unify.  Just check
16220              to see if it matches ARG.  */
16221           int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16222                          && cp_tree_equal (parm, arg));
16223           if (result)
16224             unify_expression_unequal (explain_p, parm, arg);
16225           return result;
16226         }
16227
16228       idx = TEMPLATE_PARM_IDX (parm);
16229       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16230
16231       if (targ)
16232         {
16233           int x = !cp_tree_equal (targ, arg);
16234           if (x)
16235             unify_inconsistency (explain_p, parm, targ, arg);
16236           return x;
16237         }
16238
16239       /* [temp.deduct.type] If, in the declaration of a function template
16240          with a non-type template-parameter, the non-type
16241          template-parameter is used in an expression in the function
16242          parameter-list and, if the corresponding template-argument is
16243          deduced, the template-argument type shall match the type of the
16244          template-parameter exactly, except that a template-argument
16245          deduced from an array bound may be of any integral type.
16246          The non-type parameter might use already deduced type parameters.  */
16247       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16248       if (!TREE_TYPE (arg))
16249         /* Template-parameter dependent expression.  Just accept it for now.
16250            It will later be processed in convert_template_argument.  */
16251         ;
16252       else if (same_type_p (TREE_TYPE (arg), tparm))
16253         /* OK */;
16254       else if ((strict & UNIFY_ALLOW_INTEGER)
16255                && (TREE_CODE (tparm) == INTEGER_TYPE
16256                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
16257         /* Convert the ARG to the type of PARM; the deduced non-type
16258            template argument must exactly match the types of the
16259            corresponding parameter.  */
16260         arg = fold (build_nop (tparm, arg));
16261       else if (uses_template_parms (tparm))
16262         /* We haven't deduced the type of this parameter yet.  Try again
16263            later.  */
16264         return unify_success (explain_p);
16265       else
16266         return unify_type_mismatch (explain_p, tparm, arg);
16267
16268       /* If ARG is a parameter pack or an expansion, we cannot unify
16269          against it unless PARM is also a parameter pack.  */
16270       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16271           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16272         return unify_parameter_pack_mismatch (explain_p, parm, arg);
16273
16274       arg = strip_typedefs_expr (arg);
16275       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16276       return unify_success (explain_p);
16277
16278     case PTRMEM_CST:
16279      {
16280         /* A pointer-to-member constant can be unified only with
16281          another constant.  */
16282       if (TREE_CODE (arg) != PTRMEM_CST)
16283         return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16284
16285       /* Just unify the class member. It would be useless (and possibly
16286          wrong, depending on the strict flags) to unify also
16287          PTRMEM_CST_CLASS, because we want to be sure that both parm and
16288          arg refer to the same variable, even if through different
16289          classes. For instance:
16290
16291          struct A { int x; };
16292          struct B : A { };
16293
16294          Unification of &A::x and &B::x must succeed.  */
16295       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16296                     PTRMEM_CST_MEMBER (arg), strict, explain_p);
16297      }
16298
16299     case POINTER_TYPE:
16300       {
16301         if (TREE_CODE (arg) != POINTER_TYPE)
16302           return unify_type_mismatch (explain_p, parm, arg);
16303
16304         /* [temp.deduct.call]
16305
16306            A can be another pointer or pointer to member type that can
16307            be converted to the deduced A via a qualification
16308            conversion (_conv.qual_).
16309
16310            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16311            This will allow for additional cv-qualification of the
16312            pointed-to types if appropriate.  */
16313
16314         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16315           /* The derived-to-base conversion only persists through one
16316              level of pointers.  */
16317           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16318
16319         return unify (tparms, targs, TREE_TYPE (parm),
16320                       TREE_TYPE (arg), strict, explain_p);
16321       }
16322
16323     case REFERENCE_TYPE:
16324       if (TREE_CODE (arg) != REFERENCE_TYPE)
16325         return unify_type_mismatch (explain_p, parm, arg);
16326       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16327                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16328
16329     case ARRAY_TYPE:
16330       if (TREE_CODE (arg) != ARRAY_TYPE)
16331         return unify_type_mismatch (explain_p, parm, arg);
16332       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16333           != (TYPE_DOMAIN (arg) == NULL_TREE))
16334         return unify_type_mismatch (explain_p, parm, arg);
16335       if (TYPE_DOMAIN (parm) != NULL_TREE)
16336         {
16337           tree parm_max;
16338           tree arg_max;
16339           bool parm_cst;
16340           bool arg_cst;
16341
16342           /* Our representation of array types uses "N - 1" as the
16343              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16344              not an integer constant.  We cannot unify arbitrarily
16345              complex expressions, so we eliminate the MINUS_EXPRs
16346              here.  */
16347           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16348           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16349           if (!parm_cst)
16350             {
16351               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16352               parm_max = TREE_OPERAND (parm_max, 0);
16353             }
16354           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16355           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16356           if (!arg_cst)
16357             {
16358               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16359                  trying to unify the type of a variable with the type
16360                  of a template parameter.  For example:
16361
16362                    template <unsigned int N>
16363                    void f (char (&) [N]);
16364                    int g(); 
16365                    void h(int i) {
16366                      char a[g(i)];
16367                      f(a); 
16368                    }
16369
16370                 Here, the type of the ARG will be "int [g(i)]", and
16371                 may be a SAVE_EXPR, etc.  */
16372               if (TREE_CODE (arg_max) != MINUS_EXPR)
16373                 return unify_vla_arg (explain_p, arg);
16374               arg_max = TREE_OPERAND (arg_max, 0);
16375             }
16376
16377           /* If only one of the bounds used a MINUS_EXPR, compensate
16378              by adding one to the other bound.  */
16379           if (parm_cst && !arg_cst)
16380             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16381                                     integer_type_node,
16382                                     parm_max,
16383                                     integer_one_node);
16384           else if (arg_cst && !parm_cst)
16385             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16386                                    integer_type_node,
16387                                    arg_max,
16388                                    integer_one_node);
16389
16390           RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16391                                    UNIFY_ALLOW_INTEGER, explain_p);
16392         }
16393       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16394                     strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16395
16396     case REAL_TYPE:
16397     case COMPLEX_TYPE:
16398     case VECTOR_TYPE:
16399     case INTEGER_TYPE:
16400     case BOOLEAN_TYPE:
16401     case ENUMERAL_TYPE:
16402     case VOID_TYPE:
16403     case NULLPTR_TYPE:
16404       if (TREE_CODE (arg) != TREE_CODE (parm))
16405         return unify_type_mismatch (explain_p, parm, arg);
16406
16407       /* We have already checked cv-qualification at the top of the
16408          function.  */
16409       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16410         return unify_type_mismatch (explain_p, parm, arg);
16411
16412       /* As far as unification is concerned, this wins.  Later checks
16413          will invalidate it if necessary.  */
16414       return unify_success (explain_p);
16415
16416       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16417       /* Type INTEGER_CST can come from ordinary constant template args.  */
16418     case INTEGER_CST:
16419       while (TREE_CODE (arg) == NOP_EXPR)
16420         arg = TREE_OPERAND (arg, 0);
16421
16422       if (TREE_CODE (arg) != INTEGER_CST)
16423         return unify_template_argument_mismatch (explain_p, parm, arg);
16424       return (tree_int_cst_equal (parm, arg)
16425               ? unify_success (explain_p)
16426               : unify_template_argument_mismatch (explain_p, parm, arg));
16427
16428     case TREE_VEC:
16429       {
16430         int i, len, argslen;
16431         int parm_variadic_p = 0;
16432
16433         if (TREE_CODE (arg) != TREE_VEC)
16434           return unify_template_argument_mismatch (explain_p, parm, arg);
16435
16436         len = TREE_VEC_LENGTH (parm);
16437         argslen = TREE_VEC_LENGTH (arg);
16438
16439         /* Check for pack expansions in the parameters.  */
16440         for (i = 0; i < len; ++i)
16441           {
16442             if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16443               {
16444                 if (i == len - 1)
16445                   /* We can unify against something with a trailing
16446                      parameter pack.  */
16447                   parm_variadic_p = 1;
16448                 else
16449                   /* [temp.deduct.type]/9: If the template argument list of
16450                      P contains a pack expansion that is not the last
16451                      template argument, the entire template argument list
16452                      is a non-deduced context.  */
16453                   return unify_success (explain_p);
16454               }
16455           }
16456
16457         /* If we don't have enough arguments to satisfy the parameters
16458            (not counting the pack expression at the end), or we have
16459            too many arguments for a parameter list that doesn't end in
16460            a pack expression, we can't unify.  */
16461         if (parm_variadic_p
16462             ? argslen < len - parm_variadic_p
16463             : argslen != len)
16464           return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16465
16466         /* Unify all of the parameters that precede the (optional)
16467            pack expression.  */
16468         for (i = 0; i < len - parm_variadic_p; ++i)
16469           {
16470             RECUR_AND_CHECK_FAILURE (tparms, targs,
16471                                      TREE_VEC_ELT (parm, i),
16472                                      TREE_VEC_ELT (arg, i),
16473                                      UNIFY_ALLOW_NONE, explain_p);
16474           }
16475         if (parm_variadic_p)
16476           return unify_pack_expansion (tparms, targs, parm, arg,
16477                                        DEDUCE_EXACT,
16478                                        /*subr=*/true, explain_p);
16479         return unify_success (explain_p);
16480       }
16481
16482     case RECORD_TYPE:
16483     case UNION_TYPE:
16484       if (TREE_CODE (arg) != TREE_CODE (parm))
16485         return unify_type_mismatch (explain_p, parm, arg);
16486
16487       if (TYPE_PTRMEMFUNC_P (parm))
16488         {
16489           if (!TYPE_PTRMEMFUNC_P (arg))
16490             return unify_type_mismatch (explain_p, parm, arg);
16491
16492           return unify (tparms, targs,
16493                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
16494                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
16495                         strict, explain_p);
16496         }
16497
16498       if (CLASSTYPE_TEMPLATE_INFO (parm))
16499         {
16500           tree t = NULL_TREE;
16501
16502           if (strict_in & UNIFY_ALLOW_DERIVED)
16503             {
16504               /* First, we try to unify the PARM and ARG directly.  */
16505               t = try_class_unification (tparms, targs,
16506                                          parm, arg, explain_p);
16507
16508               if (!t)
16509                 {
16510                   /* Fallback to the special case allowed in
16511                      [temp.deduct.call]:
16512
16513                        If P is a class, and P has the form
16514                        template-id, then A can be a derived class of
16515                        the deduced A.  Likewise, if P is a pointer to
16516                        a class of the form template-id, A can be a
16517                        pointer to a derived class pointed to by the
16518                        deduced A.  */
16519                   enum template_base_result r;
16520                   r = get_template_base (tparms, targs, parm, arg,
16521                                          explain_p, &t);
16522
16523                   if (!t)
16524                     return unify_no_common_base (explain_p, r, parm, arg);
16525                 }
16526             }
16527           else if (CLASSTYPE_TEMPLATE_INFO (arg)
16528                    && (CLASSTYPE_TI_TEMPLATE (parm)
16529                        == CLASSTYPE_TI_TEMPLATE (arg)))
16530             /* Perhaps PARM is something like S<U> and ARG is S<int>.
16531                Then, we should unify `int' and `U'.  */
16532             t = arg;
16533           else
16534             /* There's no chance of unification succeeding.  */
16535             return unify_type_mismatch (explain_p, parm, arg);
16536
16537           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
16538                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
16539         }
16540       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
16541         return unify_type_mismatch (explain_p, parm, arg);
16542       return unify_success (explain_p);
16543
16544     case METHOD_TYPE:
16545     case FUNCTION_TYPE:
16546       {
16547         unsigned int nargs;
16548         tree *args;
16549         tree a;
16550         unsigned int i;
16551
16552         if (TREE_CODE (arg) != TREE_CODE (parm))
16553           return unify_type_mismatch (explain_p, parm, arg);
16554
16555         /* CV qualifications for methods can never be deduced, they must
16556            match exactly.  We need to check them explicitly here,
16557            because type_unification_real treats them as any other
16558            cv-qualified parameter.  */
16559         if (TREE_CODE (parm) == METHOD_TYPE
16560             && (!check_cv_quals_for_unify
16561                 (UNIFY_ALLOW_NONE,
16562                  class_of_this_parm (arg),
16563                  class_of_this_parm (parm))))
16564           return unify_cv_qual_mismatch (explain_p, parm, arg);
16565
16566         RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
16567                                  TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
16568
16569         nargs = list_length (TYPE_ARG_TYPES (arg));
16570         args = XALLOCAVEC (tree, nargs);
16571         for (a = TYPE_ARG_TYPES (arg), i = 0;
16572              a != NULL_TREE && a != void_list_node;
16573              a = TREE_CHAIN (a), ++i)
16574           args[i] = TREE_VALUE (a);
16575         nargs = i;
16576
16577         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
16578                                       args, nargs, 1, DEDUCE_EXACT,
16579                                       LOOKUP_NORMAL, explain_p);
16580       }
16581
16582     case OFFSET_TYPE:
16583       /* Unify a pointer to member with a pointer to member function, which
16584          deduces the type of the member as a function type. */
16585       if (TYPE_PTRMEMFUNC_P (arg))
16586         {
16587           tree method_type;
16588           tree fntype;
16589
16590           /* Check top-level cv qualifiers */
16591           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
16592             return unify_cv_qual_mismatch (explain_p, parm, arg);
16593
16594           RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16595                                    TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
16596                                    UNIFY_ALLOW_NONE, explain_p);
16597
16598           /* Determine the type of the function we are unifying against. */
16599           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
16600           fntype =
16601             build_function_type (TREE_TYPE (method_type),
16602                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
16603
16604           /* Extract the cv-qualifiers of the member function from the
16605              implicit object parameter and place them on the function
16606              type to be restored later. */
16607           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
16608           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
16609         }
16610
16611       if (TREE_CODE (arg) != OFFSET_TYPE)
16612         return unify_type_mismatch (explain_p, parm, arg);
16613       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
16614                                TYPE_OFFSET_BASETYPE (arg),
16615                                UNIFY_ALLOW_NONE, explain_p);
16616       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16617                     strict, explain_p);
16618
16619     case CONST_DECL:
16620       if (DECL_TEMPLATE_PARM_P (parm))
16621         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
16622       if (arg != integral_constant_value (parm))
16623         return unify_template_argument_mismatch (explain_p, parm, arg);
16624       return unify_success (explain_p);
16625
16626     case FIELD_DECL:
16627     case TEMPLATE_DECL:
16628       /* Matched cases are handled by the ARG == PARM test above.  */
16629       return unify_template_argument_mismatch (explain_p, parm, arg);
16630
16631     case VAR_DECL:
16632       /* A non-type template parameter that is a variable should be a
16633          an integral constant, in which case, it whould have been
16634          folded into its (constant) value. So we should not be getting
16635          a variable here.  */
16636       gcc_unreachable ();
16637
16638     case TYPE_ARGUMENT_PACK:
16639     case NONTYPE_ARGUMENT_PACK:
16640       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
16641                     ARGUMENT_PACK_ARGS (arg), strict, explain_p);
16642
16643     case TYPEOF_TYPE:
16644     case DECLTYPE_TYPE:
16645     case UNDERLYING_TYPE:
16646       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
16647          or UNDERLYING_TYPE nodes.  */
16648       return unify_success (explain_p);
16649
16650     case ERROR_MARK:
16651       /* Unification fails if we hit an error node.  */
16652       return unify_invalid (explain_p);
16653
16654     default:
16655       /* An unresolved overload is a nondeduced context.  */
16656       if (is_overloaded_fn (parm) || type_unknown_p (parm))
16657         return unify_success (explain_p);
16658       gcc_assert (EXPR_P (parm));
16659
16660       /* We must be looking at an expression.  This can happen with
16661          something like:
16662
16663            template <int I>
16664            void foo(S<I>, S<I + 2>);
16665
16666          This is a "nondeduced context":
16667
16668            [deduct.type]
16669
16670            The nondeduced contexts are:
16671
16672            --A type that is a template-id in which one or more of
16673              the template-arguments is an expression that references
16674              a template-parameter.
16675
16676          In these cases, we assume deduction succeeded, but don't
16677          actually infer any unifications.  */
16678
16679       if (!uses_template_parms (parm)
16680           && !template_args_equal (parm, arg))
16681         return unify_expression_unequal (explain_p, parm, arg);
16682       else
16683         return unify_success (explain_p);
16684     }
16685 }
16686 #undef RECUR_AND_CHECK_FAILURE
16687 \f
16688 /* Note that DECL can be defined in this translation unit, if
16689    required.  */
16690
16691 static void
16692 mark_definable (tree decl)
16693 {
16694   tree clone;
16695   DECL_NOT_REALLY_EXTERN (decl) = 1;
16696   FOR_EACH_CLONE (clone, decl)
16697     DECL_NOT_REALLY_EXTERN (clone) = 1;
16698 }
16699
16700 /* Called if RESULT is explicitly instantiated, or is a member of an
16701    explicitly instantiated class.  */
16702
16703 void
16704 mark_decl_instantiated (tree result, int extern_p)
16705 {
16706   SET_DECL_EXPLICIT_INSTANTIATION (result);
16707
16708   /* If this entity has already been written out, it's too late to
16709      make any modifications.  */
16710   if (TREE_ASM_WRITTEN (result))
16711     return;
16712
16713   if (TREE_CODE (result) != FUNCTION_DECL)
16714     /* The TREE_PUBLIC flag for function declarations will have been
16715        set correctly by tsubst.  */
16716     TREE_PUBLIC (result) = 1;
16717
16718   /* This might have been set by an earlier implicit instantiation.  */
16719   DECL_COMDAT (result) = 0;
16720
16721   if (extern_p)
16722     DECL_NOT_REALLY_EXTERN (result) = 0;
16723   else
16724     {
16725       mark_definable (result);
16726       /* Always make artificials weak.  */
16727       if (DECL_ARTIFICIAL (result) && flag_weak)
16728         comdat_linkage (result);
16729       /* For WIN32 we also want to put explicit instantiations in
16730          linkonce sections.  */
16731       else if (TREE_PUBLIC (result))
16732         maybe_make_one_only (result);
16733     }
16734
16735   /* If EXTERN_P, then this function will not be emitted -- unless
16736      followed by an explicit instantiation, at which point its linkage
16737      will be adjusted.  If !EXTERN_P, then this function will be
16738      emitted here.  In neither circumstance do we want
16739      import_export_decl to adjust the linkage.  */
16740   DECL_INTERFACE_KNOWN (result) = 1;
16741 }
16742
16743 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
16744    important template arguments.  If any are missing, we check whether
16745    they're important by using error_mark_node for substituting into any
16746    args that were used for partial ordering (the ones between ARGS and END)
16747    and seeing if it bubbles up.  */
16748
16749 static bool
16750 check_undeduced_parms (tree targs, tree args, tree end)
16751 {
16752   bool found = false;
16753   int i;
16754   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
16755     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
16756       {
16757         found = true;
16758         TREE_VEC_ELT (targs, i) = error_mark_node;
16759       }
16760   if (found)
16761     {
16762       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
16763       if (substed == error_mark_node)
16764         return true;
16765     }
16766   return false;
16767 }
16768
16769 /* Given two function templates PAT1 and PAT2, return:
16770
16771    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
16772    -1 if PAT2 is more specialized than PAT1.
16773    0 if neither is more specialized.
16774
16775    LEN indicates the number of parameters we should consider
16776    (defaulted parameters should not be considered).
16777
16778    The 1998 std underspecified function template partial ordering, and
16779    DR214 addresses the issue.  We take pairs of arguments, one from
16780    each of the templates, and deduce them against each other.  One of
16781    the templates will be more specialized if all the *other*
16782    template's arguments deduce against its arguments and at least one
16783    of its arguments *does* *not* deduce against the other template's
16784    corresponding argument.  Deduction is done as for class templates.
16785    The arguments used in deduction have reference and top level cv
16786    qualifiers removed.  Iff both arguments were originally reference
16787    types *and* deduction succeeds in both directions, the template
16788    with the more cv-qualified argument wins for that pairing (if
16789    neither is more cv-qualified, they both are equal).  Unlike regular
16790    deduction, after all the arguments have been deduced in this way,
16791    we do *not* verify the deduced template argument values can be
16792    substituted into non-deduced contexts.
16793
16794    The logic can be a bit confusing here, because we look at deduce1 and
16795    targs1 to see if pat2 is at least as specialized, and vice versa; if we
16796    can find template arguments for pat1 to make arg1 look like arg2, that
16797    means that arg2 is at least as specialized as arg1.  */
16798
16799 int
16800 more_specialized_fn (tree pat1, tree pat2, int len)
16801 {
16802   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
16803   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
16804   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
16805   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
16806   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
16807   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
16808   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
16809   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
16810   tree origs1, origs2;
16811   bool lose1 = false;
16812   bool lose2 = false;
16813
16814   /* Remove the this parameter from non-static member functions.  If
16815      one is a non-static member function and the other is not a static
16816      member function, remove the first parameter from that function
16817      also.  This situation occurs for operator functions where we
16818      locate both a member function (with this pointer) and non-member
16819      operator (with explicit first operand).  */
16820   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
16821     {
16822       len--; /* LEN is the number of significant arguments for DECL1 */
16823       args1 = TREE_CHAIN (args1);
16824       if (!DECL_STATIC_FUNCTION_P (decl2))
16825         args2 = TREE_CHAIN (args2);
16826     }
16827   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
16828     {
16829       args2 = TREE_CHAIN (args2);
16830       if (!DECL_STATIC_FUNCTION_P (decl1))
16831         {
16832           len--;
16833           args1 = TREE_CHAIN (args1);
16834         }
16835     }
16836
16837   /* If only one is a conversion operator, they are unordered.  */
16838   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
16839     return 0;
16840
16841   /* Consider the return type for a conversion function */
16842   if (DECL_CONV_FN_P (decl1))
16843     {
16844       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
16845       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
16846       len++;
16847     }
16848
16849   processing_template_decl++;
16850
16851   origs1 = args1;
16852   origs2 = args2;
16853
16854   while (len--
16855          /* Stop when an ellipsis is seen.  */
16856          && args1 != NULL_TREE && args2 != NULL_TREE)
16857     {
16858       tree arg1 = TREE_VALUE (args1);
16859       tree arg2 = TREE_VALUE (args2);
16860       int deduce1, deduce2;
16861       int quals1 = -1;
16862       int quals2 = -1;
16863
16864       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
16865           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16866         {
16867           /* When both arguments are pack expansions, we need only
16868              unify the patterns themselves.  */
16869           arg1 = PACK_EXPANSION_PATTERN (arg1);
16870           arg2 = PACK_EXPANSION_PATTERN (arg2);
16871
16872           /* This is the last comparison we need to do.  */
16873           len = 0;
16874         }
16875
16876       if (TREE_CODE (arg1) == REFERENCE_TYPE)
16877         {
16878           arg1 = TREE_TYPE (arg1);
16879           quals1 = cp_type_quals (arg1);
16880         }
16881
16882       if (TREE_CODE (arg2) == REFERENCE_TYPE)
16883         {
16884           arg2 = TREE_TYPE (arg2);
16885           quals2 = cp_type_quals (arg2);
16886         }
16887
16888       if ((quals1 < 0) != (quals2 < 0))
16889         {
16890           /* Only of the args is a reference, see if we should apply
16891              array/function pointer decay to it.  This is not part of
16892              DR214, but is, IMHO, consistent with the deduction rules
16893              for the function call itself, and with our earlier
16894              implementation of the underspecified partial ordering
16895              rules.  (nathan).  */
16896           if (quals1 >= 0)
16897             {
16898               switch (TREE_CODE (arg1))
16899                 {
16900                 case ARRAY_TYPE:
16901                   arg1 = TREE_TYPE (arg1);
16902                   /* FALLTHROUGH. */
16903                 case FUNCTION_TYPE:
16904                   arg1 = build_pointer_type (arg1);
16905                   break;
16906
16907                 default:
16908                   break;
16909                 }
16910             }
16911           else
16912             {
16913               switch (TREE_CODE (arg2))
16914                 {
16915                 case ARRAY_TYPE:
16916                   arg2 = TREE_TYPE (arg2);
16917                   /* FALLTHROUGH. */
16918                 case FUNCTION_TYPE:
16919                   arg2 = build_pointer_type (arg2);
16920                   break;
16921
16922                 default:
16923                   break;
16924                 }
16925             }
16926         }
16927
16928       arg1 = TYPE_MAIN_VARIANT (arg1);
16929       arg2 = TYPE_MAIN_VARIANT (arg2);
16930
16931       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
16932         {
16933           int i, len2 = list_length (args2);
16934           tree parmvec = make_tree_vec (1);
16935           tree argvec = make_tree_vec (len2);
16936           tree ta = args2;
16937
16938           /* Setup the parameter vector, which contains only ARG1.  */
16939           TREE_VEC_ELT (parmvec, 0) = arg1;
16940
16941           /* Setup the argument vector, which contains the remaining
16942              arguments.  */
16943           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
16944             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16945
16946           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
16947                                            argvec, DEDUCE_EXACT,
16948                                            /*subr=*/true, /*explain_p=*/false)
16949                      == 0);
16950
16951           /* We cannot deduce in the other direction, because ARG1 is
16952              a pack expansion but ARG2 is not.  */
16953           deduce2 = 0;
16954         }
16955       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
16956         {
16957           int i, len1 = list_length (args1);
16958           tree parmvec = make_tree_vec (1);
16959           tree argvec = make_tree_vec (len1);
16960           tree ta = args1;
16961
16962           /* Setup the parameter vector, which contains only ARG1.  */
16963           TREE_VEC_ELT (parmvec, 0) = arg2;
16964
16965           /* Setup the argument vector, which contains the remaining
16966              arguments.  */
16967           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
16968             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
16969
16970           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
16971                                            argvec, DEDUCE_EXACT,
16972                                            /*subr=*/true, /*explain_p=*/false)
16973                      == 0);
16974
16975           /* We cannot deduce in the other direction, because ARG2 is
16976              a pack expansion but ARG1 is not.*/
16977           deduce1 = 0;
16978         }
16979
16980       else
16981         {
16982           /* The normal case, where neither argument is a pack
16983              expansion.  */
16984           deduce1 = (unify (tparms1, targs1, arg1, arg2,
16985                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16986                      == 0);
16987           deduce2 = (unify (tparms2, targs2, arg2, arg1,
16988                             UNIFY_ALLOW_NONE, /*explain_p=*/false)
16989                      == 0);
16990         }
16991
16992       /* If we couldn't deduce arguments for tparms1 to make arg1 match
16993          arg2, then arg2 is not as specialized as arg1.  */
16994       if (!deduce1)
16995         lose2 = true;
16996       if (!deduce2)
16997         lose1 = true;
16998
16999       /* "If, for a given type, deduction succeeds in both directions
17000          (i.e., the types are identical after the transformations above)
17001          and if the type from the argument template is more cv-qualified
17002          than the type from the parameter template (as described above)
17003          that type is considered to be more specialized than the other. If
17004          neither type is more cv-qualified than the other then neither type
17005          is more specialized than the other."  */
17006
17007       if (deduce1 && deduce2
17008           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
17009         {
17010           if ((quals1 & quals2) == quals2)
17011             lose2 = true;
17012           if ((quals1 & quals2) == quals1)
17013             lose1 = true;
17014         }
17015
17016       if (lose1 && lose2)
17017         /* We've failed to deduce something in either direction.
17018            These must be unordered.  */
17019         break;
17020
17021       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
17022           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17023         /* We have already processed all of the arguments in our
17024            handing of the pack expansion type.  */
17025         len = 0;
17026
17027       args1 = TREE_CHAIN (args1);
17028       args2 = TREE_CHAIN (args2);
17029     }
17030
17031   /* "In most cases, all template parameters must have values in order for
17032      deduction to succeed, but for partial ordering purposes a template
17033      parameter may remain without a value provided it is not used in the
17034      types being used for partial ordering."
17035
17036      Thus, if we are missing any of the targs1 we need to substitute into
17037      origs1, then pat2 is not as specialized as pat1.  This can happen when
17038      there is a nondeduced context.  */
17039   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
17040     lose2 = true;
17041   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
17042     lose1 = true;
17043
17044   processing_template_decl--;
17045
17046   /* All things being equal, if the next argument is a pack expansion
17047      for one function but not for the other, prefer the
17048      non-variadic function.  FIXME this is bogus; see c++/41958.  */
17049   if (lose1 == lose2
17050       && args1 && TREE_VALUE (args1)
17051       && args2 && TREE_VALUE (args2))
17052     {
17053       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
17054       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
17055     }
17056
17057   if (lose1 == lose2)
17058     return 0;
17059   else if (!lose1)
17060     return 1;
17061   else
17062     return -1;
17063 }
17064
17065 /* Determine which of two partial specializations is more specialized.
17066
17067    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
17068    to the first partial specialization.  The TREE_VALUE is the
17069    innermost set of template parameters for the partial
17070    specialization.  PAT2 is similar, but for the second template.
17071
17072    Return 1 if the first partial specialization is more specialized;
17073    -1 if the second is more specialized; 0 if neither is more
17074    specialized.
17075
17076    See [temp.class.order] for information about determining which of
17077    two templates is more specialized.  */
17078
17079 static int
17080 more_specialized_class (tree pat1, tree pat2)
17081 {
17082   tree targs;
17083   tree tmpl1, tmpl2;
17084   int winner = 0;
17085   bool any_deductions = false;
17086
17087   tmpl1 = TREE_TYPE (pat1);
17088   tmpl2 = TREE_TYPE (pat2);
17089
17090   /* Just like what happens for functions, if we are ordering between
17091      different class template specializations, we may encounter dependent
17092      types in the arguments, and we need our dependency check functions
17093      to behave correctly.  */
17094   ++processing_template_decl;
17095   targs = get_class_bindings (TREE_VALUE (pat1),
17096                               CLASSTYPE_TI_ARGS (tmpl1),
17097                               CLASSTYPE_TI_ARGS (tmpl2));
17098   if (targs)
17099     {
17100       --winner;
17101       any_deductions = true;
17102     }
17103
17104   targs = get_class_bindings (TREE_VALUE (pat2),
17105                               CLASSTYPE_TI_ARGS (tmpl2),
17106                               CLASSTYPE_TI_ARGS (tmpl1));
17107   if (targs)
17108     {
17109       ++winner;
17110       any_deductions = true;
17111     }
17112   --processing_template_decl;
17113
17114   /* In the case of a tie where at least one of the class templates
17115      has a parameter pack at the end, the template with the most
17116      non-packed parameters wins.  */
17117   if (winner == 0
17118       && any_deductions
17119       && (template_args_variadic_p (TREE_PURPOSE (pat1))
17120           || template_args_variadic_p (TREE_PURPOSE (pat2))))
17121     {
17122       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
17123       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
17124       int len1 = TREE_VEC_LENGTH (args1);
17125       int len2 = TREE_VEC_LENGTH (args2);
17126
17127       /* We don't count the pack expansion at the end.  */
17128       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
17129         --len1;
17130       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
17131         --len2;
17132
17133       if (len1 > len2)
17134         return 1;
17135       else if (len1 < len2)
17136         return -1;
17137     }
17138
17139   return winner;
17140 }
17141
17142 /* Return the template arguments that will produce the function signature
17143    DECL from the function template FN, with the explicit template
17144    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17145    also match.  Return NULL_TREE if no satisfactory arguments could be
17146    found.  */
17147
17148 static tree
17149 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17150 {
17151   int ntparms = DECL_NTPARMS (fn);
17152   tree targs = make_tree_vec (ntparms);
17153   tree decl_type;
17154   tree decl_arg_types;
17155   tree *args;
17156   unsigned int nargs, ix;
17157   tree arg;
17158
17159   /* Substitute the explicit template arguments into the type of DECL.
17160      The call to fn_type_unification will handle substitution into the
17161      FN.  */
17162   decl_type = TREE_TYPE (decl);
17163   if (explicit_args && uses_template_parms (decl_type))
17164     {
17165       tree tmpl;
17166       tree converted_args;
17167
17168       if (DECL_TEMPLATE_INFO (decl))
17169         tmpl = DECL_TI_TEMPLATE (decl);
17170       else
17171         /* We can get here for some invalid specializations.  */
17172         return NULL_TREE;
17173
17174       converted_args
17175         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17176                                  explicit_args, NULL_TREE,
17177                                  tf_none,
17178                                  /*require_all_args=*/false,
17179                                  /*use_default_args=*/false);
17180       if (converted_args == error_mark_node)
17181         return NULL_TREE;
17182
17183       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
17184       if (decl_type == error_mark_node)
17185         return NULL_TREE;
17186     }
17187
17188   /* Never do unification on the 'this' parameter.  */
17189   decl_arg_types = skip_artificial_parms_for (decl, 
17190                                               TYPE_ARG_TYPES (decl_type));
17191
17192   nargs = list_length (decl_arg_types);
17193   args = XALLOCAVEC (tree, nargs);
17194   for (arg = decl_arg_types, ix = 0;
17195        arg != NULL_TREE && arg != void_list_node;
17196        arg = TREE_CHAIN (arg), ++ix)
17197     args[ix] = TREE_VALUE (arg);
17198
17199   if (fn_type_unification (fn, explicit_args, targs,
17200                            args, ix,
17201                            (check_rettype || DECL_CONV_FN_P (fn)
17202                             ? TREE_TYPE (decl_type) : NULL_TREE),
17203                            DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false))
17204     return NULL_TREE;
17205
17206   return targs;
17207 }
17208
17209 /* Return the innermost template arguments that, when applied to a
17210    template specialization whose innermost template parameters are
17211    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17212    ARGS.
17213
17214    For example, suppose we have:
17215
17216      template <class T, class U> struct S {};
17217      template <class T> struct S<T*, int> {};
17218
17219    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17220    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17221    int}.  The resulting vector will be {double}, indicating that `T'
17222    is bound to `double'.  */
17223
17224 static tree
17225 get_class_bindings (tree tparms, tree spec_args, tree args)
17226 {
17227   int i, ntparms = TREE_VEC_LENGTH (tparms);
17228   tree deduced_args;
17229   tree innermost_deduced_args;
17230
17231   innermost_deduced_args = make_tree_vec (ntparms);
17232   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17233     {
17234       deduced_args = copy_node (args);
17235       SET_TMPL_ARGS_LEVEL (deduced_args,
17236                            TMPL_ARGS_DEPTH (deduced_args),
17237                            innermost_deduced_args);
17238     }
17239   else
17240     deduced_args = innermost_deduced_args;
17241
17242   if (unify (tparms, deduced_args,
17243              INNERMOST_TEMPLATE_ARGS (spec_args),
17244              INNERMOST_TEMPLATE_ARGS (args),
17245              UNIFY_ALLOW_NONE, /*explain_p=*/false))
17246     return NULL_TREE;
17247
17248   for (i =  0; i < ntparms; ++i)
17249     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17250       return NULL_TREE;
17251
17252   /* Verify that nondeduced template arguments agree with the type
17253      obtained from argument deduction.
17254
17255      For example:
17256
17257        struct A { typedef int X; };
17258        template <class T, class U> struct C {};
17259        template <class T> struct C<T, typename T::X> {};
17260
17261      Then with the instantiation `C<A, int>', we can deduce that
17262      `T' is `A' but unify () does not check whether `typename T::X'
17263      is `int'.  */
17264   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17265   if (spec_args == error_mark_node
17266       /* We only need to check the innermost arguments; the other
17267          arguments will always agree.  */
17268       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17269                               INNERMOST_TEMPLATE_ARGS (args)))
17270     return NULL_TREE;
17271
17272   /* Now that we have bindings for all of the template arguments,
17273      ensure that the arguments deduced for the template template
17274      parameters have compatible template parameter lists.  See the use
17275      of template_template_parm_bindings_ok_p in fn_type_unification
17276      for more information.  */
17277   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17278     return NULL_TREE;
17279
17280   return deduced_args;
17281 }
17282
17283 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17284    Return the TREE_LIST node with the most specialized template, if
17285    any.  If there is no most specialized template, the error_mark_node
17286    is returned.
17287
17288    Note that this function does not look at, or modify, the
17289    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17290    returned is one of the elements of INSTANTIATIONS, callers may
17291    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17292    and retrieve it from the value returned.  */
17293
17294 tree
17295 most_specialized_instantiation (tree templates)
17296 {
17297   tree fn, champ;
17298
17299   ++processing_template_decl;
17300
17301   champ = templates;
17302   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17303     {
17304       int fate = 0;
17305
17306       if (get_bindings (TREE_VALUE (champ),
17307                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17308                         NULL_TREE, /*check_ret=*/true))
17309         fate--;
17310
17311       if (get_bindings (TREE_VALUE (fn),
17312                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17313                         NULL_TREE, /*check_ret=*/true))
17314         fate++;
17315
17316       if (fate == -1)
17317         champ = fn;
17318       else if (!fate)
17319         {
17320           /* Equally specialized, move to next function.  If there
17321              is no next function, nothing's most specialized.  */
17322           fn = TREE_CHAIN (fn);
17323           champ = fn;
17324           if (!fn)
17325             break;
17326         }
17327     }
17328
17329   if (champ)
17330     /* Now verify that champ is better than everything earlier in the
17331        instantiation list.  */
17332     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17333       if (get_bindings (TREE_VALUE (champ),
17334                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17335                         NULL_TREE, /*check_ret=*/true)
17336           || !get_bindings (TREE_VALUE (fn),
17337                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17338                             NULL_TREE, /*check_ret=*/true))
17339         {
17340           champ = NULL_TREE;
17341           break;
17342         }
17343
17344   processing_template_decl--;
17345
17346   if (!champ)
17347     return error_mark_node;
17348
17349   return champ;
17350 }
17351
17352 /* If DECL is a specialization of some template, return the most
17353    general such template.  Otherwise, returns NULL_TREE.
17354
17355    For example, given:
17356
17357      template <class T> struct S { template <class U> void f(U); };
17358
17359    if TMPL is `template <class U> void S<int>::f(U)' this will return
17360    the full template.  This function will not trace past partial
17361    specializations, however.  For example, given in addition:
17362
17363      template <class T> struct S<T*> { template <class U> void f(U); };
17364
17365    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17366    `template <class T> template <class U> S<T*>::f(U)'.  */
17367
17368 tree
17369 most_general_template (tree decl)
17370 {
17371   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17372      an immediate specialization.  */
17373   if (TREE_CODE (decl) == FUNCTION_DECL)
17374     {
17375       if (DECL_TEMPLATE_INFO (decl)) {
17376         decl = DECL_TI_TEMPLATE (decl);
17377
17378         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17379            template friend.  */
17380         if (TREE_CODE (decl) != TEMPLATE_DECL)
17381           return NULL_TREE;
17382       } else
17383         return NULL_TREE;
17384     }
17385
17386   /* Look for more and more general templates.  */
17387   while (DECL_TEMPLATE_INFO (decl))
17388     {
17389       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17390          (See cp-tree.h for details.)  */
17391       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17392         break;
17393
17394       if (CLASS_TYPE_P (TREE_TYPE (decl))
17395           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17396         break;
17397
17398       /* Stop if we run into an explicitly specialized class template.  */
17399       if (!DECL_NAMESPACE_SCOPE_P (decl)
17400           && DECL_CONTEXT (decl)
17401           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17402         break;
17403
17404       decl = DECL_TI_TEMPLATE (decl);
17405     }
17406
17407   return decl;
17408 }
17409
17410 /* Return the most specialized of the class template partial
17411    specializations of TMPL which can produce TYPE, a specialization of
17412    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17413    a _TYPE node corresponding to the partial specialization, while the
17414    TREE_PURPOSE is the set of template arguments that must be
17415    substituted into the TREE_TYPE in order to generate TYPE.
17416
17417    If the choice of partial specialization is ambiguous, a diagnostic
17418    is issued, and the error_mark_node is returned.  If there are no
17419    partial specializations of TMPL matching TYPE, then NULL_TREE is
17420    returned.  */
17421
17422 static tree
17423 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17424 {
17425   tree list = NULL_TREE;
17426   tree t;
17427   tree champ;
17428   int fate;
17429   bool ambiguous_p;
17430   tree args;
17431   tree outer_args = NULL_TREE;
17432
17433   tmpl = most_general_template (tmpl);
17434   args = CLASSTYPE_TI_ARGS (type);
17435
17436   /* For determining which partial specialization to use, only the
17437      innermost args are interesting.  */
17438   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17439     {
17440       outer_args = strip_innermost_template_args (args, 1);
17441       args = INNERMOST_TEMPLATE_ARGS (args);
17442     }
17443
17444   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17445     {
17446       tree partial_spec_args;
17447       tree spec_args;
17448       tree parms = TREE_VALUE (t);
17449
17450       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17451
17452       ++processing_template_decl;
17453
17454       if (outer_args)
17455         {
17456           int i;
17457
17458           /* Discard the outer levels of args, and then substitute in the
17459              template args from the enclosing class.  */
17460           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17461           partial_spec_args = tsubst_template_args
17462             (partial_spec_args, outer_args, tf_none, NULL_TREE);
17463
17464           /* PARMS already refers to just the innermost parms, but the
17465              template parms in partial_spec_args had their levels lowered
17466              by tsubst, so we need to do the same for the parm list.  We
17467              can't just tsubst the TREE_VEC itself, as tsubst wants to
17468              treat a TREE_VEC as an argument vector.  */
17469           parms = copy_node (parms);
17470           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17471             TREE_VEC_ELT (parms, i) =
17472               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17473
17474         }
17475
17476       partial_spec_args =
17477           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17478                                  add_to_template_args (outer_args,
17479                                                        partial_spec_args),
17480                                  tmpl, tf_none,
17481                                  /*require_all_args=*/true,
17482                                  /*use_default_args=*/true);
17483
17484       --processing_template_decl;
17485
17486       if (partial_spec_args == error_mark_node)
17487         return error_mark_node;
17488
17489       spec_args = get_class_bindings (parms,
17490                                       partial_spec_args,
17491                                       args);
17492       if (spec_args)
17493         {
17494           if (outer_args)
17495             spec_args = add_to_template_args (outer_args, spec_args);
17496           list = tree_cons (spec_args, TREE_VALUE (t), list);
17497           TREE_TYPE (list) = TREE_TYPE (t);
17498         }
17499     }
17500
17501   if (! list)
17502     return NULL_TREE;
17503
17504   ambiguous_p = false;
17505   t = list;
17506   champ = t;
17507   t = TREE_CHAIN (t);
17508   for (; t; t = TREE_CHAIN (t))
17509     {
17510       fate = more_specialized_class (champ, t);
17511       if (fate == 1)
17512         ;
17513       else
17514         {
17515           if (fate == 0)
17516             {
17517               t = TREE_CHAIN (t);
17518               if (! t)
17519                 {
17520                   ambiguous_p = true;
17521                   break;
17522                 }
17523             }
17524           champ = t;
17525         }
17526     }
17527
17528   if (!ambiguous_p)
17529     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17530       {
17531         fate = more_specialized_class (champ, t);
17532         if (fate != 1)
17533           {
17534             ambiguous_p = true;
17535             break;
17536           }
17537       }
17538
17539   if (ambiguous_p)
17540     {
17541       const char *str;
17542       char *spaces = NULL;
17543       if (!(complain & tf_error))
17544         return error_mark_node;
17545       error ("ambiguous class template instantiation for %q#T", type);
17546       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17547       for (t = list; t; t = TREE_CHAIN (t))
17548         {
17549           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17550           spaces = spaces ? spaces : get_spaces (str);
17551         }
17552       free (spaces);
17553       return error_mark_node;
17554     }
17555
17556   return champ;
17557 }
17558
17559 /* Explicitly instantiate DECL.  */
17560
17561 void
17562 do_decl_instantiation (tree decl, tree storage)
17563 {
17564   tree result = NULL_TREE;
17565   int extern_p = 0;
17566
17567   if (!decl || decl == error_mark_node)
17568     /* An error occurred, for which grokdeclarator has already issued
17569        an appropriate message.  */
17570     return;
17571   else if (! DECL_LANG_SPECIFIC (decl))
17572     {
17573       error ("explicit instantiation of non-template %q#D", decl);
17574       return;
17575     }
17576   else if (TREE_CODE (decl) == VAR_DECL)
17577     {
17578       /* There is an asymmetry here in the way VAR_DECLs and
17579          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
17580          the latter, the DECL we get back will be marked as a
17581          template instantiation, and the appropriate
17582          DECL_TEMPLATE_INFO will be set up.  This does not happen for
17583          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
17584          should handle VAR_DECLs as it currently handles
17585          FUNCTION_DECLs.  */
17586       if (!DECL_CLASS_SCOPE_P (decl))
17587         {
17588           error ("%qD is not a static data member of a class template", decl);
17589           return;
17590         }
17591       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
17592       if (!result || TREE_CODE (result) != VAR_DECL)
17593         {
17594           error ("no matching template for %qD found", decl);
17595           return;
17596         }
17597       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
17598         {
17599           error ("type %qT for explicit instantiation %qD does not match "
17600                  "declared type %qT", TREE_TYPE (result), decl,
17601                  TREE_TYPE (decl));
17602           return;
17603         }
17604     }
17605   else if (TREE_CODE (decl) != FUNCTION_DECL)
17606     {
17607       error ("explicit instantiation of %q#D", decl);
17608       return;
17609     }
17610   else
17611     result = decl;
17612
17613   /* Check for various error cases.  Note that if the explicit
17614      instantiation is valid the RESULT will currently be marked as an
17615      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
17616      until we get here.  */
17617
17618   if (DECL_TEMPLATE_SPECIALIZATION (result))
17619     {
17620       /* DR 259 [temp.spec].
17621
17622          Both an explicit instantiation and a declaration of an explicit
17623          specialization shall not appear in a program unless the explicit
17624          instantiation follows a declaration of the explicit specialization.
17625
17626          For a given set of template parameters, if an explicit
17627          instantiation of a template appears after a declaration of an
17628          explicit specialization for that template, the explicit
17629          instantiation has no effect.  */
17630       return;
17631     }
17632   else if (DECL_EXPLICIT_INSTANTIATION (result))
17633     {
17634       /* [temp.spec]
17635
17636          No program shall explicitly instantiate any template more
17637          than once.
17638
17639          We check DECL_NOT_REALLY_EXTERN so as not to complain when
17640          the first instantiation was `extern' and the second is not,
17641          and EXTERN_P for the opposite case.  */
17642       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
17643         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
17644       /* If an "extern" explicit instantiation follows an ordinary
17645          explicit instantiation, the template is instantiated.  */
17646       if (extern_p)
17647         return;
17648     }
17649   else if (!DECL_IMPLICIT_INSTANTIATION (result))
17650     {
17651       error ("no matching template for %qD found", result);
17652       return;
17653     }
17654   else if (!DECL_TEMPLATE_INFO (result))
17655     {
17656       permerror (input_location, "explicit instantiation of non-template %q#D", result);
17657       return;
17658     }
17659
17660   if (storage == NULL_TREE)
17661     ;
17662   else if (storage == ridpointers[(int) RID_EXTERN])
17663     {
17664       if (!in_system_header && (cxx_dialect == cxx98))
17665         pedwarn (input_location, OPT_pedantic, 
17666                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
17667                  "instantiations");
17668       extern_p = 1;
17669     }
17670   else
17671     error ("storage class %qD applied to template instantiation", storage);
17672
17673   check_explicit_instantiation_namespace (result);
17674   mark_decl_instantiated (result, extern_p);
17675   if (! extern_p)
17676     instantiate_decl (result, /*defer_ok=*/1,
17677                       /*expl_inst_class_mem_p=*/false);
17678 }
17679
17680 static void
17681 mark_class_instantiated (tree t, int extern_p)
17682 {
17683   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
17684   SET_CLASSTYPE_INTERFACE_KNOWN (t);
17685   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
17686   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
17687   if (! extern_p)
17688     {
17689       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
17690       rest_of_type_compilation (t, 1);
17691     }
17692 }
17693
17694 /* Called from do_type_instantiation through binding_table_foreach to
17695    do recursive instantiation for the type bound in ENTRY.  */
17696 static void
17697 bt_instantiate_type_proc (binding_entry entry, void *data)
17698 {
17699   tree storage = *(tree *) data;
17700
17701   if (MAYBE_CLASS_TYPE_P (entry->type)
17702       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
17703     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
17704 }
17705
17706 /* Called from do_type_instantiation to instantiate a member
17707    (a member function or a static member variable) of an
17708    explicitly instantiated class template.  */
17709 static void
17710 instantiate_class_member (tree decl, int extern_p)
17711 {
17712   mark_decl_instantiated (decl, extern_p);
17713   if (! extern_p)
17714     instantiate_decl (decl, /*defer_ok=*/1,
17715                       /*expl_inst_class_mem_p=*/true);
17716 }
17717
17718 /* Perform an explicit instantiation of template class T.  STORAGE, if
17719    non-null, is the RID for extern, inline or static.  COMPLAIN is
17720    nonzero if this is called from the parser, zero if called recursively,
17721    since the standard is unclear (as detailed below).  */
17722
17723 void
17724 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
17725 {
17726   int extern_p = 0;
17727   int nomem_p = 0;
17728   int static_p = 0;
17729   int previous_instantiation_extern_p = 0;
17730
17731   if (TREE_CODE (t) == TYPE_DECL)
17732     t = TREE_TYPE (t);
17733
17734   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
17735     {
17736       tree tmpl =
17737         (TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
17738       if (tmpl)
17739         error ("explicit instantiation of non-class template %qD", tmpl);
17740       else
17741         error ("explicit instantiation of non-template type %qT", t);
17742       return;
17743     }
17744
17745   complete_type (t);
17746
17747   if (!COMPLETE_TYPE_P (t))
17748     {
17749       if (complain & tf_error)
17750         error ("explicit instantiation of %q#T before definition of template",
17751                t);
17752       return;
17753     }
17754
17755   if (storage != NULL_TREE)
17756     {
17757       if (!in_system_header)
17758         {
17759           if (storage == ridpointers[(int) RID_EXTERN])
17760             {
17761               if (cxx_dialect == cxx98)
17762                 pedwarn (input_location, OPT_pedantic, 
17763                          "ISO C++ 1998 forbids the use of %<extern%> on "
17764                          "explicit instantiations");
17765             }
17766           else
17767             pedwarn (input_location, OPT_pedantic, 
17768                      "ISO C++ forbids the use of %qE"
17769                      " on explicit instantiations", storage);
17770         }
17771
17772       if (storage == ridpointers[(int) RID_INLINE])
17773         nomem_p = 1;
17774       else if (storage == ridpointers[(int) RID_EXTERN])
17775         extern_p = 1;
17776       else if (storage == ridpointers[(int) RID_STATIC])
17777         static_p = 1;
17778       else
17779         {
17780           error ("storage class %qD applied to template instantiation",
17781                  storage);
17782           extern_p = 0;
17783         }
17784     }
17785
17786   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
17787     {
17788       /* DR 259 [temp.spec].
17789
17790          Both an explicit instantiation and a declaration of an explicit
17791          specialization shall not appear in a program unless the explicit
17792          instantiation follows a declaration of the explicit specialization.
17793
17794          For a given set of template parameters, if an explicit
17795          instantiation of a template appears after a declaration of an
17796          explicit specialization for that template, the explicit
17797          instantiation has no effect.  */
17798       return;
17799     }
17800   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
17801     {
17802       /* [temp.spec]
17803
17804          No program shall explicitly instantiate any template more
17805          than once.
17806
17807          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
17808          instantiation was `extern'.  If EXTERN_P then the second is.
17809          These cases are OK.  */
17810       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
17811
17812       if (!previous_instantiation_extern_p && !extern_p
17813           && (complain & tf_error))
17814         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
17815
17816       /* If we've already instantiated the template, just return now.  */
17817       if (!CLASSTYPE_INTERFACE_ONLY (t))
17818         return;
17819     }
17820
17821   check_explicit_instantiation_namespace (TYPE_NAME (t));
17822   mark_class_instantiated (t, extern_p);
17823
17824   if (nomem_p)
17825     return;
17826
17827   {
17828     tree tmp;
17829
17830     /* In contrast to implicit instantiation, where only the
17831        declarations, and not the definitions, of members are
17832        instantiated, we have here:
17833
17834          [temp.explicit]
17835
17836          The explicit instantiation of a class template specialization
17837          implies the instantiation of all of its members not
17838          previously explicitly specialized in the translation unit
17839          containing the explicit instantiation.
17840
17841        Of course, we can't instantiate member template classes, since
17842        we don't have any arguments for them.  Note that the standard
17843        is unclear on whether the instantiation of the members are
17844        *explicit* instantiations or not.  However, the most natural
17845        interpretation is that it should be an explicit instantiation.  */
17846
17847     if (! static_p)
17848       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
17849         if (TREE_CODE (tmp) == FUNCTION_DECL
17850             && DECL_TEMPLATE_INSTANTIATION (tmp))
17851           instantiate_class_member (tmp, extern_p);
17852
17853     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
17854       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
17855         instantiate_class_member (tmp, extern_p);
17856
17857     if (CLASSTYPE_NESTED_UTDS (t))
17858       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
17859                              bt_instantiate_type_proc, &storage);
17860   }
17861 }
17862
17863 /* Given a function DECL, which is a specialization of TMPL, modify
17864    DECL to be a re-instantiation of TMPL with the same template
17865    arguments.  TMPL should be the template into which tsubst'ing
17866    should occur for DECL, not the most general template.
17867
17868    One reason for doing this is a scenario like this:
17869
17870      template <class T>
17871      void f(const T&, int i);
17872
17873      void g() { f(3, 7); }
17874
17875      template <class T>
17876      void f(const T& t, const int i) { }
17877
17878    Note that when the template is first instantiated, with
17879    instantiate_template, the resulting DECL will have no name for the
17880    first parameter, and the wrong type for the second.  So, when we go
17881    to instantiate the DECL, we regenerate it.  */
17882
17883 static void
17884 regenerate_decl_from_template (tree decl, tree tmpl)
17885 {
17886   /* The arguments used to instantiate DECL, from the most general
17887      template.  */
17888   tree args;
17889   tree code_pattern;
17890
17891   args = DECL_TI_ARGS (decl);
17892   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
17893
17894   /* Make sure that we can see identifiers, and compute access
17895      correctly.  */
17896   push_access_scope (decl);
17897
17898   if (TREE_CODE (decl) == FUNCTION_DECL)
17899     {
17900       tree decl_parm;
17901       tree pattern_parm;
17902       tree specs;
17903       int args_depth;
17904       int parms_depth;
17905
17906       args_depth = TMPL_ARGS_DEPTH (args);
17907       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
17908       if (args_depth > parms_depth)
17909         args = get_innermost_template_args (args, parms_depth);
17910
17911       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
17912                                               args, tf_error, NULL_TREE,
17913                                               /*defer_ok*/false);
17914       if (specs && specs != error_mark_node)
17915         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
17916                                                     specs);
17917
17918       /* Merge parameter declarations.  */
17919       decl_parm = skip_artificial_parms_for (decl,
17920                                              DECL_ARGUMENTS (decl));
17921       pattern_parm
17922         = skip_artificial_parms_for (code_pattern,
17923                                      DECL_ARGUMENTS (code_pattern));
17924       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
17925         {
17926           tree parm_type;
17927           tree attributes;
17928           
17929           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17930             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
17931           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
17932                               NULL_TREE);
17933           parm_type = type_decays_to (parm_type);
17934           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17935             TREE_TYPE (decl_parm) = parm_type;
17936           attributes = DECL_ATTRIBUTES (pattern_parm);
17937           if (DECL_ATTRIBUTES (decl_parm) != attributes)
17938             {
17939               DECL_ATTRIBUTES (decl_parm) = attributes;
17940               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17941             }
17942           decl_parm = DECL_CHAIN (decl_parm);
17943           pattern_parm = DECL_CHAIN (pattern_parm);
17944         }
17945       /* Merge any parameters that match with the function parameter
17946          pack.  */
17947       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
17948         {
17949           int i, len;
17950           tree expanded_types;
17951           /* Expand the TYPE_PACK_EXPANSION that provides the types for
17952              the parameters in this function parameter pack.  */
17953           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
17954                                                  args, tf_error, NULL_TREE);
17955           len = TREE_VEC_LENGTH (expanded_types);
17956           for (i = 0; i < len; i++)
17957             {
17958               tree parm_type;
17959               tree attributes;
17960           
17961               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
17962                 /* Rename the parameter to include the index.  */
17963                 DECL_NAME (decl_parm) = 
17964                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
17965               parm_type = TREE_VEC_ELT (expanded_types, i);
17966               parm_type = type_decays_to (parm_type);
17967               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
17968                 TREE_TYPE (decl_parm) = parm_type;
17969               attributes = DECL_ATTRIBUTES (pattern_parm);
17970               if (DECL_ATTRIBUTES (decl_parm) != attributes)
17971                 {
17972                   DECL_ATTRIBUTES (decl_parm) = attributes;
17973                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
17974                 }
17975               decl_parm = DECL_CHAIN (decl_parm);
17976             }
17977         }
17978       /* Merge additional specifiers from the CODE_PATTERN.  */
17979       if (DECL_DECLARED_INLINE_P (code_pattern)
17980           && !DECL_DECLARED_INLINE_P (decl))
17981         DECL_DECLARED_INLINE_P (decl) = 1;
17982     }
17983   else if (TREE_CODE (decl) == VAR_DECL)
17984     {
17985       DECL_INITIAL (decl) =
17986         tsubst_expr (DECL_INITIAL (code_pattern), args,
17987                      tf_error, DECL_TI_TEMPLATE (decl),
17988                      /*integral_constant_expression_p=*/false);
17989       if (VAR_HAD_UNKNOWN_BOUND (decl))
17990         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
17991                                    tf_error, DECL_TI_TEMPLATE (decl));
17992     }
17993   else
17994     gcc_unreachable ();
17995
17996   pop_access_scope (decl);
17997 }
17998
17999 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
18000    substituted to get DECL.  */
18001
18002 tree
18003 template_for_substitution (tree decl)
18004 {
18005   tree tmpl = DECL_TI_TEMPLATE (decl);
18006
18007   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
18008      for the instantiation.  This is not always the most general
18009      template.  Consider, for example:
18010
18011         template <class T>
18012         struct S { template <class U> void f();
18013                    template <> void f<int>(); };
18014
18015      and an instantiation of S<double>::f<int>.  We want TD to be the
18016      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
18017   while (/* An instantiation cannot have a definition, so we need a
18018             more general template.  */
18019          DECL_TEMPLATE_INSTANTIATION (tmpl)
18020            /* We must also deal with friend templates.  Given:
18021
18022                 template <class T> struct S {
18023                   template <class U> friend void f() {};
18024                 };
18025
18026               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
18027               so far as the language is concerned, but that's still
18028               where we get the pattern for the instantiation from.  On
18029               other hand, if the definition comes outside the class, say:
18030
18031                 template <class T> struct S {
18032                   template <class U> friend void f();
18033                 };
18034                 template <class U> friend void f() {}
18035
18036               we don't need to look any further.  That's what the check for
18037               DECL_INITIAL is for.  */
18038           || (TREE_CODE (decl) == FUNCTION_DECL
18039               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
18040               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
18041     {
18042       /* The present template, TD, should not be a definition.  If it
18043          were a definition, we should be using it!  Note that we
18044          cannot restructure the loop to just keep going until we find
18045          a template with a definition, since that might go too far if
18046          a specialization was declared, but not defined.  */
18047       gcc_assert (TREE_CODE (decl) != VAR_DECL
18048                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
18049
18050       /* Fetch the more general template.  */
18051       tmpl = DECL_TI_TEMPLATE (tmpl);
18052     }
18053
18054   return tmpl;
18055 }
18056
18057 /* Returns true if we need to instantiate this template instance even if we
18058    know we aren't going to emit it..  */
18059
18060 bool
18061 always_instantiate_p (tree decl)
18062 {
18063   /* We always instantiate inline functions so that we can inline them.  An
18064      explicit instantiation declaration prohibits implicit instantiation of
18065      non-inline functions.  With high levels of optimization, we would
18066      normally inline non-inline functions -- but we're not allowed to do
18067      that for "extern template" functions.  Therefore, we check
18068      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
18069   return ((TREE_CODE (decl) == FUNCTION_DECL
18070            && DECL_DECLARED_INLINE_P (decl))
18071           /* And we need to instantiate static data members so that
18072              their initializers are available in integral constant
18073              expressions.  */
18074           || (TREE_CODE (decl) == VAR_DECL
18075               && decl_maybe_constant_var_p (decl)));
18076 }
18077
18078 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
18079    instantiate it now, modifying TREE_TYPE (fn).  */
18080
18081 void
18082 maybe_instantiate_noexcept (tree fn)
18083 {
18084   tree fntype, spec, noex, clone;
18085
18086   if (DECL_CLONED_FUNCTION_P (fn))
18087     fn = DECL_CLONED_FUNCTION (fn);
18088   fntype = TREE_TYPE (fn);
18089   spec = TYPE_RAISES_EXCEPTIONS (fntype);
18090
18091   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
18092     return;
18093
18094   noex = TREE_PURPOSE (spec);
18095
18096   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
18097     {
18098       if (push_tinst_level (fn))
18099         {
18100           push_access_scope (fn);
18101           push_deferring_access_checks (dk_no_deferred);
18102           input_location = DECL_SOURCE_LOCATION (fn);
18103           noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
18104                                         DEFERRED_NOEXCEPT_ARGS (noex),
18105                                         tf_warning_or_error, fn,
18106                                         /*function_p=*/false,
18107                                         /*integral_constant_expression_p=*/true);
18108           pop_deferring_access_checks ();
18109           pop_access_scope (fn);
18110           pop_tinst_level ();
18111           spec = build_noexcept_spec (noex, tf_warning_or_error);
18112           if (spec == error_mark_node)
18113             spec = noexcept_false_spec;
18114         }
18115       else
18116         spec = noexcept_false_spec;
18117     }
18118   else
18119     {
18120       /* This is an implicitly declared function, so NOEX is a list of
18121          other functions to evaluate and merge.  */
18122       tree elt;
18123       spec = noexcept_true_spec;
18124       for (elt = noex; elt; elt = OVL_NEXT (elt))
18125         {
18126           tree fn = OVL_CURRENT (elt);
18127           tree subspec;
18128           maybe_instantiate_noexcept (fn);
18129           subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
18130           spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
18131         }
18132     }
18133
18134   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
18135
18136   FOR_EACH_CLONE (clone, fn)
18137     {
18138       if (TREE_TYPE (clone) == fntype)
18139         TREE_TYPE (clone) = TREE_TYPE (fn);
18140       else
18141         TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
18142     }
18143 }
18144
18145 /* Produce the definition of D, a _DECL generated from a template.  If
18146    DEFER_OK is nonzero, then we don't have to actually do the
18147    instantiation now; we just have to do it sometime.  Normally it is
18148    an error if this is an explicit instantiation but D is undefined.
18149    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
18150    explicitly instantiated class template.  */
18151
18152 tree
18153 instantiate_decl (tree d, int defer_ok,
18154                   bool expl_inst_class_mem_p)
18155 {
18156   tree tmpl = DECL_TI_TEMPLATE (d);
18157   tree gen_args;
18158   tree args;
18159   tree td;
18160   tree code_pattern;
18161   tree spec;
18162   tree gen_tmpl;
18163   bool pattern_defined;
18164   location_t saved_loc = input_location;
18165   bool external_p;
18166   tree fn_context;
18167   bool nested;
18168
18169   /* This function should only be used to instantiate templates for
18170      functions and static member variables.  */
18171   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18172               || TREE_CODE (d) == VAR_DECL);
18173
18174   /* Variables are never deferred; if instantiation is required, they
18175      are instantiated right away.  That allows for better code in the
18176      case that an expression refers to the value of the variable --
18177      if the variable has a constant value the referring expression can
18178      take advantage of that fact.  */
18179   if (TREE_CODE (d) == VAR_DECL
18180       || DECL_DECLARED_CONSTEXPR_P (d))
18181     defer_ok = 0;
18182
18183   /* Don't instantiate cloned functions.  Instead, instantiate the
18184      functions they cloned.  */
18185   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18186     d = DECL_CLONED_FUNCTION (d);
18187
18188   if (DECL_TEMPLATE_INSTANTIATED (d)
18189       || (TREE_CODE (d) == FUNCTION_DECL
18190           && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
18191       || DECL_TEMPLATE_SPECIALIZATION (d))
18192     /* D has already been instantiated or explicitly specialized, so
18193        there's nothing for us to do here.
18194
18195        It might seem reasonable to check whether or not D is an explicit
18196        instantiation, and, if so, stop here.  But when an explicit
18197        instantiation is deferred until the end of the compilation,
18198        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18199        the instantiation.  */
18200     return d;
18201
18202   /* Check to see whether we know that this template will be
18203      instantiated in some other file, as with "extern template"
18204      extension.  */
18205   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18206
18207   /* In general, we do not instantiate such templates.  */
18208   if (external_p && !always_instantiate_p (d))
18209     return d;
18210
18211   gen_tmpl = most_general_template (tmpl);
18212   gen_args = DECL_TI_ARGS (d);
18213
18214   if (tmpl != gen_tmpl)
18215     /* We should already have the extra args.  */
18216     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18217                 == TMPL_ARGS_DEPTH (gen_args));
18218   /* And what's in the hash table should match D.  */
18219   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18220               || spec == NULL_TREE);
18221
18222   /* This needs to happen before any tsubsting.  */
18223   if (! push_tinst_level (d))
18224     return d;
18225
18226   timevar_push (TV_TEMPLATE_INST);
18227
18228   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18229      for the instantiation.  */
18230   td = template_for_substitution (d);
18231   code_pattern = DECL_TEMPLATE_RESULT (td);
18232
18233   /* We should never be trying to instantiate a member of a class
18234      template or partial specialization.  */
18235   gcc_assert (d != code_pattern);
18236
18237   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18238       || DECL_TEMPLATE_SPECIALIZATION (td))
18239     /* In the case of a friend template whose definition is provided
18240        outside the class, we may have too many arguments.  Drop the
18241        ones we don't need.  The same is true for specializations.  */
18242     args = get_innermost_template_args
18243       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18244   else
18245     args = gen_args;
18246
18247   if (TREE_CODE (d) == FUNCTION_DECL)
18248     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18249                        || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18250   else
18251     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18252
18253   /* We may be in the middle of deferred access check.  Disable it now.  */
18254   push_deferring_access_checks (dk_no_deferred);
18255
18256   /* Unless an explicit instantiation directive has already determined
18257      the linkage of D, remember that a definition is available for
18258      this entity.  */
18259   if (pattern_defined
18260       && !DECL_INTERFACE_KNOWN (d)
18261       && !DECL_NOT_REALLY_EXTERN (d))
18262     mark_definable (d);
18263
18264   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18265   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18266   input_location = DECL_SOURCE_LOCATION (d);
18267
18268   /* If D is a member of an explicitly instantiated class template,
18269      and no definition is available, treat it like an implicit
18270      instantiation.  */
18271   if (!pattern_defined && expl_inst_class_mem_p
18272       && DECL_EXPLICIT_INSTANTIATION (d))
18273     {
18274       /* Leave linkage flags alone on instantiations with anonymous
18275          visibility.  */
18276       if (TREE_PUBLIC (d))
18277         {
18278           DECL_NOT_REALLY_EXTERN (d) = 0;
18279           DECL_INTERFACE_KNOWN (d) = 0;
18280         }
18281       SET_DECL_IMPLICIT_INSTANTIATION (d);
18282     }
18283
18284   if (TREE_CODE (d) == FUNCTION_DECL)
18285     maybe_instantiate_noexcept (d);
18286
18287   /* Recheck the substitutions to obtain any warning messages
18288      about ignoring cv qualifiers.  Don't do this for artificial decls,
18289      as it breaks the context-sensitive substitution for lambda op(). */
18290   if (!defer_ok && !DECL_ARTIFICIAL (d))
18291     {
18292       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
18293       tree type = TREE_TYPE (gen);
18294
18295       /* Make sure that we can see identifiers, and compute access
18296          correctly.  D is already the target FUNCTION_DECL with the
18297          right context.  */
18298       push_access_scope (d);
18299
18300       if (TREE_CODE (gen) == FUNCTION_DECL)
18301         {
18302           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
18303           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
18304                                           d, /*defer_ok*/true);
18305           /* Don't simply tsubst the function type, as that will give
18306              duplicate warnings about poor parameter qualifications.
18307              The function arguments are the same as the decl_arguments
18308              without the top level cv qualifiers.  */
18309           type = TREE_TYPE (type);
18310         }
18311       tsubst (type, gen_args, tf_warning_or_error, d);
18312
18313       pop_access_scope (d);
18314     }
18315
18316   /* Defer all other templates, unless we have been explicitly
18317      forbidden from doing so.  */
18318   if (/* If there is no definition, we cannot instantiate the
18319          template.  */
18320       ! pattern_defined
18321       /* If it's OK to postpone instantiation, do so.  */
18322       || defer_ok
18323       /* If this is a static data member that will be defined
18324          elsewhere, we don't want to instantiate the entire data
18325          member, but we do want to instantiate the initializer so that
18326          we can substitute that elsewhere.  */
18327       || (external_p && TREE_CODE (d) == VAR_DECL))
18328     {
18329       /* The definition of the static data member is now required so
18330          we must substitute the initializer.  */
18331       if (TREE_CODE (d) == VAR_DECL
18332           && !DECL_INITIAL (d)
18333           && DECL_INITIAL (code_pattern))
18334         {
18335           tree ns;
18336           tree init;
18337           bool const_init = false;
18338
18339           ns = decl_namespace_context (d);
18340           push_nested_namespace (ns);
18341           push_nested_class (DECL_CONTEXT (d));
18342           init = tsubst_expr (DECL_INITIAL (code_pattern),
18343                               args,
18344                               tf_warning_or_error, NULL_TREE,
18345                               /*integral_constant_expression_p=*/false);
18346           /* Make sure the initializer is still constant, in case of
18347              circular dependency (template/instantiate6.C). */
18348           const_init
18349             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18350           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18351                           /*asmspec_tree=*/NULL_TREE,
18352                           LOOKUP_ONLYCONVERTING);
18353           pop_nested_class ();
18354           pop_nested_namespace (ns);
18355         }
18356
18357       /* We restore the source position here because it's used by
18358          add_pending_template.  */
18359       input_location = saved_loc;
18360
18361       if (at_eof && !pattern_defined
18362           && DECL_EXPLICIT_INSTANTIATION (d)
18363           && DECL_NOT_REALLY_EXTERN (d))
18364         /* [temp.explicit]
18365
18366            The definition of a non-exported function template, a
18367            non-exported member function template, or a non-exported
18368            member function or static data member of a class template
18369            shall be present in every translation unit in which it is
18370            explicitly instantiated.  */
18371         permerror (input_location,  "explicit instantiation of %qD "
18372                    "but no definition available", d);
18373
18374       /* If we're in unevaluated context, we just wanted to get the
18375          constant value; this isn't an odr use, so don't queue
18376          a full instantiation.  */
18377       if (cp_unevaluated_operand != 0)
18378         goto out;
18379       /* ??? Historically, we have instantiated inline functions, even
18380          when marked as "extern template".  */
18381       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18382         add_pending_template (d);
18383       goto out;
18384     }
18385   /* Tell the repository that D is available in this translation unit
18386      -- and see if it is supposed to be instantiated here.  */
18387   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18388     {
18389       /* In a PCH file, despite the fact that the repository hasn't
18390          requested instantiation in the PCH it is still possible that
18391          an instantiation will be required in a file that includes the
18392          PCH.  */
18393       if (pch_file)
18394         add_pending_template (d);
18395       /* Instantiate inline functions so that the inliner can do its
18396          job, even though we'll not be emitting a copy of this
18397          function.  */
18398       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18399         goto out;
18400     }
18401
18402   fn_context = decl_function_context (d);
18403   nested = (current_function_decl != NULL_TREE);
18404   if (!fn_context)
18405     push_to_top_level ();
18406   else if (nested)
18407     push_function_context ();
18408
18409   /* Mark D as instantiated so that recursive calls to
18410      instantiate_decl do not try to instantiate it again.  */
18411   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18412
18413   /* Regenerate the declaration in case the template has been modified
18414      by a subsequent redeclaration.  */
18415   regenerate_decl_from_template (d, td);
18416
18417   /* We already set the file and line above.  Reset them now in case
18418      they changed as a result of calling regenerate_decl_from_template.  */
18419   input_location = DECL_SOURCE_LOCATION (d);
18420
18421   if (TREE_CODE (d) == VAR_DECL)
18422     {
18423       tree init;
18424       bool const_init = false;
18425
18426       /* Clear out DECL_RTL; whatever was there before may not be right
18427          since we've reset the type of the declaration.  */
18428       SET_DECL_RTL (d, NULL);
18429       DECL_IN_AGGR_P (d) = 0;
18430
18431       /* The initializer is placed in DECL_INITIAL by
18432          regenerate_decl_from_template so we don't need to
18433          push/pop_access_scope again here.  Pull it out so that
18434          cp_finish_decl can process it.  */
18435       init = DECL_INITIAL (d);
18436       DECL_INITIAL (d) = NULL_TREE;
18437       DECL_INITIALIZED_P (d) = 0;
18438
18439       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18440          initializer.  That function will defer actual emission until
18441          we have a chance to determine linkage.  */
18442       DECL_EXTERNAL (d) = 0;
18443
18444       /* Enter the scope of D so that access-checking works correctly.  */
18445       push_nested_class (DECL_CONTEXT (d));
18446       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18447       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18448       pop_nested_class ();
18449     }
18450   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18451     synthesize_method (d);
18452   else if (TREE_CODE (d) == FUNCTION_DECL)
18453     {
18454       htab_t saved_local_specializations;
18455       tree subst_decl;
18456       tree tmpl_parm;
18457       tree spec_parm;
18458
18459       /* Save away the current list, in case we are instantiating one
18460          template from within the body of another.  */
18461       saved_local_specializations = local_specializations;
18462
18463       /* Set up the list of local specializations.  */
18464       local_specializations = htab_create (37,
18465                                            hash_local_specialization,
18466                                            eq_local_specializations,
18467                                            NULL);
18468
18469       /* Set up context.  */
18470       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18471
18472       /* Create substitution entries for the parameters.  */
18473       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18474       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18475       spec_parm = DECL_ARGUMENTS (d);
18476       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18477         {
18478           register_local_specialization (spec_parm, tmpl_parm);
18479           spec_parm = skip_artificial_parms_for (d, spec_parm);
18480           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18481         }
18482       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18483         {
18484           if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18485             {
18486               register_local_specialization (spec_parm, tmpl_parm);
18487               spec_parm = DECL_CHAIN (spec_parm);
18488             }
18489           else
18490             {
18491               /* Register the (value) argument pack as a specialization of
18492                  TMPL_PARM, then move on.  */
18493               tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18494               register_local_specialization (argpack, tmpl_parm);
18495             }
18496         }
18497       gcc_assert (!spec_parm);
18498
18499       /* Substitute into the body of the function.  */
18500       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18501                    tf_warning_or_error, tmpl,
18502                    /*integral_constant_expression_p=*/false);
18503
18504       /* Set the current input_location to the end of the function
18505          so that finish_function knows where we are.  */
18506       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18507
18508       /* We don't need the local specializations any more.  */
18509       htab_delete (local_specializations);
18510       local_specializations = saved_local_specializations;
18511
18512       /* Finish the function.  */
18513       d = finish_function (0);
18514       expand_or_defer_fn (d);
18515     }
18516
18517   /* We're not deferring instantiation any more.  */
18518   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18519
18520   if (!fn_context)
18521     pop_from_top_level ();
18522   else if (nested)
18523     pop_function_context ();
18524
18525 out:
18526   input_location = saved_loc;
18527   pop_deferring_access_checks ();
18528   pop_tinst_level ();
18529
18530   timevar_pop (TV_TEMPLATE_INST);
18531
18532   return d;
18533 }
18534
18535 /* Run through the list of templates that we wish we could
18536    instantiate, and instantiate any we can.  RETRIES is the
18537    number of times we retry pending template instantiation.  */
18538
18539 void
18540 instantiate_pending_templates (int retries)
18541 {
18542   int reconsider;
18543   location_t saved_loc = input_location;
18544
18545   /* Instantiating templates may trigger vtable generation.  This in turn
18546      may require further template instantiations.  We place a limit here
18547      to avoid infinite loop.  */
18548   if (pending_templates && retries >= max_tinst_depth)
18549     {
18550       tree decl = pending_templates->tinst->decl;
18551
18552       error ("template instantiation depth exceeds maximum of %d"
18553              " instantiating %q+D, possibly from virtual table generation"
18554              " (use -ftemplate-depth= to increase the maximum)",
18555              max_tinst_depth, decl);
18556       if (TREE_CODE (decl) == FUNCTION_DECL)
18557         /* Pretend that we defined it.  */
18558         DECL_INITIAL (decl) = error_mark_node;
18559       return;
18560     }
18561
18562   do
18563     {
18564       struct pending_template **t = &pending_templates;
18565       struct pending_template *last = NULL;
18566       reconsider = 0;
18567       while (*t)
18568         {
18569           tree instantiation = reopen_tinst_level ((*t)->tinst);
18570           bool complete = false;
18571
18572           if (TYPE_P (instantiation))
18573             {
18574               tree fn;
18575
18576               if (!COMPLETE_TYPE_P (instantiation))
18577                 {
18578                   instantiate_class_template (instantiation);
18579                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18580                     for (fn = TYPE_METHODS (instantiation);
18581                          fn;
18582                          fn = TREE_CHAIN (fn))
18583                       if (! DECL_ARTIFICIAL (fn))
18584                         instantiate_decl (fn,
18585                                           /*defer_ok=*/0,
18586                                           /*expl_inst_class_mem_p=*/false);
18587                   if (COMPLETE_TYPE_P (instantiation))
18588                     reconsider = 1;
18589                 }
18590
18591               complete = COMPLETE_TYPE_P (instantiation);
18592             }
18593           else
18594             {
18595               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
18596                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
18597                 {
18598                   instantiation
18599                     = instantiate_decl (instantiation,
18600                                         /*defer_ok=*/0,
18601                                         /*expl_inst_class_mem_p=*/false);
18602                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
18603                     reconsider = 1;
18604                 }
18605
18606               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
18607                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
18608             }
18609
18610           if (complete)
18611             /* If INSTANTIATION has been instantiated, then we don't
18612                need to consider it again in the future.  */
18613             *t = (*t)->next;
18614           else
18615             {
18616               last = *t;
18617               t = &(*t)->next;
18618             }
18619           tinst_depth = 0;
18620           current_tinst_level = NULL;
18621         }
18622       last_pending_template = last;
18623     }
18624   while (reconsider);
18625
18626   input_location = saved_loc;
18627 }
18628
18629 /* Substitute ARGVEC into T, which is a list of initializers for
18630    either base class or a non-static data member.  The TREE_PURPOSEs
18631    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
18632    instantiate_decl.  */
18633
18634 static tree
18635 tsubst_initializer_list (tree t, tree argvec)
18636 {
18637   tree inits = NULL_TREE;
18638
18639   for (; t; t = TREE_CHAIN (t))
18640     {
18641       tree decl;
18642       tree init;
18643       tree expanded_bases = NULL_TREE;
18644       tree expanded_arguments = NULL_TREE;
18645       int i, len = 1;
18646
18647       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
18648         {
18649           tree expr;
18650           tree arg;
18651
18652           /* Expand the base class expansion type into separate base
18653              classes.  */
18654           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
18655                                                  tf_warning_or_error,
18656                                                  NULL_TREE);
18657           if (expanded_bases == error_mark_node)
18658             continue;
18659           
18660           /* We'll be building separate TREE_LISTs of arguments for
18661              each base.  */
18662           len = TREE_VEC_LENGTH (expanded_bases);
18663           expanded_arguments = make_tree_vec (len);
18664           for (i = 0; i < len; i++)
18665             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
18666
18667           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
18668              expand each argument in the TREE_VALUE of t.  */
18669           expr = make_node (EXPR_PACK_EXPANSION);
18670           PACK_EXPANSION_LOCAL_P (expr) = true;
18671           PACK_EXPANSION_PARAMETER_PACKS (expr) =
18672             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
18673
18674           if (TREE_VALUE (t) == void_type_node)
18675             /* VOID_TYPE_NODE is used to indicate
18676                value-initialization.  */
18677             {
18678               for (i = 0; i < len; i++)
18679                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
18680             }
18681           else
18682             {
18683               /* Substitute parameter packs into each argument in the
18684                  TREE_LIST.  */
18685               in_base_initializer = 1;
18686               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
18687                 {
18688                   tree expanded_exprs;
18689
18690                   /* Expand the argument.  */
18691                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
18692                   expanded_exprs 
18693                     = tsubst_pack_expansion (expr, argvec,
18694                                              tf_warning_or_error,
18695                                              NULL_TREE);
18696                   if (expanded_exprs == error_mark_node)
18697                     continue;
18698
18699                   /* Prepend each of the expanded expressions to the
18700                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
18701                   for (i = 0; i < len; i++)
18702                     {
18703                       TREE_VEC_ELT (expanded_arguments, i) = 
18704                         tree_cons (NULL_TREE, 
18705                                    TREE_VEC_ELT (expanded_exprs, i),
18706                                    TREE_VEC_ELT (expanded_arguments, i));
18707                     }
18708                 }
18709               in_base_initializer = 0;
18710
18711               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
18712                  since we built them backwards.  */
18713               for (i = 0; i < len; i++)
18714                 {
18715                   TREE_VEC_ELT (expanded_arguments, i) = 
18716                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
18717                 }
18718             }
18719         }
18720
18721       for (i = 0; i < len; ++i)
18722         {
18723           if (expanded_bases)
18724             {
18725               decl = TREE_VEC_ELT (expanded_bases, i);
18726               decl = expand_member_init (decl);
18727               init = TREE_VEC_ELT (expanded_arguments, i);
18728             }
18729           else
18730             {
18731               tree tmp;
18732               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
18733                                   tf_warning_or_error, NULL_TREE);
18734
18735               decl = expand_member_init (decl);
18736               if (decl && !DECL_P (decl))
18737                 in_base_initializer = 1;
18738
18739               init = TREE_VALUE (t);
18740               tmp = init;
18741               if (init != void_type_node)
18742                 init = tsubst_expr (init, argvec,
18743                                     tf_warning_or_error, NULL_TREE,
18744                                     /*integral_constant_expression_p=*/false);
18745               if (init == NULL_TREE && tmp != NULL_TREE)
18746                 /* If we had an initializer but it instantiated to nothing,
18747                    value-initialize the object.  This will only occur when
18748                    the initializer was a pack expansion where the parameter
18749                    packs used in that expansion were of length zero.  */
18750                 init = void_type_node;
18751               in_base_initializer = 0;
18752             }
18753
18754           if (decl)
18755             {
18756               init = build_tree_list (decl, init);
18757               TREE_CHAIN (init) = inits;
18758               inits = init;
18759             }
18760         }
18761     }
18762   return inits;
18763 }
18764
18765 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
18766
18767 static void
18768 set_current_access_from_decl (tree decl)
18769 {
18770   if (TREE_PRIVATE (decl))
18771     current_access_specifier = access_private_node;
18772   else if (TREE_PROTECTED (decl))
18773     current_access_specifier = access_protected_node;
18774   else
18775     current_access_specifier = access_public_node;
18776 }
18777
18778 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
18779    is the instantiation (which should have been created with
18780    start_enum) and ARGS are the template arguments to use.  */
18781
18782 static void
18783 tsubst_enum (tree tag, tree newtag, tree args)
18784 {
18785   tree e;
18786
18787   if (SCOPED_ENUM_P (newtag))
18788     begin_scope (sk_scoped_enum, newtag);
18789
18790   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
18791     {
18792       tree value;
18793       tree decl;
18794
18795       decl = TREE_VALUE (e);
18796       /* Note that in a template enum, the TREE_VALUE is the
18797          CONST_DECL, not the corresponding INTEGER_CST.  */
18798       value = tsubst_expr (DECL_INITIAL (decl),
18799                            args, tf_warning_or_error, NULL_TREE,
18800                            /*integral_constant_expression_p=*/true);
18801
18802       /* Give this enumeration constant the correct access.  */
18803       set_current_access_from_decl (decl);
18804
18805       /* Actually build the enumerator itself.  */
18806       build_enumerator
18807         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
18808     }
18809
18810   if (SCOPED_ENUM_P (newtag))
18811     finish_scope ();
18812
18813   finish_enum_value_list (newtag);
18814   finish_enum (newtag);
18815
18816   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
18817     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
18818 }
18819
18820 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
18821    its type -- but without substituting the innermost set of template
18822    arguments.  So, innermost set of template parameters will appear in
18823    the type.  */
18824
18825 tree
18826 get_mostly_instantiated_function_type (tree decl)
18827 {
18828   tree fn_type;
18829   tree tmpl;
18830   tree targs;
18831   tree tparms;
18832   int parm_depth;
18833
18834   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
18835   targs = DECL_TI_ARGS (decl);
18836   tparms = DECL_TEMPLATE_PARMS (tmpl);
18837   parm_depth = TMPL_PARMS_DEPTH (tparms);
18838
18839   /* There should be as many levels of arguments as there are levels
18840      of parameters.  */
18841   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
18842
18843   fn_type = TREE_TYPE (tmpl);
18844
18845   if (parm_depth == 1)
18846     /* No substitution is necessary.  */
18847     ;
18848   else
18849     {
18850       int i;
18851       tree partial_args;
18852
18853       /* Replace the innermost level of the TARGS with NULL_TREEs to
18854          let tsubst know not to substitute for those parameters.  */
18855       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
18856       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
18857         SET_TMPL_ARGS_LEVEL (partial_args, i,
18858                              TMPL_ARGS_LEVEL (targs, i));
18859       SET_TMPL_ARGS_LEVEL (partial_args,
18860                            TMPL_ARGS_DEPTH (targs),
18861                            make_tree_vec (DECL_NTPARMS (tmpl)));
18862
18863       /* Make sure that we can see identifiers, and compute access
18864          correctly.  */
18865       push_access_scope (decl);
18866
18867       ++processing_template_decl;
18868       /* Now, do the (partial) substitution to figure out the
18869          appropriate function type.  */
18870       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
18871       --processing_template_decl;
18872
18873       /* Substitute into the template parameters to obtain the real
18874          innermost set of parameters.  This step is important if the
18875          innermost set of template parameters contains value
18876          parameters whose types depend on outer template parameters.  */
18877       TREE_VEC_LENGTH (partial_args)--;
18878       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
18879
18880       pop_access_scope (decl);
18881     }
18882
18883   return fn_type;
18884 }
18885
18886 /* Return truthvalue if we're processing a template different from
18887    the last one involved in diagnostics.  */
18888 int
18889 problematic_instantiation_changed (void)
18890 {
18891   return current_tinst_level != last_error_tinst_level;
18892 }
18893
18894 /* Remember current template involved in diagnostics.  */
18895 void
18896 record_last_problematic_instantiation (void)
18897 {
18898   last_error_tinst_level = current_tinst_level;
18899 }
18900
18901 struct tinst_level *
18902 current_instantiation (void)
18903 {
18904   return current_tinst_level;
18905 }
18906
18907 /* [temp.param] Check that template non-type parm TYPE is of an allowable
18908    type. Return zero for ok, nonzero for disallowed. Issue error and
18909    warning messages under control of COMPLAIN.  */
18910
18911 static int
18912 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
18913 {
18914   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
18915     return 0;
18916   else if (POINTER_TYPE_P (type))
18917     return 0;
18918   else if (TYPE_PTR_TO_MEMBER_P (type))
18919     return 0;
18920   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
18921     return 0;
18922   else if (TREE_CODE (type) == TYPENAME_TYPE)
18923     return 0;
18924   else if (TREE_CODE (type) == DECLTYPE_TYPE)
18925     return 0;
18926   else if (TREE_CODE (type) == NULLPTR_TYPE)
18927     return 0;
18928
18929   if (complain & tf_error)
18930     {
18931       if (type == error_mark_node)
18932         inform (input_location, "invalid template non-type parameter");
18933       else
18934         error ("%q#T is not a valid type for a template non-type parameter",
18935                type);
18936     }
18937   return 1;
18938 }
18939
18940 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
18941    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
18942
18943 static bool
18944 dependent_type_p_r (tree type)
18945 {
18946   tree scope;
18947
18948   /* [temp.dep.type]
18949
18950      A type is dependent if it is:
18951
18952      -- a template parameter. Template template parameters are types
18953         for us (since TYPE_P holds true for them) so we handle
18954         them here.  */
18955   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18956       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
18957     return true;
18958   /* -- a qualified-id with a nested-name-specifier which contains a
18959         class-name that names a dependent type or whose unqualified-id
18960         names a dependent type.  */
18961   if (TREE_CODE (type) == TYPENAME_TYPE)
18962     return true;
18963   /* -- a cv-qualified type where the cv-unqualified type is
18964         dependent.  */
18965   type = TYPE_MAIN_VARIANT (type);
18966   /* -- a compound type constructed from any dependent type.  */
18967   if (TYPE_PTR_TO_MEMBER_P (type))
18968     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
18969             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
18970                                            (type)));
18971   else if (TREE_CODE (type) == POINTER_TYPE
18972            || TREE_CODE (type) == REFERENCE_TYPE)
18973     return dependent_type_p (TREE_TYPE (type));
18974   else if (TREE_CODE (type) == FUNCTION_TYPE
18975            || TREE_CODE (type) == METHOD_TYPE)
18976     {
18977       tree arg_type;
18978
18979       if (dependent_type_p (TREE_TYPE (type)))
18980         return true;
18981       for (arg_type = TYPE_ARG_TYPES (type);
18982            arg_type;
18983            arg_type = TREE_CHAIN (arg_type))
18984         if (dependent_type_p (TREE_VALUE (arg_type)))
18985           return true;
18986       return false;
18987     }
18988   /* -- an array type constructed from any dependent type or whose
18989         size is specified by a constant expression that is
18990         value-dependent.
18991
18992         We checked for type- and value-dependence of the bounds in
18993         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
18994   if (TREE_CODE (type) == ARRAY_TYPE)
18995     {
18996       if (TYPE_DOMAIN (type)
18997           && dependent_type_p (TYPE_DOMAIN (type)))
18998         return true;
18999       return dependent_type_p (TREE_TYPE (type));
19000     }
19001
19002   /* -- a template-id in which either the template name is a template
19003      parameter ...  */
19004   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19005     return true;
19006   /* ... or any of the template arguments is a dependent type or
19007         an expression that is type-dependent or value-dependent.  */
19008   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
19009            && (any_dependent_template_arguments_p
19010                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
19011     return true;
19012
19013   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
19014      dependent; if the argument of the `typeof' expression is not
19015      type-dependent, then it should already been have resolved.  */
19016   if (TREE_CODE (type) == TYPEOF_TYPE
19017       || TREE_CODE (type) == DECLTYPE_TYPE
19018       || TREE_CODE (type) == UNDERLYING_TYPE)
19019     return true;
19020
19021   /* A template argument pack is dependent if any of its packed
19022      arguments are.  */
19023   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
19024     {
19025       tree args = ARGUMENT_PACK_ARGS (type);
19026       int i, len = TREE_VEC_LENGTH (args);
19027       for (i = 0; i < len; ++i)
19028         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19029           return true;
19030     }
19031
19032   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
19033      be template parameters.  */
19034   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
19035     return true;
19036
19037   /* The standard does not specifically mention types that are local
19038      to template functions or local classes, but they should be
19039      considered dependent too.  For example:
19040
19041        template <int I> void f() {
19042          enum E { a = I };
19043          S<sizeof (E)> s;
19044        }
19045
19046      The size of `E' cannot be known until the value of `I' has been
19047      determined.  Therefore, `E' must be considered dependent.  */
19048   scope = TYPE_CONTEXT (type);
19049   if (scope && TYPE_P (scope))
19050     return dependent_type_p (scope);
19051   /* Don't use type_dependent_expression_p here, as it can lead
19052      to infinite recursion trying to determine whether a lambda
19053      nested in a lambda is dependent (c++/47687).  */
19054   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
19055            && DECL_LANG_SPECIFIC (scope)
19056            && DECL_TEMPLATE_INFO (scope)
19057            && (any_dependent_template_arguments_p
19058                (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
19059     return true;
19060
19061   /* Other types are non-dependent.  */
19062   return false;
19063 }
19064
19065 /* Returns TRUE if TYPE is dependent, in the sense of
19066    [temp.dep.type].  Note that a NULL type is considered dependent.  */
19067
19068 bool
19069 dependent_type_p (tree type)
19070 {
19071   /* If there are no template parameters in scope, then there can't be
19072      any dependent types.  */
19073   if (!processing_template_decl)
19074     {
19075       /* If we are not processing a template, then nobody should be
19076          providing us with a dependent type.  */
19077       gcc_assert (type);
19078       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
19079       return false;
19080     }
19081
19082   /* If the type is NULL, we have not computed a type for the entity
19083      in question; in that case, the type is dependent.  */
19084   if (!type)
19085     return true;
19086
19087   /* Erroneous types can be considered non-dependent.  */
19088   if (type == error_mark_node)
19089     return false;
19090
19091   /* If we have not already computed the appropriate value for TYPE,
19092      do so now.  */
19093   if (!TYPE_DEPENDENT_P_VALID (type))
19094     {
19095       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
19096       TYPE_DEPENDENT_P_VALID (type) = 1;
19097     }
19098
19099   return TYPE_DEPENDENT_P (type);
19100 }
19101
19102 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
19103    lookup.  In other words, a dependent type that is not the current
19104    instantiation.  */
19105
19106 bool
19107 dependent_scope_p (tree scope)
19108 {
19109   return (scope && TYPE_P (scope) && dependent_type_p (scope)
19110           && !currently_open_class (scope));
19111 }
19112
19113 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
19114    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
19115    expression.  */
19116
19117 /* Note that this predicate is not appropriate for general expressions;
19118    only constant expressions (that satisfy potential_constant_expression)
19119    can be tested for value dependence.
19120
19121    We should really also have a predicate for "instantiation-dependent".
19122
19123    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
19124      (what about instantiation-dependent constant-expressions?)
19125    is_late_template_attribute: defer if instantiation-dependent.
19126    compute_array_index_type: proceed if constant and not t- or v-dependent
19127      if instantiation-dependent, need to remember full expression
19128    uses_template_parms: FIXME - need to audit callers
19129    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
19130    dependent_type_p [array_type]: dependent if index type is dependent
19131      (or non-constant?)
19132    static_assert - instantiation-dependent */
19133
19134 bool
19135 value_dependent_expression_p (tree expression)
19136 {
19137   if (!processing_template_decl)
19138     return false;
19139
19140   /* A name declared with a dependent type.  */
19141   if (DECL_P (expression) && type_dependent_expression_p (expression))
19142     return true;
19143
19144   switch (TREE_CODE (expression))
19145     {
19146     case IDENTIFIER_NODE:
19147       /* A name that has not been looked up -- must be dependent.  */
19148       return true;
19149
19150     case TEMPLATE_PARM_INDEX:
19151       /* A non-type template parm.  */
19152       return true;
19153
19154     case CONST_DECL:
19155       /* A non-type template parm.  */
19156       if (DECL_TEMPLATE_PARM_P (expression))
19157         return true;
19158       return value_dependent_expression_p (DECL_INITIAL (expression));
19159
19160     case VAR_DECL:
19161        /* A constant with literal type and is initialized
19162           with an expression that is value-dependent.
19163
19164           Note that a non-dependent parenthesized initializer will have
19165           already been replaced with its constant value, so if we see
19166           a TREE_LIST it must be dependent.  */
19167       if (DECL_INITIAL (expression)
19168           && decl_constant_var_p (expression)
19169           && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
19170               || value_dependent_expression_p (DECL_INITIAL (expression))))
19171         return true;
19172       return false;
19173
19174     case DYNAMIC_CAST_EXPR:
19175     case STATIC_CAST_EXPR:
19176     case CONST_CAST_EXPR:
19177     case REINTERPRET_CAST_EXPR:
19178     case CAST_EXPR:
19179       /* These expressions are value-dependent if the type to which
19180          the cast occurs is dependent or the expression being casted
19181          is value-dependent.  */
19182       {
19183         tree type = TREE_TYPE (expression);
19184
19185         if (dependent_type_p (type))
19186           return true;
19187
19188         /* A functional cast has a list of operands.  */
19189         expression = TREE_OPERAND (expression, 0);
19190         if (!expression)
19191           {
19192             /* If there are no operands, it must be an expression such
19193                as "int()". This should not happen for aggregate types
19194                because it would form non-constant expressions.  */
19195             gcc_assert (cxx_dialect >= cxx0x
19196                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19197
19198             return false;
19199           }
19200
19201         if (TREE_CODE (expression) == TREE_LIST)
19202           return any_value_dependent_elements_p (expression);
19203
19204         return value_dependent_expression_p (expression);
19205       }
19206
19207     case SIZEOF_EXPR:
19208     case ALIGNOF_EXPR:
19209     case TYPEID_EXPR:
19210       /* A `sizeof' expression is value-dependent if the operand is
19211          type-dependent or is a pack expansion.  */
19212       expression = TREE_OPERAND (expression, 0);
19213       if (PACK_EXPANSION_P (expression))
19214         return true;
19215       else if (TYPE_P (expression))
19216         return dependent_type_p (expression);
19217       return type_dependent_expression_p (expression);
19218
19219     case AT_ENCODE_EXPR:
19220       /* An 'encode' expression is value-dependent if the operand is
19221          type-dependent.  */
19222       expression = TREE_OPERAND (expression, 0);
19223       return dependent_type_p (expression);
19224
19225     case NOEXCEPT_EXPR:
19226       expression = TREE_OPERAND (expression, 0);
19227       return type_dependent_expression_p (expression);
19228
19229     case SCOPE_REF:
19230       {
19231         tree name = TREE_OPERAND (expression, 1);
19232         return value_dependent_expression_p (name);
19233       }
19234
19235     case COMPONENT_REF:
19236       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19237               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19238
19239     case NONTYPE_ARGUMENT_PACK:
19240       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19241          is value-dependent.  */
19242       {
19243         tree values = ARGUMENT_PACK_ARGS (expression);
19244         int i, len = TREE_VEC_LENGTH (values);
19245         
19246         for (i = 0; i < len; ++i)
19247           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19248             return true;
19249         
19250         return false;
19251       }
19252
19253     case TRAIT_EXPR:
19254       {
19255         tree type2 = TRAIT_EXPR_TYPE2 (expression);
19256         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19257                 || (type2 ? dependent_type_p (type2) : false));
19258       }
19259
19260     case MODOP_EXPR:
19261       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19262               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19263
19264     case ARRAY_REF:
19265       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19266               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19267
19268     case ADDR_EXPR:
19269       {
19270         tree op = TREE_OPERAND (expression, 0);
19271         return (value_dependent_expression_p (op)
19272                 || has_value_dependent_address (op));
19273       }
19274
19275     case CALL_EXPR:
19276       {
19277         tree fn = get_callee_fndecl (expression);
19278         int i, nargs;
19279         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19280           return true;
19281         nargs = call_expr_nargs (expression);
19282         for (i = 0; i < nargs; ++i)
19283           {
19284             tree op = CALL_EXPR_ARG (expression, i);
19285             /* In a call to a constexpr member function, look through the
19286                implicit ADDR_EXPR on the object argument so that it doesn't
19287                cause the call to be considered value-dependent.  We also
19288                look through it in potential_constant_expression.  */
19289             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19290                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19291                 && TREE_CODE (op) == ADDR_EXPR)
19292               op = TREE_OPERAND (op, 0);
19293             if (value_dependent_expression_p (op))
19294               return true;
19295           }
19296         return false;
19297       }
19298
19299     case TEMPLATE_ID_EXPR:
19300       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19301          type-dependent.  */
19302       return type_dependent_expression_p (expression);
19303
19304     case CONSTRUCTOR:
19305       {
19306         unsigned ix;
19307         tree val;
19308         FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19309           if (value_dependent_expression_p (val))
19310             return true;
19311         return false;
19312       }
19313
19314     case STMT_EXPR:
19315       /* Treat a GNU statement expression as dependent to avoid crashing
19316          under fold_non_dependent_expr; it can't be constant.  */
19317       return true;
19318
19319     default:
19320       /* A constant expression is value-dependent if any subexpression is
19321          value-dependent.  */
19322       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19323         {
19324         case tcc_reference:
19325         case tcc_unary:
19326         case tcc_comparison:
19327         case tcc_binary:
19328         case tcc_expression:
19329         case tcc_vl_exp:
19330           {
19331             int i, len = cp_tree_operand_length (expression);
19332
19333             for (i = 0; i < len; i++)
19334               {
19335                 tree t = TREE_OPERAND (expression, i);
19336
19337                 /* In some cases, some of the operands may be missing.l
19338                    (For example, in the case of PREDECREMENT_EXPR, the
19339                    amount to increment by may be missing.)  That doesn't
19340                    make the expression dependent.  */
19341                 if (t && value_dependent_expression_p (t))
19342                   return true;
19343               }
19344           }
19345           break;
19346         default:
19347           break;
19348         }
19349       break;
19350     }
19351
19352   /* The expression is not value-dependent.  */
19353   return false;
19354 }
19355
19356 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19357    [temp.dep.expr].  Note that an expression with no type is
19358    considered dependent.  Other parts of the compiler arrange for an
19359    expression with type-dependent subexpressions to have no type, so
19360    this function doesn't have to be fully recursive.  */
19361
19362 bool
19363 type_dependent_expression_p (tree expression)
19364 {
19365   if (!processing_template_decl)
19366     return false;
19367
19368   if (expression == error_mark_node)
19369     return false;
19370
19371   /* An unresolved name is always dependent.  */
19372   if (TREE_CODE (expression) == IDENTIFIER_NODE
19373       || TREE_CODE (expression) == USING_DECL)
19374     return true;
19375
19376   /* Some expression forms are never type-dependent.  */
19377   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19378       || TREE_CODE (expression) == SIZEOF_EXPR
19379       || TREE_CODE (expression) == ALIGNOF_EXPR
19380       || TREE_CODE (expression) == AT_ENCODE_EXPR
19381       || TREE_CODE (expression) == NOEXCEPT_EXPR
19382       || TREE_CODE (expression) == TRAIT_EXPR
19383       || TREE_CODE (expression) == TYPEID_EXPR
19384       || TREE_CODE (expression) == DELETE_EXPR
19385       || TREE_CODE (expression) == VEC_DELETE_EXPR
19386       || TREE_CODE (expression) == THROW_EXPR)
19387     return false;
19388
19389   /* The types of these expressions depends only on the type to which
19390      the cast occurs.  */
19391   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19392       || TREE_CODE (expression) == STATIC_CAST_EXPR
19393       || TREE_CODE (expression) == CONST_CAST_EXPR
19394       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19395       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19396       || TREE_CODE (expression) == CAST_EXPR)
19397     return dependent_type_p (TREE_TYPE (expression));
19398
19399   /* The types of these expressions depends only on the type created
19400      by the expression.  */
19401   if (TREE_CODE (expression) == NEW_EXPR
19402       || TREE_CODE (expression) == VEC_NEW_EXPR)
19403     {
19404       /* For NEW_EXPR tree nodes created inside a template, either
19405          the object type itself or a TREE_LIST may appear as the
19406          operand 1.  */
19407       tree type = TREE_OPERAND (expression, 1);
19408       if (TREE_CODE (type) == TREE_LIST)
19409         /* This is an array type.  We need to check array dimensions
19410            as well.  */
19411         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19412                || value_dependent_expression_p
19413                     (TREE_OPERAND (TREE_VALUE (type), 1));
19414       else
19415         return dependent_type_p (type);
19416     }
19417
19418   if (TREE_CODE (expression) == SCOPE_REF)
19419     {
19420       tree scope = TREE_OPERAND (expression, 0);
19421       tree name = TREE_OPERAND (expression, 1);
19422
19423       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19424          contains an identifier associated by name lookup with one or more
19425          declarations declared with a dependent type, or...a
19426          nested-name-specifier or qualified-id that names a member of an
19427          unknown specialization.  */
19428       return (type_dependent_expression_p (name)
19429               || dependent_scope_p (scope));
19430     }
19431
19432   if (TREE_CODE (expression) == FUNCTION_DECL
19433       && DECL_LANG_SPECIFIC (expression)
19434       && DECL_TEMPLATE_INFO (expression)
19435       && (any_dependent_template_arguments_p
19436           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19437     return true;
19438
19439   if (TREE_CODE (expression) == TEMPLATE_DECL
19440       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19441     return false;
19442
19443   if (TREE_CODE (expression) == STMT_EXPR)
19444     expression = stmt_expr_value_expr (expression);
19445
19446   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19447     {
19448       tree elt;
19449       unsigned i;
19450
19451       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19452         {
19453           if (type_dependent_expression_p (elt))
19454             return true;
19455         }
19456       return false;
19457     }
19458
19459   /* A static data member of the current instantiation with incomplete
19460      array type is type-dependent, as the definition and specializations
19461      can have different bounds.  */
19462   if (TREE_CODE (expression) == VAR_DECL
19463       && DECL_CLASS_SCOPE_P (expression)
19464       && dependent_type_p (DECL_CONTEXT (expression))
19465       && VAR_HAD_UNKNOWN_BOUND (expression))
19466     return true;
19467
19468   if (TREE_TYPE (expression) == unknown_type_node)
19469     {
19470       if (TREE_CODE (expression) == ADDR_EXPR)
19471         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19472       if (TREE_CODE (expression) == COMPONENT_REF
19473           || TREE_CODE (expression) == OFFSET_REF)
19474         {
19475           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19476             return true;
19477           expression = TREE_OPERAND (expression, 1);
19478           if (TREE_CODE (expression) == IDENTIFIER_NODE)
19479             return false;
19480         }
19481       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19482       if (TREE_CODE (expression) == SCOPE_REF)
19483         return false;
19484
19485       if (BASELINK_P (expression))
19486         expression = BASELINK_FUNCTIONS (expression);
19487
19488       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19489         {
19490           if (any_dependent_template_arguments_p
19491               (TREE_OPERAND (expression, 1)))
19492             return true;
19493           expression = TREE_OPERAND (expression, 0);
19494         }
19495       gcc_assert (TREE_CODE (expression) == OVERLOAD
19496                   || TREE_CODE (expression) == FUNCTION_DECL);
19497
19498       while (expression)
19499         {
19500           if (type_dependent_expression_p (OVL_CURRENT (expression)))
19501             return true;
19502           expression = OVL_NEXT (expression);
19503         }
19504       return false;
19505     }
19506
19507   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19508
19509   return (dependent_type_p (TREE_TYPE (expression)));
19510 }
19511
19512 /* Like type_dependent_expression_p, but it also works while not processing
19513    a template definition, i.e. during substitution or mangling.  */
19514
19515 bool
19516 type_dependent_expression_p_push (tree expr)
19517 {
19518   bool b;
19519   ++processing_template_decl;
19520   b = type_dependent_expression_p (expr);
19521   --processing_template_decl;
19522   return b;
19523 }
19524
19525 /* Returns TRUE if ARGS contains a type-dependent expression.  */
19526
19527 bool
19528 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
19529 {
19530   unsigned int i;
19531   tree arg;
19532
19533   FOR_EACH_VEC_ELT (tree, args, i, arg)
19534     {
19535       if (type_dependent_expression_p (arg))
19536         return true;
19537     }
19538   return false;
19539 }
19540
19541 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19542    expressions) contains any type-dependent expressions.  */
19543
19544 bool
19545 any_type_dependent_elements_p (const_tree list)
19546 {
19547   for (; list; list = TREE_CHAIN (list))
19548     if (value_dependent_expression_p (TREE_VALUE (list)))
19549       return true;
19550
19551   return false;
19552 }
19553
19554 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
19555    expressions) contains any value-dependent expressions.  */
19556
19557 bool
19558 any_value_dependent_elements_p (const_tree list)
19559 {
19560   for (; list; list = TREE_CHAIN (list))
19561     if (value_dependent_expression_p (TREE_VALUE (list)))
19562       return true;
19563
19564   return false;
19565 }
19566
19567 /* Returns TRUE if the ARG (a template argument) is dependent.  */
19568
19569 bool
19570 dependent_template_arg_p (tree arg)
19571 {
19572   if (!processing_template_decl)
19573     return false;
19574
19575   /* Assume a template argument that was wrongly written by the user
19576      is dependent. This is consistent with what
19577      any_dependent_template_arguments_p [that calls this function]
19578      does.  */
19579   if (!arg || arg == error_mark_node)
19580     return true;
19581
19582   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
19583     arg = ARGUMENT_PACK_SELECT_ARG (arg);
19584
19585   if (TREE_CODE (arg) == TEMPLATE_DECL
19586       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19587     return dependent_template_p (arg);
19588   else if (ARGUMENT_PACK_P (arg))
19589     {
19590       tree args = ARGUMENT_PACK_ARGS (arg);
19591       int i, len = TREE_VEC_LENGTH (args);
19592       for (i = 0; i < len; ++i)
19593         {
19594           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19595             return true;
19596         }
19597
19598       return false;
19599     }
19600   else if (TYPE_P (arg))
19601     return dependent_type_p (arg);
19602   else
19603     return (type_dependent_expression_p (arg)
19604             || value_dependent_expression_p (arg));
19605 }
19606
19607 /* Returns true if ARGS (a collection of template arguments) contains
19608    any types that require structural equality testing.  */
19609
19610 bool
19611 any_template_arguments_need_structural_equality_p (tree args)
19612 {
19613   int i;
19614   int j;
19615
19616   if (!args)
19617     return false;
19618   if (args == error_mark_node)
19619     return true;
19620
19621   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19622     {
19623       tree level = TMPL_ARGS_LEVEL (args, i + 1);
19624       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19625         {
19626           tree arg = TREE_VEC_ELT (level, j);
19627           tree packed_args = NULL_TREE;
19628           int k, len = 1;
19629
19630           if (ARGUMENT_PACK_P (arg))
19631             {
19632               /* Look inside the argument pack.  */
19633               packed_args = ARGUMENT_PACK_ARGS (arg);
19634               len = TREE_VEC_LENGTH (packed_args);
19635             }
19636
19637           for (k = 0; k < len; ++k)
19638             {
19639               if (packed_args)
19640                 arg = TREE_VEC_ELT (packed_args, k);
19641
19642               if (error_operand_p (arg))
19643                 return true;
19644               else if (TREE_CODE (arg) == TEMPLATE_DECL
19645                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
19646                 continue;
19647               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
19648                 return true;
19649               else if (!TYPE_P (arg) && TREE_TYPE (arg)
19650                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
19651                 return true;
19652             }
19653         }
19654     }
19655
19656   return false;
19657 }
19658
19659 /* Returns true if ARGS (a collection of template arguments) contains
19660    any dependent arguments.  */
19661
19662 bool
19663 any_dependent_template_arguments_p (const_tree args)
19664 {
19665   int i;
19666   int j;
19667
19668   if (!args)
19669     return false;
19670   if (args == error_mark_node)
19671     return true;
19672
19673   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
19674     {
19675       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
19676       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
19677         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
19678           return true;
19679     }
19680
19681   return false;
19682 }
19683
19684 /* Returns TRUE if the template TMPL is dependent.  */
19685
19686 bool
19687 dependent_template_p (tree tmpl)
19688 {
19689   if (TREE_CODE (tmpl) == OVERLOAD)
19690     {
19691       while (tmpl)
19692         {
19693           if (dependent_template_p (OVL_CURRENT (tmpl)))
19694             return true;
19695           tmpl = OVL_NEXT (tmpl);
19696         }
19697       return false;
19698     }
19699
19700   /* Template template parameters are dependent.  */
19701   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
19702       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
19703     return true;
19704   /* So are names that have not been looked up.  */
19705   if (TREE_CODE (tmpl) == SCOPE_REF
19706       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
19707     return true;
19708   /* So are member templates of dependent classes.  */
19709   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
19710     return dependent_type_p (DECL_CONTEXT (tmpl));
19711   return false;
19712 }
19713
19714 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
19715
19716 bool
19717 dependent_template_id_p (tree tmpl, tree args)
19718 {
19719   return (dependent_template_p (tmpl)
19720           || any_dependent_template_arguments_p (args));
19721 }
19722
19723 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
19724    is dependent.  */
19725
19726 bool
19727 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
19728 {
19729   int i;
19730
19731   if (!processing_template_decl)
19732     return false;
19733
19734   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
19735     {
19736       tree decl = TREE_VEC_ELT (declv, i);
19737       tree init = TREE_VEC_ELT (initv, i);
19738       tree cond = TREE_VEC_ELT (condv, i);
19739       tree incr = TREE_VEC_ELT (incrv, i);
19740
19741       if (type_dependent_expression_p (decl))
19742         return true;
19743
19744       if (init && type_dependent_expression_p (init))
19745         return true;
19746
19747       if (type_dependent_expression_p (cond))
19748         return true;
19749
19750       if (COMPARISON_CLASS_P (cond)
19751           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
19752               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
19753         return true;
19754
19755       if (TREE_CODE (incr) == MODOP_EXPR)
19756         {
19757           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
19758               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
19759             return true;
19760         }
19761       else if (type_dependent_expression_p (incr))
19762         return true;
19763       else if (TREE_CODE (incr) == MODIFY_EXPR)
19764         {
19765           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
19766             return true;
19767           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
19768             {
19769               tree t = TREE_OPERAND (incr, 1);
19770               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
19771                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
19772                 return true;
19773             }
19774         }
19775     }
19776
19777   return false;
19778 }
19779
19780 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
19781    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
19782    no such TYPE can be found.  Note that this function peers inside
19783    uninstantiated templates and therefore should be used only in
19784    extremely limited situations.  ONLY_CURRENT_P restricts this
19785    peering to the currently open classes hierarchy (which is required
19786    when comparing types).  */
19787
19788 tree
19789 resolve_typename_type (tree type, bool only_current_p)
19790 {
19791   tree scope;
19792   tree name;
19793   tree decl;
19794   int quals;
19795   tree pushed_scope;
19796   tree result;
19797
19798   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
19799
19800   scope = TYPE_CONTEXT (type);
19801   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
19802      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
19803      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
19804      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
19805      identifier  of the TYPENAME_TYPE anymore.
19806      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
19807      TYPENAME_TYPE instead, we avoid messing up with a possible
19808      typedef variant case.  */
19809   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
19810
19811   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
19812      it first before we can figure out what NAME refers to.  */
19813   if (TREE_CODE (scope) == TYPENAME_TYPE)
19814     {
19815       if (TYPENAME_IS_RESOLVING_P (scope))
19816         /* Given a class template A with a dependent base with nested type C,
19817            typedef typename A::C::C C will land us here, as trying to resolve
19818            the initial A::C leads to the local C typedef, which leads back to
19819            A::C::C.  So we break the recursion now.  */
19820         return type;
19821       else
19822         scope = resolve_typename_type (scope, only_current_p);
19823     }
19824   /* If we don't know what SCOPE refers to, then we cannot resolve the
19825      TYPENAME_TYPE.  */
19826   if (TREE_CODE (scope) == TYPENAME_TYPE)
19827     return type;
19828   /* If the SCOPE is a template type parameter, we have no way of
19829      resolving the name.  */
19830   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
19831     return type;
19832   /* If the SCOPE is not the current instantiation, there's no reason
19833      to look inside it.  */
19834   if (only_current_p && !currently_open_class (scope))
19835     return type;
19836   /* If this is a typedef, we don't want to look inside (c++/11987).  */
19837   if (typedef_variant_p (type))
19838     return type;
19839   /* If SCOPE isn't the template itself, it will not have a valid
19840      TYPE_FIELDS list.  */
19841   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
19842     /* scope is either the template itself or a compatible instantiation
19843        like X<T>, so look up the name in the original template.  */
19844     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
19845   else
19846     /* scope is a partial instantiation, so we can't do the lookup or we
19847        will lose the template arguments.  */
19848     return type;
19849   /* Enter the SCOPE so that name lookup will be resolved as if we
19850      were in the class definition.  In particular, SCOPE will no
19851      longer be considered a dependent type.  */
19852   pushed_scope = push_scope (scope);
19853   /* Look up the declaration.  */
19854   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
19855                         tf_warning_or_error);
19856
19857   result = NULL_TREE;
19858   
19859   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
19860      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
19861   if (!decl)
19862     /*nop*/;
19863   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
19864            && TREE_CODE (decl) == TYPE_DECL)
19865     {
19866       result = TREE_TYPE (decl);
19867       if (result == error_mark_node)
19868         result = NULL_TREE;
19869     }
19870   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
19871            && DECL_CLASS_TEMPLATE_P (decl))
19872     {
19873       tree tmpl;
19874       tree args;
19875       /* Obtain the template and the arguments.  */
19876       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
19877       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
19878       /* Instantiate the template.  */
19879       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
19880                                       /*entering_scope=*/0,
19881                                       tf_error | tf_user);
19882       if (result == error_mark_node)
19883         result = NULL_TREE;
19884     }
19885   
19886   /* Leave the SCOPE.  */
19887   if (pushed_scope)
19888     pop_scope (pushed_scope);
19889
19890   /* If we failed to resolve it, return the original typename.  */
19891   if (!result)
19892     return type;
19893   
19894   /* If lookup found a typename type, resolve that too.  */
19895   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
19896     {
19897       /* Ill-formed programs can cause infinite recursion here, so we
19898          must catch that.  */
19899       TYPENAME_IS_RESOLVING_P (type) = 1;
19900       result = resolve_typename_type (result, only_current_p);
19901       TYPENAME_IS_RESOLVING_P (type) = 0;
19902     }
19903   
19904   /* Qualify the resulting type.  */
19905   quals = cp_type_quals (type);
19906   if (quals)
19907     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
19908
19909   return result;
19910 }
19911
19912 /* EXPR is an expression which is not type-dependent.  Return a proxy
19913    for EXPR that can be used to compute the types of larger
19914    expressions containing EXPR.  */
19915
19916 tree
19917 build_non_dependent_expr (tree expr)
19918 {
19919   tree inner_expr;
19920
19921 #ifdef ENABLE_CHECKING
19922   /* Try to get a constant value for all non-type-dependent expressions in
19923       order to expose bugs in *_dependent_expression_p and constexpr.  */
19924   if (cxx_dialect >= cxx0x)
19925     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
19926 #endif
19927
19928   /* Preserve OVERLOADs; the functions must be available to resolve
19929      types.  */
19930   inner_expr = expr;
19931   if (TREE_CODE (inner_expr) == STMT_EXPR)
19932     inner_expr = stmt_expr_value_expr (inner_expr);
19933   if (TREE_CODE (inner_expr) == ADDR_EXPR)
19934     inner_expr = TREE_OPERAND (inner_expr, 0);
19935   if (TREE_CODE (inner_expr) == COMPONENT_REF)
19936     inner_expr = TREE_OPERAND (inner_expr, 1);
19937   if (is_overloaded_fn (inner_expr)
19938       || TREE_CODE (inner_expr) == OFFSET_REF)
19939     return expr;
19940   /* There is no need to return a proxy for a variable.  */
19941   if (TREE_CODE (expr) == VAR_DECL)
19942     return expr;
19943   /* Preserve string constants; conversions from string constants to
19944      "char *" are allowed, even though normally a "const char *"
19945      cannot be used to initialize a "char *".  */
19946   if (TREE_CODE (expr) == STRING_CST)
19947     return expr;
19948   /* Preserve arithmetic constants, as an optimization -- there is no
19949      reason to create a new node.  */
19950   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
19951     return expr;
19952   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
19953      There is at least one place where we want to know that a
19954      particular expression is a throw-expression: when checking a ?:
19955      expression, there are special rules if the second or third
19956      argument is a throw-expression.  */
19957   if (TREE_CODE (expr) == THROW_EXPR)
19958     return expr;
19959
19960   /* Don't wrap an initializer list, we need to be able to look inside.  */
19961   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
19962     return expr;
19963
19964   if (TREE_CODE (expr) == COND_EXPR)
19965     return build3 (COND_EXPR,
19966                    TREE_TYPE (expr),
19967                    TREE_OPERAND (expr, 0),
19968                    (TREE_OPERAND (expr, 1)
19969                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
19970                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
19971                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
19972   if (TREE_CODE (expr) == COMPOUND_EXPR
19973       && !COMPOUND_EXPR_OVERLOADED (expr))
19974     return build2 (COMPOUND_EXPR,
19975                    TREE_TYPE (expr),
19976                    TREE_OPERAND (expr, 0),
19977                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
19978
19979   /* If the type is unknown, it can't really be non-dependent */
19980   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
19981
19982   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
19983   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
19984 }
19985
19986 /* ARGS is a vector of expressions as arguments to a function call.
19987    Replace the arguments with equivalent non-dependent expressions.
19988    This modifies ARGS in place.  */
19989
19990 void
19991 make_args_non_dependent (VEC(tree,gc) *args)
19992 {
19993   unsigned int ix;
19994   tree arg;
19995
19996   FOR_EACH_VEC_ELT (tree, args, ix, arg)
19997     {
19998       tree newarg = build_non_dependent_expr (arg);
19999       if (newarg != arg)
20000         VEC_replace (tree, args, ix, newarg);
20001     }
20002 }
20003
20004 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
20005    with a level one deeper than the actual template parms.  */
20006
20007 tree
20008 make_auto (void)
20009 {
20010   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
20011   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
20012                                TYPE_DECL, get_identifier ("auto"), au);
20013   TYPE_STUB_DECL (au) = TYPE_NAME (au);
20014   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
20015     (0, processing_template_decl + 1, processing_template_decl + 1,
20016      TYPE_NAME (au), NULL_TREE);
20017   TYPE_CANONICAL (au) = canonical_type_parameter (au);
20018   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
20019   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
20020
20021   return au;
20022 }
20023
20024 /* Given type ARG, return std::initializer_list<ARG>.  */
20025
20026 static tree
20027 listify (tree arg)
20028 {
20029   tree std_init_list = namespace_binding
20030     (get_identifier ("initializer_list"), std_node);
20031   tree argvec;
20032   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
20033     {    
20034       error ("deducing from brace-enclosed initializer list requires "
20035              "#include <initializer_list>");
20036       return error_mark_node;
20037     }
20038   argvec = make_tree_vec (1);
20039   TREE_VEC_ELT (argvec, 0) = arg;
20040   return lookup_template_class (std_init_list, argvec, NULL_TREE,
20041                                 NULL_TREE, 0, tf_warning_or_error);
20042 }
20043
20044 /* Replace auto in TYPE with std::initializer_list<auto>.  */
20045
20046 static tree
20047 listify_autos (tree type, tree auto_node)
20048 {
20049   tree init_auto = listify (auto_node);
20050   tree argvec = make_tree_vec (1);
20051   TREE_VEC_ELT (argvec, 0) = init_auto;
20052   if (processing_template_decl)
20053     argvec = add_to_template_args (current_template_args (), argvec);
20054   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20055 }
20056
20057 /* walk_tree helper for do_auto_deduction.  */
20058
20059 static tree
20060 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
20061                  void *type)
20062 {
20063   /* Is this a variable with the type we're looking for?  */
20064   if (DECL_P (*tp)
20065       && TREE_TYPE (*tp) == type)
20066     return *tp;
20067   else
20068     return NULL_TREE;
20069 }
20070
20071 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
20072    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
20073
20074 tree
20075 do_auto_deduction (tree type, tree init, tree auto_node)
20076 {
20077   tree parms, tparms, targs;
20078   tree args[1];
20079   tree decl;
20080   int val;
20081
20082   if (type_dependent_expression_p (init))
20083     /* Defining a subset of type-dependent expressions that we can deduce
20084        from ahead of time isn't worth the trouble.  */
20085     return type;
20086
20087   /* The name of the object being declared shall not appear in the
20088      initializer expression.  */
20089   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
20090   if (decl)
20091     {
20092       error ("variable %q#D with %<auto%> type used in its own "
20093              "initializer", decl);
20094       return error_mark_node;
20095     }
20096
20097   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
20098      with either a new invented type template parameter U or, if the
20099      initializer is a braced-init-list (8.5.4), with
20100      std::initializer_list<U>.  */
20101   if (BRACE_ENCLOSED_INITIALIZER_P (init))
20102     type = listify_autos (type, auto_node);
20103
20104   init = resolve_nondeduced_context (init);
20105
20106   parms = build_tree_list (NULL_TREE, type);
20107   args[0] = init;
20108   tparms = make_tree_vec (1);
20109   targs = make_tree_vec (1);
20110   TREE_VEC_ELT (tparms, 0)
20111     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
20112   val = type_unification_real (tparms, targs, parms, args, 1, 0,
20113                                DEDUCE_CALL, LOOKUP_NORMAL,
20114                                /*explain_p=*/false);
20115   if (val > 0)
20116     {
20117       if (processing_template_decl)
20118         /* Try again at instantiation time.  */
20119         return type;
20120       if (type && type != error_mark_node)
20121         /* If type is error_mark_node a diagnostic must have been
20122            emitted by now.  Also, having a mention to '<type error>'
20123            in the diagnostic is not really useful to the user.  */
20124         error ("unable to deduce %qT from %qE", type, init);
20125       return error_mark_node;
20126     }
20127
20128   /* If the list of declarators contains more than one declarator, the type
20129      of each declared variable is determined as described above. If the
20130      type deduced for the template parameter U is not the same in each
20131      deduction, the program is ill-formed.  */
20132   if (TREE_TYPE (auto_node)
20133       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
20134     {
20135       error ("inconsistent deduction for %qT: %qT and then %qT",
20136              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
20137       return error_mark_node;
20138     }
20139   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
20140
20141   if (processing_template_decl)
20142     targs = add_to_template_args (current_template_args (), targs);
20143   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
20144 }
20145
20146 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
20147    result.  */
20148
20149 tree
20150 splice_late_return_type (tree type, tree late_return_type)
20151 {
20152   tree argvec;
20153
20154   if (late_return_type == NULL_TREE)
20155     return type;
20156   argvec = make_tree_vec (1);
20157   TREE_VEC_ELT (argvec, 0) = late_return_type;
20158   if (processing_template_parmlist)
20159     /* For a late-specified return type in a template type-parameter, we
20160        need to add a dummy argument level for its parmlist.  */
20161     argvec = add_to_template_args
20162       (make_tree_vec (processing_template_parmlist), argvec);
20163   if (current_template_parms)
20164     argvec = add_to_template_args (current_template_args (), argvec);
20165   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20166 }
20167
20168 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
20169
20170 bool
20171 is_auto (const_tree type)
20172 {
20173   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20174       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
20175     return true;
20176   else
20177     return false;
20178 }
20179
20180 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
20181    appear as a type-specifier for the declaration in question, we don't
20182    have to look through the whole type.  */
20183
20184 tree
20185 type_uses_auto (tree type)
20186 {
20187   enum tree_code code;
20188   if (is_auto (type))
20189     return type;
20190
20191   code = TREE_CODE (type);
20192
20193   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20194       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20195       || code == METHOD_TYPE || code == ARRAY_TYPE)
20196     return type_uses_auto (TREE_TYPE (type));
20197
20198   if (TYPE_PTRMEMFUNC_P (type))
20199     return type_uses_auto (TREE_TYPE (TREE_TYPE
20200                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20201
20202   return NULL_TREE;
20203 }
20204
20205 /* For a given template T, return the vector of typedefs referenced
20206    in T for which access check is needed at T instantiation time.
20207    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20208    Those typedefs were added to T by the function
20209    append_type_to_template_for_access_check.  */
20210
20211 VEC(qualified_typedef_usage_t,gc)*
20212 get_types_needing_access_check (tree t)
20213 {
20214   tree ti;
20215   VEC(qualified_typedef_usage_t,gc) *result = NULL;
20216
20217   if (!t || t == error_mark_node)
20218     return NULL;
20219
20220   if (!(ti = get_template_info (t)))
20221     return NULL;
20222
20223   if (CLASS_TYPE_P (t)
20224       || TREE_CODE (t) == FUNCTION_DECL)
20225     {
20226       if (!TI_TEMPLATE (ti))
20227         return NULL;
20228
20229       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20230     }
20231
20232   return result;
20233 }
20234
20235 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20236    tied to T. That list of typedefs will be access checked at
20237    T instantiation time.
20238    T is either a FUNCTION_DECL or a RECORD_TYPE.
20239    TYPE_DECL is a TYPE_DECL node representing a typedef.
20240    SCOPE is the scope through which TYPE_DECL is accessed.
20241    LOCATION is the location of the usage point of TYPE_DECL.
20242
20243    This function is a subroutine of
20244    append_type_to_template_for_access_check.  */
20245
20246 static void
20247 append_type_to_template_for_access_check_1 (tree t,
20248                                             tree type_decl,
20249                                             tree scope,
20250                                             location_t location)
20251 {
20252   qualified_typedef_usage_t typedef_usage;
20253   tree ti;
20254
20255   if (!t || t == error_mark_node)
20256     return;
20257
20258   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20259                || CLASS_TYPE_P (t))
20260               && type_decl
20261               && TREE_CODE (type_decl) == TYPE_DECL
20262               && scope);
20263
20264   if (!(ti = get_template_info (t)))
20265     return;
20266
20267   gcc_assert (TI_TEMPLATE (ti));
20268
20269   typedef_usage.typedef_decl = type_decl;
20270   typedef_usage.context = scope;
20271   typedef_usage.locus = location;
20272
20273   VEC_safe_push (qualified_typedef_usage_t, gc,
20274                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
20275                  &typedef_usage);
20276 }
20277
20278 /* Append TYPE_DECL to the template TEMPL.
20279    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20280    At TEMPL instanciation time, TYPE_DECL will be checked to see
20281    if it can be accessed through SCOPE.
20282    LOCATION is the location of the usage point of TYPE_DECL.
20283
20284    e.g. consider the following code snippet:
20285
20286      class C
20287      {
20288        typedef int myint;
20289      };
20290
20291      template<class U> struct S
20292      {
20293        C::myint mi; // <-- usage point of the typedef C::myint
20294      };
20295
20296      S<char> s;
20297
20298    At S<char> instantiation time, we need to check the access of C::myint
20299    In other words, we need to check the access of the myint typedef through
20300    the C scope. For that purpose, this function will add the myint typedef
20301    and the scope C through which its being accessed to a list of typedefs
20302    tied to the template S. That list will be walked at template instantiation
20303    time and access check performed on each typedefs it contains.
20304    Note that this particular code snippet should yield an error because
20305    myint is private to C.  */
20306
20307 void
20308 append_type_to_template_for_access_check (tree templ,
20309                                           tree type_decl,
20310                                           tree scope,
20311                                           location_t location)
20312 {
20313   qualified_typedef_usage_t *iter;
20314   int i;
20315
20316   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20317
20318   /* Make sure we don't append the type to the template twice.  */
20319   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
20320                     get_types_needing_access_check (templ),
20321                     i, iter)
20322     if (iter->typedef_decl == type_decl && scope == iter->context)
20323       return;
20324
20325   append_type_to_template_for_access_check_1 (templ, type_decl,
20326                                               scope, location);
20327 }
20328
20329 /* Set up the hash tables for template instantiations.  */
20330
20331 void
20332 init_template_processing (void)
20333 {
20334   decl_specializations = htab_create_ggc (37,
20335                                           hash_specialization,
20336                                           eq_specializations,
20337                                           ggc_free);
20338   type_specializations = htab_create_ggc (37,
20339                                           hash_specialization,
20340                                           eq_specializations,
20341                                           ggc_free);
20342 }
20343
20344 /* Print stats about the template hash tables for -fstats.  */
20345
20346 void
20347 print_template_statistics (void)
20348 {
20349   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20350            "%f collisions\n", (long) htab_size (decl_specializations),
20351            (long) htab_elements (decl_specializations),
20352            htab_collisions (decl_specializations));
20353   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20354            "%f collisions\n", (long) htab_size (type_specializations),
20355            (long) htab_elements (type_specializations),
20356            htab_collisions (type_specializations));
20357 }
20358
20359 #include "gt-cp-pt.h"